dsh-agent-enhancer 0.3.11 → 0.3.13

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 (90) hide show
  1. package/README.en.md +12 -11
  2. package/README.md +12 -11
  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/dsh/settings-about.d.ts +0 -3
  8. package/lib/client/dsh/settings-about.d.ts.map +1 -1
  9. package/lib/client/dsh/settings.d.ts +0 -3
  10. package/lib/client/dsh/settings.d.ts.map +1 -1
  11. package/lib/client/index.d.ts.map +1 -1
  12. package/lib/client/locales.d.ts +93 -55
  13. package/lib/client/locales.d.ts.map +1 -1
  14. package/lib/client/mcp-connectors/remote.d.ts +7 -1
  15. package/lib/client/mcp-connectors/remote.d.ts.map +1 -1
  16. package/lib/client/mcp-connectors/tab.d.ts.map +1 -1
  17. package/lib/client/quote/position.d.ts +8 -6
  18. package/lib/client/quote/position.d.ts.map +1 -1
  19. package/lib/client/remote.d.ts +4 -8
  20. package/lib/client/remote.d.ts.map +1 -1
  21. package/lib/client/soft-pause/action.d.ts.map +1 -1
  22. package/lib/client/web-chat-bridge/capture.d.ts +2 -0
  23. package/lib/client/web-chat-bridge/capture.d.ts.map +1 -1
  24. package/lib/client/web-chat-bridge/dom-to-markdown.d.ts +13 -0
  25. package/lib/client/web-chat-bridge/dom-to-markdown.d.ts.map +1 -0
  26. package/lib/client/web-chat-bridge/panel.d.ts.map +1 -1
  27. package/lib/client/web-chat-bridge/preview.d.ts.map +1 -1
  28. package/lib/client/web-chat-bridge/remote.d.ts.map +1 -1
  29. package/lib/client/web-chat-bridge/share-fetch.d.ts +15 -0
  30. package/lib/client/web-chat-bridge/share-fetch.d.ts.map +1 -1
  31. package/lib/client.js +1881 -1567
  32. package/lib/client.js.map +1 -1
  33. package/lib/errors.d.ts +1 -1
  34. package/lib/errors.d.ts.map +1 -1
  35. package/lib/host/auto-route/errors.d.ts +8 -0
  36. package/lib/host/auto-route/errors.d.ts.map +1 -0
  37. package/lib/host/auto-route/router.d.ts.map +1 -1
  38. package/lib/host/auto-route/session-hook.d.ts.map +1 -1
  39. package/lib/host/browser-agent/driver.d.ts +3 -1
  40. package/lib/host/browser-agent/driver.d.ts.map +1 -1
  41. package/lib/host/browser-agent/install.d.ts +17 -0
  42. package/lib/host/browser-agent/install.d.ts.map +1 -1
  43. package/lib/host/browser-agent/playwright-driver.d.ts +3 -1
  44. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  45. package/lib/host/browser-agent/prompt.d.ts.map +1 -1
  46. package/lib/host/browser-agent/tools.d.ts.map +1 -1
  47. package/lib/host/context-compact.d.ts.map +1 -1
  48. package/lib/host/index.d.ts +5 -6
  49. package/lib/host/index.d.ts.map +1 -1
  50. package/lib/host/mcp-connectors/io.d.ts +3 -1
  51. package/lib/host/mcp-connectors/io.d.ts.map +1 -1
  52. package/lib/host/mcp-connectors/probe-message.d.ts +7 -0
  53. package/lib/host/mcp-connectors/probe-message.d.ts.map +1 -0
  54. package/lib/host/mcp-connectors/runtime.d.ts +11 -0
  55. package/lib/host/mcp-connectors/runtime.d.ts.map +1 -1
  56. package/lib/host/mcp-connectors/status.d.ts +32 -0
  57. package/lib/host/mcp-connectors/status.d.ts.map +1 -0
  58. package/lib/host/mcp-connectors/types.d.ts +33 -0
  59. package/lib/host/mcp-connectors/types.d.ts.map +1 -1
  60. package/lib/host/model.d.ts.map +1 -1
  61. package/lib/host/rpc.d.ts +625 -36
  62. package/lib/host/rpc.d.ts.map +1 -1
  63. package/lib/host/web-chat-bridge/convert-conversation.d.ts +38 -0
  64. package/lib/host/web-chat-bridge/convert-conversation.d.ts.map +1 -0
  65. package/lib/host/web-chat-bridge/fragments.d.ts +72 -0
  66. package/lib/host/web-chat-bridge/fragments.d.ts.map +1 -0
  67. package/lib/host/web-chat-bridge/import-session.d.ts +12 -2
  68. package/lib/host/web-chat-bridge/import-session.d.ts.map +1 -1
  69. package/lib/host/web-chat-bridge/share-link.d.ts +1 -0
  70. package/lib/host/web-chat-bridge/share-link.d.ts.map +1 -1
  71. package/lib/host/web-chat-bridge/types.d.ts +9 -0
  72. package/lib/host/web-chat-bridge/types.d.ts.map +1 -1
  73. package/lib/identity.d.ts +1 -1
  74. package/lib/index.js +1442 -590
  75. package/lib/index.js.map +4 -4
  76. package/package.json +60 -56
  77. package/lib/client/dsh/settings-update.d.ts +0 -9
  78. package/lib/client/dsh/settings-update.d.ts.map +0 -1
  79. package/lib/host/update/check.d.ts +0 -32
  80. package/lib/host/update/check.d.ts.map +0 -1
  81. package/lib/host/update/cli.d.ts +0 -41
  82. package/lib/host/update/cli.d.ts.map +0 -1
  83. package/lib/host/update/install-kind.d.ts +0 -3
  84. package/lib/host/update/install-kind.d.ts.map +0 -1
  85. package/lib/host/update/registry.d.ts +0 -16
  86. package/lib/host/update/registry.d.ts.map +0 -1
  87. package/lib/host/update/semver.d.ts +0 -2
  88. package/lib/host/update/semver.d.ts.map +0 -1
  89. package/lib/host/update/types.d.ts +0 -17
  90. package/lib/host/update/types.d.ts.map +0 -1
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";
3
- import { homedir as homedir7 } from "node:os";
4
- import { join as join33 } from "node:path";
2
+ import { existsSync as existsSync20, mkdirSync as mkdirSync12, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
+ import { homedir as homedir5 } from "node:os";
4
+ import { join as join30 } 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
@@ -6496,8 +6613,8 @@ async function deleteSessionNow(options) {
6496
6613
  }
6497
6614
 
6498
6615
  // src/host/web-chat-bridge/import-session.ts
6499
- import { randomUUID as randomUUID6 } from "node:crypto";
6500
- import { existsSync as existsSync5, statSync } from "node:fs";
6616
+ import { randomUUID as randomUUID7 } from "node:crypto";
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 {
@@ -6507,7 +6624,7 @@ import {
6507
6624
  } from "@deepseek-ai/dsh-llm";
6508
6625
  import {
6509
6626
  SessionId,
6510
- SessionSeq as SessionSeq2
6627
+ SessionSeq as SessionSeq3
6511
6628
  } from "@deepseek-ai/dsh-session";
6512
6629
 
6513
6630
  // src/host/extra-folders/pick.ts
@@ -6738,6 +6855,413 @@ async function pickFileNow(signal, options = {}) {
6738
6855
  );
6739
6856
  }
6740
6857
 
6858
+ // src/host/web-chat-bridge/convert-conversation.ts
6859
+ import { randomUUID as randomUUID6 } from "node:crypto";
6860
+ import {
6861
+ MessageId as MessageId2,
6862
+ ToolCallId
6863
+ } from "@deepseek-ai/dsh-llm";
6864
+ import { SessionSeq as SessionSeq2 } from "@deepseek-ai/dsh-session";
6865
+ import {
6866
+ fetchMetaFromValue,
6867
+ formatFetchOutput,
6868
+ formatSearchOutput,
6869
+ searchMetaFromValue
6870
+ } from "@deepseek-ai/dsh-tool-web";
6871
+ var WEB_CHAT_IMPORTED_MODEL_SOURCE = {
6872
+ provider: "web-chat-bridge",
6873
+ model: "imported-history"
6874
+ };
6875
+ var FETCH_OUTPUT_CHARS = 4e3;
6876
+ var UNFINISHED_STATUS_CODES = /* @__PURE__ */ new Map([
6877
+ ["FAILED", "DEEPSEEK_EXPORT_FAILED"],
6878
+ ["TIMEOUT", "DEEPSEEK_EXPORT_TIMEOUT"],
6879
+ ["CONTEXT_LENGTH_EXCEEDED", "DEEPSEEK_EXPORT_CONTEXT_LENGTH_EXCEEDED"],
6880
+ ["INCOMPLETE", "DEEPSEEK_EXPORT_INCOMPLETE"],
6881
+ ["WIP", "DEEPSEEK_EXPORT_WIP"]
6882
+ ]);
6883
+ var WebChatConvertError = class extends Error {
6884
+ name = "WebChatConvertError";
6885
+ };
6886
+ function nonEmpty(value) {
6887
+ return value === null || value === void 0 || value.trim().length === 0 ? void 0 : value;
6888
+ }
6889
+ function selectWebChatBranch(messages, currentMessageId) {
6890
+ if (messages.length === 0) {
6891
+ throw new WebChatConvertError("conversation has no messages");
6892
+ }
6893
+ const ids = new Set(messages.map((message) => message.id));
6894
+ const resolved = messages.map((message) => {
6895
+ if (message.parent_id === null || ids.has(message.parent_id)) return message;
6896
+ return { ...message, parent_id: null };
6897
+ });
6898
+ const hasParents = resolved.some((message) => message.parent_id !== null);
6899
+ if (!hasParents) return resolved;
6900
+ const byId = /* @__PURE__ */ new Map();
6901
+ let newest;
6902
+ for (const message of resolved) {
6903
+ if (byId.has(message.id)) {
6904
+ return resolved;
6905
+ }
6906
+ byId.set(message.id, message);
6907
+ if (newest === void 0 || message.id > newest.id) newest = message;
6908
+ }
6909
+ if (newest === void 0) {
6910
+ throw new WebChatConvertError("conversation has no messages");
6911
+ }
6912
+ const selected = currentMessageId === null || currentMessageId === void 0 ? void 0 : byId.get(currentMessageId);
6913
+ const chain = [];
6914
+ for (let message = selected ?? newest; ; ) {
6915
+ if (chain.length === byId.size) {
6916
+ return resolved;
6917
+ }
6918
+ chain.push(message);
6919
+ if (message.parent_id === null) return chain.reverse();
6920
+ const parent = byId.get(message.parent_id);
6921
+ if (parent === void 0) return resolved;
6922
+ message = parent;
6923
+ }
6924
+ }
6925
+ function convertWebChatConversation(input, options = {}) {
6926
+ const createId = options.createId ?? (() => randomUUID6());
6927
+ const chain = selectWebChatBranch(input.messages, input.currentMessageId);
6928
+ const log = new LogBuilder(createId, options.provenancePrefix ?? "");
6929
+ const title = input.title !== null && input.title.trim() !== "" ? input.title.trim() : null;
6930
+ let turn = 0;
6931
+ let withdrawn = 0;
6932
+ for (let index = 0; index < chain.length; index++) {
6933
+ const user = chain[index];
6934
+ if (user.role !== "USER") continue;
6935
+ const next = chain[index + 1];
6936
+ const reply = next?.role === "ASSISTANT" ? next : void 0;
6937
+ if (reply !== void 0) index++;
6938
+ if (reply?.status === "CONTENT_FILTER") {
6939
+ withdrawn++;
6940
+ continue;
6941
+ }
6942
+ turn++;
6943
+ log.turn(turn, user, reply);
6944
+ if (turn === 1 && title !== null) {
6945
+ log.add({
6946
+ type: "session/title",
6947
+ data: { title, messageSeqs: [], source: { kind: "user" } }
6948
+ });
6949
+ }
6950
+ }
6951
+ if (turn === 0) {
6952
+ throw new WebChatConvertError(
6953
+ withdrawn === 0 ? "conversation has no user message" : "every question of the conversation was withdrawn by content filtering"
6954
+ );
6955
+ }
6956
+ return { title, events: log.events };
6957
+ }
6958
+ var LogBuilder = class {
6959
+ constructor(createId, provenancePrefix) {
6960
+ this.createId = createId;
6961
+ this.provenancePrefix = provenancePrefix;
6962
+ }
6963
+ createId;
6964
+ provenancePrefix;
6965
+ events = [];
6966
+ time = Date.now();
6967
+ add(event) {
6968
+ const seq = SessionSeq2(this.events.length);
6969
+ this.events.push({ ...event, seq, time: this.time });
6970
+ return seq;
6971
+ }
6972
+ turn(turn, user, reply) {
6973
+ this.add({ type: "turn/start", data: { turn } });
6974
+ let step = 1;
6975
+ this.add({ type: "step/start", data: { turn, step } });
6976
+ if (turn === 1) {
6977
+ const head = {
6978
+ id: MessageId2(this.id()),
6979
+ role: "system",
6980
+ content: [],
6981
+ source: { kind: "system-prompt" }
6982
+ };
6983
+ this.add({
6984
+ type: "system/message",
6985
+ data: { turn, step, message: head },
6986
+ surfaceOp: "append"
6987
+ });
6988
+ }
6989
+ this.add({
6990
+ type: "user/message",
6991
+ data: this.userMessage(user, turn === 1),
6992
+ surfaceOp: "append"
6993
+ });
6994
+ if (reply === void 0) {
6995
+ this.closeTurn(turn, step, failure(
6996
+ "DEEPSEEK_EXPORT_NO_REPLY",
6997
+ "The export contains no reply to this message."
6998
+ ));
6999
+ return;
7000
+ }
7001
+ const { steps, template } = this.replySteps(reply);
7002
+ const excluded = excludedReply(reply, template, steps.length);
7003
+ if (excluded !== void 0) {
7004
+ this.closeTurn(turn, step, { kind: "error", error: excluded });
7005
+ return;
7006
+ }
7007
+ for (const [position, { content, calls, elapsedMs }] of steps.entries()) {
7008
+ if (position > 0) {
7009
+ step++;
7010
+ this.add({ type: "step/start", data: { turn, step } });
7011
+ }
7012
+ this.time += elapsedMs;
7013
+ this.add({
7014
+ type: "assistant/message",
7015
+ data: {
7016
+ turn,
7017
+ step,
7018
+ message: assistantMessage(this.id(), [
7019
+ ...content,
7020
+ ...calls.map((call) => call.block)
7021
+ ]),
7022
+ stream: []
7023
+ },
7024
+ surfaceOp: "append"
7025
+ });
7026
+ const callSeqs = calls.map(({ block }) => this.add({
7027
+ type: "tool/call",
7028
+ data: {
7029
+ turn,
7030
+ step,
7031
+ callId: block.id,
7032
+ name: block.name,
7033
+ arguments: block.arguments
7034
+ }
7035
+ }));
7036
+ for (const [callIndex, call] of calls.entries()) {
7037
+ this.add({
7038
+ type: "tool/result",
7039
+ data: {
7040
+ turn,
7041
+ step,
7042
+ message: toolResult(this.id(), call),
7043
+ ...call.meta === void 0 ? {} : { meta: call.meta }
7044
+ },
7045
+ surfaceOp: "append",
7046
+ sourceEventSeqs: [callSeqs[callIndex]]
7047
+ });
7048
+ }
7049
+ if (position < steps.length - 1) {
7050
+ this.add({ type: "step/end", data: { turn, step } });
7051
+ }
7052
+ }
7053
+ this.closeTurn(turn, step, { kind: "completed" });
7054
+ }
7055
+ closeTurn(turn, step, reason) {
7056
+ this.add({ type: "step/end", data: { turn, step } });
7057
+ this.add({ type: "turn/end", data: { turn, reason } });
7058
+ }
7059
+ id() {
7060
+ return this.createId();
7061
+ }
7062
+ userMessage(message, firstTurn) {
7063
+ const lines = [];
7064
+ for (const fragment of message.fragments) {
7065
+ if (fragment.type === "REQUEST") lines.push(fragment.content);
7066
+ }
7067
+ let text3 = lines.join("\n");
7068
+ if (firstTurn && this.provenancePrefix !== "") {
7069
+ text3 = `${this.provenancePrefix}${text3}`;
7070
+ }
7071
+ const content = [{ type: "text", text: text3 }];
7072
+ return {
7073
+ id: MessageId2(this.id()),
7074
+ role: "user",
7075
+ content,
7076
+ source: { kind: "user" }
7077
+ };
7078
+ }
7079
+ replySteps(reply) {
7080
+ const steps = [];
7081
+ let template;
7082
+ let current = emptyStep();
7083
+ const pushStep = () => {
7084
+ if (current.content.length === 0 && current.calls.length === 0) return;
7085
+ steps.push(current);
7086
+ current = emptyStep();
7087
+ };
7088
+ const appendContent = (block) => {
7089
+ if (current.calls.length > 0) pushStep();
7090
+ current.content.push(block);
7091
+ };
7092
+ const appendCall = (call, stage) => {
7093
+ if (stage !== null) {
7094
+ if (current.stage !== null && stage !== current.stage) pushStep();
7095
+ current.stage = stage;
7096
+ }
7097
+ current.calls.push(call);
7098
+ };
7099
+ for (const fragment of reply.fragments) {
7100
+ switch (fragment.type) {
7101
+ case "THINK":
7102
+ if (fragment.content.length > 0) {
7103
+ appendContent({ type: "reasoning", text: fragment.content });
7104
+ }
7105
+ current.elapsedMs += Math.round((fragment.elapsed_secs ?? 0) * 1e3);
7106
+ break;
7107
+ case "RESPONSE":
7108
+ if (fragment.content.length > 0) {
7109
+ appendContent({ type: "text", text: fragment.content });
7110
+ }
7111
+ break;
7112
+ case "TOOL_SEARCH": {
7113
+ if (fragment.status === "WIP") break;
7114
+ const call = searchCall(this.id(), fragment);
7115
+ if (call !== void 0) appendCall(call, fragment.stage_id ?? null);
7116
+ break;
7117
+ }
7118
+ case "TOOL_OPEN": {
7119
+ const url = nonEmpty(fragment.url);
7120
+ if (fragment.status === "WIP" || url === void 0) break;
7121
+ appendCall(openCall(this.id(), fragment, url), fragment.stage_id ?? null);
7122
+ break;
7123
+ }
7124
+ case "READ_LINK": {
7125
+ const text3 = linkLines(fragment.results);
7126
+ if (text3 !== void 0) appendContent({ type: "text", text: text3 });
7127
+ break;
7128
+ }
7129
+ case "TEMPLATE_RESPONSE":
7130
+ template ??= fragment.content;
7131
+ break;
7132
+ case "REQUEST":
7133
+ break;
7134
+ default: {
7135
+ const _exhaustive = fragment;
7136
+ throw new WebChatConvertError(`unexpected fragment ${String(_exhaustive)}`);
7137
+ }
7138
+ }
7139
+ }
7140
+ pushStep();
7141
+ return { steps, template };
7142
+ }
7143
+ };
7144
+ function emptyStep() {
7145
+ return { content: [], calls: [], elapsedMs: 0, stage: null };
7146
+ }
7147
+ function excludedReply(reply, template, stepCount) {
7148
+ if (template !== void 0) {
7149
+ return { code: "DEEPSEEK_EXPORT_TEMPLATE_RESPONSE", message: template };
7150
+ }
7151
+ if (reply.status !== "FINISHED") {
7152
+ return {
7153
+ code: UNFINISHED_STATUS_CODES.get(reply.status) ?? "DEEPSEEK_EXPORT_UNFINISHED_REPLY",
7154
+ message: `The original reply ended with status ${JSON.stringify(reply.status)} and is excluded from the model context.`
7155
+ };
7156
+ }
7157
+ return stepCount === 0 ? {
7158
+ code: "DEEPSEEK_EXPORT_EMPTY_REPLY",
7159
+ message: "The original reply has no importable content."
7160
+ } : void 0;
7161
+ }
7162
+ function failure(code, message) {
7163
+ return { kind: "error", error: { code, message } };
7164
+ }
7165
+ function linkLines(results) {
7166
+ const lines = [];
7167
+ for (const result of results) {
7168
+ const url = nonEmpty(result.url);
7169
+ const title = nonEmpty(result.title);
7170
+ if (url !== void 0) lines.push(`[${title ?? url}](${url})`);
7171
+ else if (title !== void 0) lines.push(title);
7172
+ }
7173
+ return lines.length === 0 ? void 0 : lines.join("\n");
7174
+ }
7175
+ function assistantMessage(id, content) {
7176
+ return {
7177
+ id: MessageId2(id),
7178
+ role: "assistant",
7179
+ content,
7180
+ source: { kind: "model", ...WEB_CHAT_IMPORTED_MODEL_SOURCE }
7181
+ };
7182
+ }
7183
+ function toolResult(id, call) {
7184
+ return {
7185
+ id: MessageId2(id),
7186
+ role: "tool",
7187
+ content: call.result,
7188
+ isError: call.isError,
7189
+ source: { kind: "tool", callId: call.block.id },
7190
+ toolCallId: call.block.id
7191
+ };
7192
+ }
7193
+ function searchCall(id, fragment) {
7194
+ const queries = fragment.queries.filter((query) => query.trim().length > 0);
7195
+ const block = {
7196
+ type: "tool-call",
7197
+ id: ToolCallId(id),
7198
+ name: "web_search",
7199
+ arguments: JSON.stringify({ queries })
7200
+ };
7201
+ if (fragment.status === "FAILED") {
7202
+ return {
7203
+ block,
7204
+ result: [{ type: "text", text: "Error: the export records this search as failed." }],
7205
+ isError: true
7206
+ };
7207
+ }
7208
+ if (queries.length === 0) return void 0;
7209
+ const result = {
7210
+ sources: fragment.results.map((source) => {
7211
+ const title = nonEmpty(source.title);
7212
+ const snippet = nonEmpty(source.snippet);
7213
+ const publishedAt = nonEmpty(source.published_at);
7214
+ return {
7215
+ url: source.url,
7216
+ ...title === void 0 ? {} : { title },
7217
+ ...snippet === void 0 ? {} : { snippet },
7218
+ ...publishedAt === void 0 ? {} : { publishedAt }
7219
+ };
7220
+ }),
7221
+ truncated: false
7222
+ };
7223
+ return {
7224
+ block,
7225
+ result: [{ type: "text", text: formatSearchOutput(result) }],
7226
+ isError: false,
7227
+ meta: searchMetaFromValue(result)
7228
+ };
7229
+ }
7230
+ function openCall(id, fragment, url) {
7231
+ const block = {
7232
+ type: "tool-call",
7233
+ id: ToolCallId(id),
7234
+ name: "web_fetch",
7235
+ arguments: JSON.stringify({ url })
7236
+ };
7237
+ if (fragment.status !== "FINISHED") {
7238
+ return {
7239
+ block,
7240
+ result: [{ type: "text", text: "Error: the page could not be opened." }],
7241
+ isError: true
7242
+ };
7243
+ }
7244
+ const title = nonEmpty(fragment.title);
7245
+ const notice = "The page content is not included in the DeepSeek chat export.";
7246
+ const value = {
7247
+ url,
7248
+ statusCode: 200,
7249
+ truncated: false,
7250
+ body: {
7251
+ kind: "text",
7252
+ content: title === void 0 ? notice : `${title}
7253
+
7254
+ ${notice}`
7255
+ }
7256
+ };
7257
+ return {
7258
+ block,
7259
+ result: [{ type: "text", text: formatFetchOutput(value, FETCH_OUTPUT_CHARS) }],
7260
+ isError: false,
7261
+ meta: fetchMetaFromValue(value, FETCH_OUTPUT_CHARS)
7262
+ };
7263
+ }
7264
+
6741
7265
  // src/host/web-chat-bridge/limits.ts
6742
7266
  var WEB_CHAT_MAX_TEXT_BYTES = 5 * 1024 * 1024;
6743
7267
  var WEB_CHAT_MAX_MESSAGES = 5e3;
@@ -6819,6 +7343,9 @@ function resolveWebChatImportTitle(transcript) {
6819
7343
  if (raw !== "") return raw;
6820
7344
  return "Imported chat";
6821
7345
  }
7346
+ function transcriptHasRichMessages(transcript) {
7347
+ return Array.isArray(transcript.messages) && transcript.messages.length > 0;
7348
+ }
6822
7349
  function closeOpenTurn(session, turn) {
6823
7350
  session.append("turn/end", { turn, reason: { kind: "completed" } });
6824
7351
  }
@@ -6834,34 +7361,44 @@ function appendSessionTitle(session, title, firstUserMessageSeq) {
6834
7361
  if (trimmed === "") return;
6835
7362
  session.append("session/title", {
6836
7363
  title: trimmed,
6837
- messageSeqs: firstUserMessageSeq === void 0 ? [] : [SessionSeq2(firstUserMessageSeq)],
7364
+ messageSeqs: firstUserMessageSeq === void 0 ? [] : [SessionSeq3(firstUserMessageSeq)],
6838
7365
  source: { kind: "fallback" }
6839
7366
  });
6840
7367
  }
6841
7368
  function appendAssistantMessage(session, turn, step, text3) {
6842
- session.append("step/start", { turn, step });
6843
7369
  const message = createAssistantMessage({
6844
7370
  content: [{ type: "text", text: text3 }],
6845
7371
  source: { provider: "web-chat-bridge", model: "imported-history" }
6846
7372
  });
6847
- session.append("assistant/message", {
6848
- turn,
6849
- step,
6850
- message,
6851
- stream: []
6852
- }, { surfaceOp: "append" });
6853
- session.append("step/end", { turn, step });
7373
+ session.append([
7374
+ ["step/start", { turn, step }],
7375
+ ["assistant/message", {
7376
+ turn,
7377
+ step,
7378
+ message,
7379
+ stream: []
7380
+ }, { surfaceOp: "append" }],
7381
+ ["step/end", { turn, step }]
7382
+ ]);
6854
7383
  }
6855
7384
  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 });
7385
+ session.append([
7386
+ ["step/start", { turn, step }],
7387
+ ["system/message", {
7388
+ turn,
7389
+ step,
7390
+ message: createSystemMessage("")
7391
+ }, { surfaceOp: "append" }],
7392
+ ["step/end", { turn, step }]
7393
+ ]);
6863
7394
  }
6864
7395
  function appendTranscript(session, transcript) {
7396
+ if (transcriptHasRichMessages(transcript)) {
7397
+ throw new WebChatImportError(
7398
+ "import-failed",
7399
+ "Rich web-chat transcripts require seed import"
7400
+ );
7401
+ }
6865
7402
  const provenance = importProvenancePrefix(transcript);
6866
7403
  const turns = transcript.turns;
6867
7404
  let turn = 1;
@@ -6920,18 +7457,47 @@ function appendTranscript(session, transcript) {
6920
7457
  appendSessionTitle(session, resolveWebChatImportTitle(transcript), firstUserMessageSeq);
6921
7458
  }
6922
7459
  function buildWebChatImportSeed(transcript) {
7460
+ if (transcriptHasRichMessages(transcript)) {
7461
+ try {
7462
+ const converted = convertWebChatConversation({
7463
+ title: resolveWebChatImportTitle(transcript),
7464
+ currentMessageId: transcript.currentMessageId,
7465
+ messages: transcript.messages
7466
+ }, {
7467
+ createId: () => randomUUID7(),
7468
+ provenancePrefix: importProvenancePrefix(transcript)
7469
+ });
7470
+ return [...converted.events];
7471
+ } catch (error) {
7472
+ if (error instanceof WebChatConvertError) {
7473
+ throw new WebChatImportError("invalid-transcript", error.message);
7474
+ }
7475
+ throw error;
7476
+ }
7477
+ }
6923
7478
  const events = [];
7479
+ const recordOne = (type, data, intent) => {
7480
+ const event = {
7481
+ type,
7482
+ seq: SessionSeq3(events.length),
7483
+ time: Date.now(),
7484
+ data,
7485
+ ...intent?.surfaceOp === void 0 ? {} : { surfaceOp: intent.surfaceOp }
7486
+ };
7487
+ events.push(event);
7488
+ return event;
7489
+ };
6924
7490
  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;
7491
+ append(typeOrInputs, data, intent) {
7492
+ if (typeof typeOrInputs !== "string") {
7493
+ return typeOrInputs.map((input) => {
7494
+ const type = input[0];
7495
+ const payload = input[1];
7496
+ const surface = input[2];
7497
+ return recordOne(type, payload, surface);
7498
+ });
7499
+ }
7500
+ return recordOne(typeOrInputs, data, intent);
6935
7501
  }
6936
7502
  };
6937
7503
  appendTranscript(recorder, transcript);
@@ -6956,7 +7522,7 @@ function errorDetail(error) {
6956
7522
  }
6957
7523
  async function openAgentWorkSession(input, cwd) {
6958
7524
  const agents = input.agents;
6959
- if (typeof agents.createSession === "function") {
7525
+ if (typeof agents.createSession === "function" && !transcriptHasRichMessages(input.transcript)) {
6960
7526
  let created;
6961
7527
  try {
6962
7528
  created = await agents.createSession({
@@ -6986,7 +7552,7 @@ async function openAgentWorkSession(input, cwd) {
6986
7552
  if (typeof agents.create !== "function") {
6987
7553
  throw new WebChatImportError("import-failed", "Agent registry is unavailable");
6988
7554
  }
6989
- const sessionId = SessionId(`session-${randomUUID6()}`);
7555
+ const sessionId = SessionId(`session-${randomUUID7()}`);
6990
7556
  const seed = buildWebChatImportSeed(input.transcript);
6991
7557
  let handle;
6992
7558
  try {
@@ -7005,9 +7571,30 @@ async function openAgentWorkSession(input, cwd) {
7005
7571
  }
7006
7572
  return { session, dispose: onceDispose(() => handle.dispose()) };
7007
7573
  }
7574
+ function ensureResolvableWorkspaceCwd(cwd) {
7575
+ const absolute = resolve2(cwd);
7576
+ try {
7577
+ if (!existsSync5(absolute)) {
7578
+ mkdirSync2(absolute, { recursive: true });
7579
+ }
7580
+ if (!statSync(absolute).isDirectory()) {
7581
+ throw new WebChatImportError(
7582
+ "missing-cwd",
7583
+ `Workspace path exists but is not a directory: ${absolute}`
7584
+ );
7585
+ }
7586
+ } catch (error) {
7587
+ if (error instanceof WebChatImportError) throw error;
7588
+ throw new WebChatImportError(
7589
+ "missing-cwd",
7590
+ `Workspace folder could not be created or read: ${absolute}`
7591
+ );
7592
+ }
7593
+ return absolute;
7594
+ }
7008
7595
  async function importWebChatHistoryNow(input) {
7009
7596
  assertTranscript(input.transcript);
7010
- const cwd = resolve2(input.cwd);
7597
+ const cwd = ensureResolvableWorkspaceCwd(input.cwd);
7011
7598
  const opened = await openAgentWorkSession(input, cwd);
7012
7599
  try {
7013
7600
  const flushed = await input.sessions.flush(opened.session);
@@ -7542,86 +8129,230 @@ function analyzeWebChatExport(input) {
7542
8129
  };
7543
8130
  }
7544
8131
 
7545
- // src/host/web-chat-bridge/share-link.ts
7546
- var SHARE_URL_RE = /(?:https?:\/\/chat\.deepseek\.com)?\/share\/([A-Za-z0-9_-]+)/i;
7547
- var SHARE_ID_RE = /^[A-Za-z0-9_-]{6,}$/;
7548
- function extractWebChatShareId(raw) {
7549
- const trimmed = raw.trim();
7550
- if (trimmed === "") return null;
7551
- const fromUrl = trimmed.match(SHARE_URL_RE);
7552
- if (fromUrl?.[1]) return fromUrl[1];
7553
- if (SHARE_ID_RE.test(trimmed)) return trimmed;
7554
- return null;
8132
+ // src/host/web-chat-bridge/fragments.ts
8133
+ function nonEmptyString(value) {
8134
+ if (typeof value !== "string") return void 0;
8135
+ const trimmed = value.trim();
8136
+ return trimmed === "" ? void 0 : trimmed;
8137
+ }
8138
+ function optionalNumber(value) {
8139
+ if (value === null) return null;
8140
+ if (typeof value === "number" && Number.isFinite(value)) return value;
8141
+ return void 0;
7555
8142
  }
7556
- function webChatSharePageUrl(shareId) {
7557
- return `https://chat.deepseek.com/share/${shareId}`;
8143
+ function parseSearchResults(raw) {
8144
+ if (!Array.isArray(raw)) return [];
8145
+ const out = [];
8146
+ for (const row of raw) {
8147
+ if (row === null || typeof row !== "object") continue;
8148
+ const item = row;
8149
+ const url = nonEmptyString(item.url);
8150
+ if (url === void 0) continue;
8151
+ out.push({
8152
+ url,
8153
+ title: typeof item.title === "string" || item.title === null ? item.title : void 0,
8154
+ snippet: typeof item.snippet === "string" || item.snippet === null ? item.snippet : void 0,
8155
+ published_at: typeof item.published_at === "string" || item.published_at === null ? item.published_at : void 0
8156
+ });
8157
+ }
8158
+ return out;
7558
8159
  }
7559
- function webChatShareContentApiUrl(shareId) {
7560
- return `https://chat.deepseek.com/api/v0/share/content?share_id=${encodeURIComponent(shareId)}`;
8160
+ function parseReadLinkResults(raw) {
8161
+ if (!Array.isArray(raw)) return [];
8162
+ const out = [];
8163
+ for (const row of raw) {
8164
+ if (row === null || typeof row !== "object") continue;
8165
+ const item = row;
8166
+ out.push({
8167
+ url: typeof item.url === "string" || item.url === null ? item.url : void 0,
8168
+ title: typeof item.title === "string" || item.title === null ? item.title : void 0
8169
+ });
8170
+ }
8171
+ return out;
8172
+ }
8173
+ function parseWebChatFragment(raw) {
8174
+ if (raw === null || typeof raw !== "object") return void 0;
8175
+ const item = raw;
8176
+ const type = String(item.type ?? "").toUpperCase();
8177
+ switch (type) {
8178
+ case "REQUEST": {
8179
+ const content = typeof item.content === "string" ? item.content : "";
8180
+ return { type: "REQUEST", content };
8181
+ }
8182
+ case "RESPONSE": {
8183
+ const content = typeof item.content === "string" ? item.content : "";
8184
+ return { type: "RESPONSE", content };
8185
+ }
8186
+ case "THINK": {
8187
+ const content = typeof item.content === "string" ? item.content : "";
8188
+ return {
8189
+ type: "THINK",
8190
+ content,
8191
+ elapsed_secs: optionalNumber(item.elapsed_secs)
8192
+ };
8193
+ }
8194
+ case "TEMPLATE_RESPONSE": {
8195
+ const content = typeof item.content === "string" ? item.content : "";
8196
+ return { type: "TEMPLATE_RESPONSE", content };
8197
+ }
8198
+ case "TOOL_SEARCH": {
8199
+ const queries = Array.isArray(item.queries) ? item.queries.filter((q) => typeof q === "string") : [];
8200
+ return {
8201
+ type: "TOOL_SEARCH",
8202
+ queries,
8203
+ results: parseSearchResults(item.results),
8204
+ status: typeof item.status === "string" ? item.status : void 0,
8205
+ stage_id: optionalNumber(item.stage_id)
8206
+ };
8207
+ }
8208
+ case "TOOL_OPEN": {
8209
+ const url = item.url === null ? null : typeof item.url === "string" ? item.url : null;
8210
+ return {
8211
+ type: "TOOL_OPEN",
8212
+ status: typeof item.status === "string" ? item.status : "FINISHED",
8213
+ url,
8214
+ title: typeof item.title === "string" || item.title === null ? item.title : void 0,
8215
+ stage_id: optionalNumber(item.stage_id)
8216
+ };
8217
+ }
8218
+ case "READ_LINK":
8219
+ return { type: "READ_LINK", results: parseReadLinkResults(item.results) };
8220
+ default:
8221
+ return void 0;
8222
+ }
7561
8223
  }
7562
- function normalizeRole2(raw) {
8224
+ function normalizeExportRole(raw) {
7563
8225
  if (typeof raw !== "string") return null;
7564
- const key = raw.trim().toLowerCase();
7565
- if (key === "user" || key === "human") return "user";
7566
- if (key === "assistant" || key === "ai" || key === "model") return "assistant";
8226
+ const key = raw.trim().toUpperCase();
8227
+ if (key === "USER" || key === "HUMAN") return "USER";
8228
+ if (key === "ASSISTANT" || key === "AI" || key === "MODEL") return "ASSISTANT";
7567
8229
  return null;
7568
8230
  }
7569
- function messageText2(raw) {
7570
- if (typeof raw === "string") return raw.trim();
7571
- if (Array.isArray(raw)) {
7572
- return raw.map((part) => {
8231
+ function messageTextFallback(item) {
8232
+ const content = item.content ?? item.text ?? item.message;
8233
+ if (typeof content === "string") return content;
8234
+ if (Array.isArray(content)) {
8235
+ return content.map((part) => {
7573
8236
  if (typeof part === "string") return part;
7574
8237
  if (part && typeof part === "object" && "text" in part) {
7575
8238
  const text3 = Reflect.get(part, "text");
7576
8239
  return typeof text3 === "string" ? text3 : "";
7577
8240
  }
7578
8241
  return "";
7579
- }).filter(Boolean).join("\n").trim();
8242
+ }).filter(Boolean).join("\n");
7580
8243
  }
7581
8244
  return "";
7582
8245
  }
7583
- function fragmentsText(fragments, preferTypes) {
7584
- if (!Array.isArray(fragments)) return "";
7585
- const preferred = new Set(preferTypes.map((type) => type.toUpperCase()));
7586
- const preferredParts = [];
7587
- const fallbackParts = [];
7588
- for (const frag of fragments) {
7589
- if (frag === null || typeof frag !== "object") continue;
7590
- const type = String(Reflect.get(frag, "type") ?? "").toUpperCase();
7591
- const content = Reflect.get(frag, "content");
7592
- if (typeof content !== "string" || content.trim() === "") continue;
7593
- const text3 = content.trim();
7594
- if (type === "THINK" || type === "TIP" || type.startsWith("TOOL_")) {
7595
- if (preferred.size === 0) fallbackParts.push(text3);
7596
- continue;
7597
- }
7598
- if (preferred.size === 0 || preferred.has(type)) preferredParts.push(text3);
7599
- else fallbackParts.push(text3);
8246
+ function numberId(raw) {
8247
+ if (typeof raw === "number" && Number.isFinite(raw)) return Math.trunc(raw);
8248
+ if (typeof raw === "string" && raw.trim() !== "") {
8249
+ const parsed = Number(raw);
8250
+ if (Number.isFinite(parsed)) return Math.trunc(parsed);
7600
8251
  }
7601
- if (preferredParts.length > 0) return preferredParts.join("\n\n");
7602
- return fallbackParts.join("\n\n");
7603
- }
7604
- function rowText(item, role) {
7605
- const direct = messageText2(item.content ?? item.text ?? item.message);
7606
- if (direct) return direct;
7607
- if (role === "user") return fragmentsText(item.fragments, ["REQUEST"]);
7608
- return fragmentsText(item.fragments, ["RESPONSE"]);
8252
+ return void 0;
7609
8253
  }
7610
- function assertTurns(turns) {
7611
- if (turns.length === 0) {
7612
- throw new Error("Share link has no messages");
8254
+ function parseWebChatRichMessage(raw, fallbackId) {
8255
+ if (raw === null || typeof raw !== "object") return null;
8256
+ const item = raw;
8257
+ const role = normalizeExportRole(item.role ?? item.author ?? item.speaker);
8258
+ if (role === null) return null;
8259
+ const id = numberId(item.id) ?? numberId(item.message_id) ?? fallbackId;
8260
+ const parent_id = numberId(item.parent_id) ?? numberId(item.parent_message_id) ?? null;
8261
+ const fragments = [];
8262
+ if (Array.isArray(item.fragments)) {
8263
+ for (const frag of item.fragments) {
8264
+ const parsed = parseWebChatFragment(frag);
8265
+ if (parsed !== void 0) fragments.push(parsed);
8266
+ }
8267
+ }
8268
+ if (fragments.length === 0) {
8269
+ const text3 = messageTextFallback(item);
8270
+ if (role === "USER") fragments.push({ type: "REQUEST", content: text3 });
8271
+ else fragments.push({ type: "RESPONSE", content: text3 });
8272
+ }
8273
+ return {
8274
+ id,
8275
+ parent_id,
8276
+ role,
8277
+ status: typeof item.status === "string" && item.status.trim() !== "" ? item.status.trim() : "FINISHED",
8278
+ inserted_at: typeof item.inserted_at === "string" ? item.inserted_at : void 0,
8279
+ fragments
8280
+ };
8281
+ }
8282
+ function previewTextFromFragments(fragments, role) {
8283
+ const prefer = role === "USER" ? "REQUEST" : "RESPONSE";
8284
+ const preferred = [];
8285
+ for (const frag of fragments) {
8286
+ if (frag.type === prefer && frag.content.trim() !== "") {
8287
+ preferred.push(frag.content.trim());
8288
+ }
8289
+ }
8290
+ return preferred.join("\n\n");
8291
+ }
8292
+ function richMessagesToPreviewTurns(messages) {
8293
+ const turns = [];
8294
+ for (const message of messages) {
8295
+ const text3 = previewTextFromFragments(message.fragments, message.role);
8296
+ if (text3 === "") continue;
8297
+ turns.push({
8298
+ role: message.role === "USER" ? "user" : "assistant",
8299
+ text: text3
8300
+ });
8301
+ }
8302
+ return turns;
8303
+ }
8304
+
8305
+ // src/host/web-chat-bridge/share-link.ts
8306
+ var SHARE_URL_RE = /(?:https?:\/\/chat\.deepseek\.com)?\/share\/([A-Za-z0-9_-]+)/i;
8307
+ var SHARE_ID_RE = /^[A-Za-z0-9_-]{6,}$/;
8308
+ function extractWebChatShareId(raw) {
8309
+ const trimmed = raw.trim();
8310
+ if (trimmed === "") return null;
8311
+ const fromUrl = trimmed.match(SHARE_URL_RE);
8312
+ if (fromUrl?.[1]) return fromUrl[1];
8313
+ if (SHARE_ID_RE.test(trimmed)) return trimmed;
8314
+ return null;
8315
+ }
8316
+ function webChatSharePageUrl(shareId) {
8317
+ return `https://chat.deepseek.com/share/${shareId}`;
8318
+ }
8319
+ function webChatShareContentApiUrl(shareId) {
8320
+ return `https://chat.deepseek.com/api/v0/share/content?share_id=${encodeURIComponent(shareId)}`;
8321
+ }
8322
+ function utf8ByteLength(text3) {
8323
+ return new TextEncoder().encode(text3).length;
8324
+ }
8325
+ function assertTurns(turns) {
8326
+ if (turns.length === 0) {
8327
+ throw new Error("Share link has no messages");
7613
8328
  }
7614
8329
  if (turns.length > WEB_CHAT_MAX_MESSAGES) {
7615
8330
  throw new Error(`Exceeds message limit (${WEB_CHAT_MAX_MESSAGES})`);
7616
8331
  }
7617
8332
  let bytes = 0;
7618
8333
  for (const turn of turns) {
7619
- bytes += Buffer.byteLength(turn.text, "utf8");
8334
+ bytes += utf8ByteLength(turn.text);
7620
8335
  if (bytes > WEB_CHAT_MAX_TEXT_BYTES) {
7621
8336
  throw new Error(`Share content exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
7622
8337
  }
7623
8338
  }
7624
8339
  }
8340
+ function assertRichBudget(messages) {
8341
+ if (messages.length > WEB_CHAT_MAX_MESSAGES) {
8342
+ throw new Error(`Exceeds message limit (${WEB_CHAT_MAX_MESSAGES})`);
8343
+ }
8344
+ let bytes = 0;
8345
+ for (const message of messages) {
8346
+ for (const frag of message.fragments) {
8347
+ if ("content" in frag && typeof frag.content === "string") {
8348
+ bytes += utf8ByteLength(frag.content);
8349
+ }
8350
+ if (bytes > WEB_CHAT_MAX_TEXT_BYTES) {
8351
+ throw new Error(`Share content exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
8352
+ }
8353
+ }
8354
+ }
8355
+ }
7625
8356
  function bizRecord(data) {
7626
8357
  if (data === null || typeof data !== "object") return null;
7627
8358
  const root = data;
@@ -7636,42 +8367,63 @@ function bizRecord(data) {
7636
8367
  if (biz !== null && typeof biz === "object") return biz;
7637
8368
  return root;
7638
8369
  }
7639
- function turnsFromBizRecord(record2) {
8370
+ function messagesFromBizRecord(record2) {
7640
8371
  const rowsRaw = record2.messages ?? record2.chat_messages;
7641
8372
  const rows = Array.isArray(rowsRaw) ? rowsRaw : [];
7642
- const turns = [];
7643
- for (const row of rows) {
7644
- if (row === null || typeof row !== "object") continue;
7645
- const item = row;
7646
- const role = normalizeRole2(item.role ?? item.author ?? item.speaker);
7647
- if (!role) continue;
7648
- const text3 = rowText(item, role);
7649
- if (!text3) continue;
7650
- turns.push({ role, text: text3 });
8373
+ const messages = [];
8374
+ for (let i = 0; i < rows.length; i++) {
8375
+ const parsed = parseWebChatRichMessage(rows[i], i + 1);
8376
+ if (parsed !== null) messages.push(parsed);
7651
8377
  }
7652
- return turns;
8378
+ return messages;
7653
8379
  }
7654
- function parseWebChatShareContent(data, options) {
7655
- const record2 = bizRecord(data);
7656
- if (record2 === null) {
7657
- throw new Error("unrecognized-share: empty response");
8380
+ function coerceMessageId(raw) {
8381
+ if (raw === null) return null;
8382
+ if (typeof raw === "number" && Number.isFinite(raw)) return Math.trunc(raw);
8383
+ if (typeof raw === "string" && raw.trim() !== "") {
8384
+ const parsed = Number(raw);
8385
+ if (Number.isFinite(parsed)) return Math.trunc(parsed);
7658
8386
  }
7659
- const titleRaw = record2.title;
7660
- const title = typeof titleRaw === "string" && titleRaw.trim() !== "" ? titleRaw.trim() : `Shared chat ${options.shareId}`;
7661
- const turns = turnsFromBizRecord(record2);
8387
+ return void 0;
8388
+ }
8389
+ function currentMessageIdOf(record2) {
8390
+ const fromRoot = coerceMessageId(record2.current_message_id);
8391
+ if (fromRoot !== void 0) return fromRoot;
8392
+ const session = Reflect.get(record2, "chat_session");
8393
+ if (session !== null && typeof session === "object") {
8394
+ return coerceMessageId(Reflect.get(session, "current_message_id"));
8395
+ }
8396
+ return void 0;
8397
+ }
8398
+ function transcriptFromBiz(record2, title, source) {
8399
+ const messages = messagesFromBizRecord(record2);
8400
+ assertRichBudget(messages);
8401
+ const turns = richMessagesToPreviewTurns(messages);
7662
8402
  assertTurns(turns);
8403
+ const currentMessageId = currentMessageIdOf(record2);
7663
8404
  return {
7664
8405
  title,
7665
8406
  turns,
8407
+ messages,
8408
+ ...currentMessageId === void 0 ? {} : { currentMessageId },
7666
8409
  partial: false,
7667
- source: {
7668
- kind: "share-link",
7669
- url: options.shareUrl,
7670
- chatSessionId: options.shareId,
7671
- capturedAt: (/* @__PURE__ */ new Date()).toISOString()
7672
- }
8410
+ source
7673
8411
  };
7674
8412
  }
8413
+ function parseWebChatShareContent(data, options) {
8414
+ const record2 = bizRecord(data);
8415
+ if (record2 === null) {
8416
+ throw new Error("unrecognized-share: empty response");
8417
+ }
8418
+ const titleRaw = record2.title;
8419
+ const title = typeof titleRaw === "string" && titleRaw.trim() !== "" ? titleRaw.trim() : `Shared chat ${options.shareId}`;
8420
+ return transcriptFromBiz(record2, title, {
8421
+ kind: "share-link",
8422
+ url: options.shareUrl,
8423
+ chatSessionId: options.shareId,
8424
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString()
8425
+ });
8426
+ }
7675
8427
  async function fetchWebChatShareContent(shareId, signal) {
7676
8428
  signal.throwIfAborted();
7677
8429
  const response = await fetch(webChatShareContentApiUrl(shareId), {
@@ -7690,7 +8442,7 @@ async function fetchWebChatShareContent(shareId, signal) {
7690
8442
  }
7691
8443
 
7692
8444
  // src/host/web-chat-bridge/login-snapshot.ts
7693
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
8445
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7694
8446
  import { dirname, join as join9 } from "node:path";
7695
8447
 
7696
8448
  // src/host/web-chat-bridge/login-snapshot-types.ts
@@ -7784,7 +8536,7 @@ function saveWebChatLoginSnapshot(pluginDataPackageRoot, input, options) {
7784
8536
  savedAt: typeof input.savedAt === "string" && input.savedAt.trim() !== "" ? input.savedAt : (/* @__PURE__ */ new Date()).toISOString()
7785
8537
  };
7786
8538
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7787
- mkdirSync2(dirname(path), { recursive: true });
8539
+ mkdirSync3(dirname(path), { recursive: true });
7788
8540
  const tmp = `${path}.${process.pid}.tmp`;
7789
8541
  writeFileSync(tmp, `${JSON.stringify(snapshot, null, 2)}
7790
8542
  `, "utf8");
@@ -8064,7 +8816,7 @@ function loadExtraRootPaths(store, primaryCwd) {
8064
8816
  }
8065
8817
 
8066
8818
  // src/host/extra-folders/store.ts
8067
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
8819
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
8068
8820
  import { dirname as dirname2, join as join11 } from "node:path";
8069
8821
  function emptyDoc(primaryCwd) {
8070
8822
  return {
@@ -8097,7 +8849,7 @@ function parseDoc(raw, primaryCwd) {
8097
8849
  }
8098
8850
  }
8099
8851
  function createExtraFoldersStore(rootDir) {
8100
- mkdirSync3(rootDir, { recursive: true });
8852
+ mkdirSync4(rootDir, { recursive: true });
8101
8853
  const fileOf = (primaryCwd) => join11(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
8102
8854
  return {
8103
8855
  rootDir,
@@ -8118,7 +8870,7 @@ function createExtraFoldersStore(rootDir) {
8118
8870
  roots: [...roots]
8119
8871
  };
8120
8872
  const file = fileOf(primaryCwd);
8121
- mkdirSync3(dirname2(file), { recursive: true });
8873
+ mkdirSync4(dirname2(file), { recursive: true });
8122
8874
  const tmp = `${file}.${process.pid}.tmp`;
8123
8875
  writeFileSync2(tmp, `${JSON.stringify(doc, null, 2)}
8124
8876
  `, "utf8");
@@ -8467,7 +9219,7 @@ import { existsSync as existsSync17, readFileSync as readFileSync7, statSync as
8467
9219
  import { basename as basename13, join as join26, resolve as resolve16, sep as sep7 } from "node:path";
8468
9220
 
8469
9221
  // src/host/instructions-skills/create.ts
8470
- import { existsSync as existsSync9, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
9222
+ import { existsSync as existsSync9, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
8471
9223
  import { dirname as dirname5, join as join14, resolve as resolve8 } from "node:path";
8472
9224
 
8473
9225
  // src/host/instructions-skills/paths.ts
@@ -8595,7 +9347,7 @@ function createWorkspaceAgentsFile(projectRoot) {
8595
9347
  if (existsSync9(path)) {
8596
9348
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
8597
9349
  }
8598
- mkdirSync4(dirname5(path), { recursive: true });
9350
+ mkdirSync5(dirname5(path), { recursive: true });
8599
9351
  writeFileSync3(path, AGENTS_STUB, "utf8");
8600
9352
  return { path, created: true };
8601
9353
  }
@@ -8609,7 +9361,7 @@ function createWorkspaceSkill(projectRoot, rawName) {
8609
9361
  if (existsSync9(path) || existsSync9(dir)) {
8610
9362
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
8611
9363
  }
8612
- mkdirSync4(dir, { recursive: true });
9364
+ mkdirSync5(dir, { recursive: true });
8613
9365
  writeFileSync3(path, skillStubMarkdown(name2), "utf8");
8614
9366
  return { path, created: true, name: name2 };
8615
9367
  }
@@ -8696,14 +9448,14 @@ import { lstatSync as lstatSync3 } from "node:fs";
8696
9448
  import { basename as basename8, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
8697
9449
 
8698
9450
  // 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";
9451
+ import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
8700
9452
  import { dirname as dirname6, join as join16 } from "node:path";
8701
9453
  function ledgerPath(dataRoot) {
8702
9454
  return join16(dataRoot, "skills-install", "registry.json");
8703
9455
  }
8704
9456
  function writeLedger(dataRoot, ledger) {
8705
9457
  const path = ledgerPath(dataRoot);
8706
- mkdirSync5(dirname6(path), { recursive: true });
9458
+ mkdirSync6(dirname6(path), { recursive: true });
8707
9459
  const tmp = `${path}.${process.pid}.tmp`;
8708
9460
  writeFileSync4(tmp, `${JSON.stringify(ledger, null, 2)}
8709
9461
  `, "utf8");
@@ -9357,7 +10109,7 @@ import { promisify as promisify3 } from "node:util";
9357
10109
  import { execFile as execFile2 } from "node:child_process";
9358
10110
  import {
9359
10111
  createWriteStream,
9360
- mkdirSync as mkdirSync6,
10112
+ mkdirSync as mkdirSync7,
9361
10113
  readdirSync as readdirSync4,
9362
10114
  renameSync as renameSync5,
9363
10115
  rmSync as rmSync3,
@@ -9408,7 +10160,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
9408
10160
  }
9409
10161
  async function extractZip(zipPath, destDir, signal) {
9410
10162
  signal.throwIfAborted();
9411
- mkdirSync6(destDir, { recursive: true });
10163
+ mkdirSync7(destDir, { recursive: true });
9412
10164
  try {
9413
10165
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
9414
10166
  windowsHide: true,
@@ -9466,10 +10218,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
9466
10218
  }
9467
10219
  async function fetchGithubRepoArchive(options) {
9468
10220
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
9469
- mkdirSync6(workDir, { recursive: true });
10221
+ mkdirSync7(workDir, { recursive: true });
9470
10222
  const zipPath = join20(workDir, "repo.zip");
9471
10223
  const extractDir = join20(workDir, "extract");
9472
- mkdirSync6(extractDir, { recursive: true });
10224
+ mkdirSync7(extractDir, { recursive: true });
9473
10225
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
9474
10226
  const candidates = archiveCandidates(owner, repo, defaultBranch);
9475
10227
  const errors = [];
@@ -9480,7 +10232,7 @@ async function fetchGithubRepoArchive(options) {
9480
10232
  try {
9481
10233
  rmSync3(zipPath, { force: true });
9482
10234
  rmSync3(extractDir, { recursive: true, force: true });
9483
- mkdirSync6(extractDir, { recursive: true });
10235
+ mkdirSync7(extractDir, { recursive: true });
9484
10236
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
9485
10237
  if (!downloadStarted) {
9486
10238
  onStage?.("downloading", detail);
@@ -9524,7 +10276,7 @@ import {
9524
10276
  cpSync,
9525
10277
  existsSync as existsSync14,
9526
10278
  lstatSync as lstatSync4,
9527
- mkdirSync as mkdirSync7,
10279
+ mkdirSync as mkdirSync8,
9528
10280
  readdirSync as readdirSync5,
9529
10281
  readFileSync as readFileSync5,
9530
10282
  renameSync as renameSync6,
@@ -9673,7 +10425,7 @@ function copySkillTree(source, dest) {
9673
10425
  }
9674
10426
  }
9675
10427
  function copySkillTreeAtomic(source, dest, kind) {
9676
- mkdirSync7(dirname9(dest), { recursive: true });
10428
+ mkdirSync8(dirname9(dest), { recursive: true });
9677
10429
  if (kind === "file") {
9678
10430
  if (destinationPresent(dest)) removeDestination(dest);
9679
10431
  copySkillTree(source, dest);
@@ -9701,7 +10453,7 @@ function copySkillTreeAtomic(source, dest, kind) {
9701
10453
  }
9702
10454
  }
9703
10455
  function linkOrCopy(source, dest, mode, kind) {
9704
- mkdirSync7(dirname9(dest), { recursive: true });
10456
+ mkdirSync8(dirname9(dest), { recursive: true });
9705
10457
  if (mode === "copy") {
9706
10458
  copySkillTreeAtomic(source, dest, kind);
9707
10459
  return "copy";
@@ -10176,7 +10928,7 @@ async function checkGithubSkillUpdate(record2, options) {
10176
10928
 
10177
10929
  // src/host/instructions-skills/zip-install.ts
10178
10930
  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";
10931
+ import { existsSync as existsSync16, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
10180
10932
  import { tmpdir as tmpdir5 } from "node:os";
10181
10933
  import { basename as basename12, join as join25, resolve as resolve15 } from "node:path";
10182
10934
  import { promisify as promisify4 } from "node:util";
@@ -10191,7 +10943,7 @@ function tempWorkDir3(prefix) {
10191
10943
  }
10192
10944
  async function extractZipArchive(zipPath, destDir, signal) {
10193
10945
  signal.throwIfAborted();
10194
- mkdirSync8(destDir, { recursive: true });
10946
+ mkdirSync9(destDir, { recursive: true });
10195
10947
  try {
10196
10948
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
10197
10949
  windowsHide: true,
@@ -10775,7 +11527,7 @@ function parseMcpJsonText(jsonText) {
10775
11527
  }
10776
11528
 
10777
11529
  // 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";
11530
+ import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
10779
11531
  import { join as join28 } from "node:path";
10780
11532
 
10781
11533
  // src/host/mcp-connectors/paths.ts
@@ -10873,11 +11625,11 @@ async function installMcpServerFromGit(options) {
10873
11625
  }
10874
11626
  removePathRobust(installDir);
10875
11627
  }
10876
- mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
11628
+ mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
10877
11629
  const staging = `${installDir}.staging.${process.pid}`;
10878
11630
  try {
10879
11631
  if (existsSync18(staging)) removePathRobust(staging);
10880
- mkdirSync9(staging, { recursive: true });
11632
+ mkdirSync10(staging, { recursive: true });
10881
11633
  if (parsed.github === null) {
10882
11634
  throw new AuxiliaryError(
10883
11635
  "FILE_EDIT_FAILED",
@@ -10899,7 +11651,7 @@ async function installMcpServerFromGit(options) {
10899
11651
  }
10900
11652
  contentRoot = nested;
10901
11653
  }
10902
- mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
11654
+ mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
10903
11655
  if (contentRoot !== repoDir) {
10904
11656
  const nestedStaging = `${installDir}.nested.${process.pid}`;
10905
11657
  renameSync7(contentRoot, nestedStaging);
@@ -10936,6 +11688,7 @@ async function installMcpServerFromGit(options) {
10936
11688
  function snapshotOf2(host) {
10937
11689
  return {
10938
11690
  connectors: host.store.load().connectors,
11691
+ statuses: host.runtime.statusRows(),
10939
11692
  bridgeAvailable: host.runtime.bridgeAvailable,
10940
11693
  bridgeError: host.runtime.lastBridgeError
10941
11694
  };
@@ -11146,9 +11899,25 @@ function listMcpConnectorToolsNow(host, request) {
11146
11899
  }));
11147
11900
  return { serverName, tools };
11148
11901
  }
11902
+ async function restartMcpConnectorNow(host, request) {
11903
+ const restarted = await host.runtime.restart(request.id);
11904
+ return {
11905
+ id: request.id,
11906
+ ok: restarted.ok,
11907
+ error: restarted.error,
11908
+ snapshot: snapshotOf2(host)
11909
+ };
11910
+ }
11911
+ async function probeMcpConnectorNow(host, request, signal) {
11912
+ const probed = await host.runtime.probe(request.id, signal);
11913
+ return {
11914
+ ...probed,
11915
+ snapshot: snapshotOf2(host)
11916
+ };
11917
+ }
11149
11918
 
11150
11919
  // src/host/mcp-connectors/store.ts
11151
- import { mkdirSync as mkdirSync10, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
11920
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
11152
11921
  import { dirname as dirname11 } from "node:path";
11153
11922
 
11154
11923
  // src/host/mcp-connectors/types.ts
@@ -11231,7 +12000,7 @@ function parseDoc2(raw) {
11231
12000
  }
11232
12001
  }
11233
12002
  function createMcpConnectorsStore(rootDir) {
11234
- mkdirSync10(rootDir, { recursive: true });
12003
+ mkdirSync11(rootDir, { recursive: true });
11235
12004
  const file = mcpConnectorsLedgerPath(rootDir);
11236
12005
  return {
11237
12006
  rootDir,
@@ -11250,7 +12019,7 @@ function createMcpConnectorsStore(rootDir) {
11250
12019
  version: MCP_CONNECTORS_VERSION,
11251
12020
  connectors: [...connectors]
11252
12021
  };
11253
- mkdirSync10(dirname11(file), { recursive: true });
12022
+ mkdirSync11(dirname11(file), { recursive: true });
11254
12023
  const tmp = `${file}.${process.pid}.tmp`;
11255
12024
  writeFileSync5(tmp, `${JSON.stringify(doc, null, 2)}
11256
12025
  `, "utf8");
@@ -11260,6 +12029,80 @@ function createMcpConnectorsStore(rootDir) {
11260
12029
  };
11261
12030
  }
11262
12031
 
12032
+ // src/host/mcp-connectors/probe-message.ts
12033
+ function classifyMcpProbeFailure(message) {
12034
+ const lower = message.toLowerCase();
12035
+ if (lower.includes("url is expired") || lower.includes("url expired") || lower.includes('"url is expired"')) {
12036
+ return "url-expired";
12037
+ }
12038
+ return "generic";
12039
+ }
12040
+ function rewriteMcpProbeFailure(message) {
12041
+ const code = classifyMcpProbeFailure(message);
12042
+ switch (code) {
12043
+ case "url-expired":
12044
+ return "url-expired";
12045
+ case "generic":
12046
+ return message;
12047
+ default: {
12048
+ const _exhaustive = code;
12049
+ return _exhaustive;
12050
+ }
12051
+ }
12052
+ }
12053
+
12054
+ // src/host/mcp-connectors/status.ts
12055
+ function summarizeMcpConnectionStatus(status) {
12056
+ if (status === null || status === void 0) {
12057
+ return { state: "unmounted", detail: null, toolCount: null };
12058
+ }
12059
+ switch (status.state) {
12060
+ case "connected":
12061
+ return {
12062
+ state: "connected",
12063
+ detail: null,
12064
+ toolCount: status.toolCount
12065
+ };
12066
+ case "connecting":
12067
+ return {
12068
+ state: "connecting",
12069
+ detail: status.attempt > 0 ? `attempt ${status.attempt + 1}` : null,
12070
+ toolCount: null
12071
+ };
12072
+ case "reconnecting":
12073
+ return {
12074
+ state: "reconnecting",
12075
+ detail: status.lastError.trim() !== "" ? status.lastError : `attempt ${status.attempt}/${status.maxAttempts}`,
12076
+ toolCount: null
12077
+ };
12078
+ case "waiting-credentials":
12079
+ return {
12080
+ state: "waiting-credentials",
12081
+ detail: status.lastError.trim() !== "" ? status.lastError : null,
12082
+ toolCount: null
12083
+ };
12084
+ case "failed":
12085
+ return {
12086
+ state: "failed",
12087
+ detail: status.lastError?.trim() ? `${status.reason}: ${status.lastError}` : status.reason,
12088
+ toolCount: null
12089
+ };
12090
+ case "closed":
12091
+ return {
12092
+ state: "closed",
12093
+ detail: status.result?.cleanupError ?? null,
12094
+ toolCount: null
12095
+ };
12096
+ default: {
12097
+ const _exhaustive = status;
12098
+ return _exhaustive;
12099
+ }
12100
+ }
12101
+ }
12102
+ function disabledMcpStatus() {
12103
+ return { state: "disabled", detail: null, toolCount: null };
12104
+ }
12105
+
11263
12106
  // src/host/mcp-connectors/runtime.ts
11264
12107
  function toPluginConfig(entry) {
11265
12108
  const base = {
@@ -11296,6 +12139,7 @@ var McpConnectorRuntime = class {
11296
12139
  store;
11297
12140
  mounts = /* @__PURE__ */ new Map();
11298
12141
  module = null;
12142
+ clientApi = null;
11299
12143
  bridgeError = null;
11300
12144
  featureEnabled = true;
11301
12145
  get bridgeAvailable() {
@@ -11314,23 +12158,155 @@ var McpConnectorRuntime = class {
11314
12158
  if (typeof loaded.apply !== "function") {
11315
12159
  this.bridgeError = "@deepseek-ai/dsh-mcp-client apply() missing";
11316
12160
  this.module = null;
12161
+ this.clientApi = null;
11317
12162
  return false;
11318
12163
  }
11319
12164
  this.module = loaded;
12165
+ this.clientApi = loaded;
11320
12166
  this.bridgeError = null;
11321
12167
  return true;
11322
12168
  } catch (error) {
11323
12169
  const detail = error instanceof Error ? error.message : String(error);
11324
12170
  this.bridgeError = detail;
11325
12171
  this.module = null;
12172
+ this.clientApi = null;
11326
12173
  this.ctx.logger.warn(`agent-enhancer: dsh-mcp-client unavailable: ${detail}`);
11327
12174
  return false;
11328
12175
  }
11329
12176
  }
12177
+ statusOf(id, entry) {
12178
+ const connector = entry ?? this.store.load().connectors.find((row) => row.id === id);
12179
+ if (connector === void 0) {
12180
+ return summarizeMcpConnectionStatus(void 0);
12181
+ }
12182
+ if (!connector.enabled || !this.featureEnabled) {
12183
+ return disabledMcpStatus();
12184
+ }
12185
+ const mount = this.mounts.get(id);
12186
+ if (mount === void 0) {
12187
+ return summarizeMcpConnectionStatus(void 0);
12188
+ }
12189
+ try {
12190
+ const handle = this.clientApi?.connectionStatusOf?.(mount.fiber);
12191
+ return summarizeMcpConnectionStatus(handle?.current());
12192
+ } catch {
12193
+ return summarizeMcpConnectionStatus(void 0);
12194
+ }
12195
+ }
12196
+ statusRows() {
12197
+ return this.store.load().connectors.map((entry) => ({
12198
+ id: entry.id,
12199
+ status: this.statusOf(entry.id, entry)
12200
+ }));
12201
+ }
12202
+ async restart(id) {
12203
+ const entry = this.store.load().connectors.find((row) => row.id === id);
12204
+ if (entry === void 0) {
12205
+ return { ok: false, error: `MCP connector not found: ${id}` };
12206
+ }
12207
+ if (!entry.enabled) {
12208
+ return { ok: false, error: "Connector is disabled" };
12209
+ }
12210
+ if (!this.featureEnabled) {
12211
+ return { ok: false, error: "MCP connectors feature is disabled" };
12212
+ }
12213
+ const ok = await this.ensureBridge();
12214
+ if (!ok) {
12215
+ return { ok: false, error: this.bridgeError ?? "mcp-client bridge unavailable" };
12216
+ }
12217
+ await this.disposeOne(id);
12218
+ await this.mountOne(entry);
12219
+ if (!this.mounts.has(id)) {
12220
+ return { ok: false, error: "Restart failed to remount connector" };
12221
+ }
12222
+ return { ok: true, error: null };
12223
+ }
12224
+ async probe(id, signal) {
12225
+ const entry = this.store.load().connectors.find((row) => row.id === id);
12226
+ if (entry === void 0) {
12227
+ return {
12228
+ id,
12229
+ ok: false,
12230
+ message: `MCP connector not found: ${id}`,
12231
+ toolNames: [],
12232
+ truncated: false,
12233
+ durationMs: 0
12234
+ };
12235
+ }
12236
+ const live = this.statusOf(id, entry);
12237
+ if (live.state === "connected") {
12238
+ const toolNames = this.liveToolNames(entry.serverName);
12239
+ const count = live.toolCount ?? toolNames.length;
12240
+ return {
12241
+ id,
12242
+ ok: true,
12243
+ message: `live \xB7 ${count} tools`,
12244
+ toolNames,
12245
+ truncated: false,
12246
+ durationMs: 0
12247
+ };
12248
+ }
12249
+ const ok = await this.ensureBridge();
12250
+ if (!ok || this.clientApi?.probeServer === void 0) {
12251
+ return {
12252
+ id,
12253
+ ok: false,
12254
+ message: this.bridgeError ?? "mcp-client probeServer unavailable",
12255
+ toolNames: [],
12256
+ truncated: false,
12257
+ durationMs: 0
12258
+ };
12259
+ }
12260
+ try {
12261
+ const result = await this.clientApi.probeServer(this.ctx, toPluginConfig(entry), {
12262
+ timeoutMs: 15e3,
12263
+ ...signal === void 0 ? {} : { signal }
12264
+ });
12265
+ if (result.ok) {
12266
+ const toolNames = result.toolNames ?? [];
12267
+ return {
12268
+ id,
12269
+ ok: true,
12270
+ message: result.serverInfo === void 0 ? `ok \xB7 ${toolNames.length} tools` : `ok \xB7 ${result.serverInfo.name}@${result.serverInfo.version} \xB7 ${toolNames.length} tools`,
12271
+ toolNames,
12272
+ truncated: result.truncated === true,
12273
+ durationMs: result.durationMs ?? 0
12274
+ };
12275
+ }
12276
+ const raw = `${result.stage ?? "probe"}: ${result.message ?? "failed"}`;
12277
+ return {
12278
+ id,
12279
+ ok: false,
12280
+ message: rewriteMcpProbeFailure(raw),
12281
+ toolNames: [],
12282
+ truncated: false,
12283
+ durationMs: result.durationMs ?? 0
12284
+ };
12285
+ } catch (error) {
12286
+ const detail = error instanceof Error ? error.message : String(error);
12287
+ return {
12288
+ id,
12289
+ ok: false,
12290
+ message: rewriteMcpProbeFailure(detail),
12291
+ toolNames: [],
12292
+ truncated: false,
12293
+ durationMs: 0
12294
+ };
12295
+ }
12296
+ }
12297
+ liveToolNames(serverName) {
12298
+ const prefix = `mcp__${serverName}__`;
12299
+ try {
12300
+ const definitions = this.ctx.tools.definitions();
12301
+ return definitions.filter((def) => def.name.startsWith(prefix)).map((def) => def.name.slice(prefix.length)).filter((name2) => name2.length > 0);
12302
+ } catch {
12303
+ return [];
12304
+ }
12305
+ }
11330
12306
  async disposeAll() {
11331
12307
  const ids = [...this.mounts.keys()];
11332
- for (const id of ids) {
11333
- await this.disposeOne(id);
12308
+ for (const nextId of ids) {
12309
+ await this.disposeOne(nextId);
11334
12310
  }
11335
12311
  }
11336
12312
  async disposeOne(id) {
@@ -11686,7 +12662,7 @@ var AutoCatalogAdapter = class extends LlmAdapter {
11686
12662
  stream(_options) {
11687
12663
  throw new LlmError(
11688
12664
  "Auto is a routing sentinel and is not sent to a provider",
11689
- "AUTO_SENTINEL"
12665
+ "UNSUPPORTED_OPTION"
11690
12666
  );
11691
12667
  }
11692
12668
  };
@@ -11844,17 +12820,28 @@ function installAutoSessionRoute(ctx, options) {
11844
12820
  const map = autoRouteMapOf(settings);
11845
12821
  const note = (agent === void 0 ? void 0 : notes.get(agent)) ?? loggedTurn(asAgent(agent));
11846
12822
  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
- });
12823
+ let mapped;
12824
+ try {
12825
+ mapped = await resolveAutoRoute({
12826
+ text: note?.text ?? "",
12827
+ feature,
12828
+ toolHeavy: note?.toolHeavy ?? false,
12829
+ map,
12830
+ classifierEnabled: settings.autoClassifierEnabled,
12831
+ classify,
12832
+ isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
12833
+ signal,
12834
+ fallback: fallbackRoute(ctx, asAgent(agent))
12835
+ });
12836
+ } catch (error) {
12837
+ if (error instanceof AutoRouteUnconfiguredError) {
12838
+ throw new LlmError(AUTO_ROUTE_UNCONFIGURED_LLM_MESSAGE, "INVALID_CONFIG");
12839
+ }
12840
+ throw error;
12841
+ }
12842
+ if (mapped.provider === "" || mapped.model === "" || isAutoModel({ provider: mapped.provider, model: mapped.model })) {
12843
+ throw new LlmError(AUTO_ROUTE_UNCONFIGURED_LLM_MESSAGE, "INVALID_CONFIG");
12844
+ }
11858
12845
  if (agent !== void 0 && feature === "session") setSessionResolvedRoute(agent, mapped);
11859
12846
  return mapped;
11860
12847
  };
@@ -12234,16 +13221,27 @@ var AuxiliaryModels = class {
12234
13221
  const settings = this.enhancerSettings();
12235
13222
  const map = autoRouteMapOf(settings);
12236
13223
  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
- });
13224
+ let mapped;
13225
+ try {
13226
+ mapped = await resolveAutoRoute({
13227
+ text: text3,
13228
+ feature,
13229
+ toolHeavy,
13230
+ map,
13231
+ classifierEnabled: settings.autoClassifierEnabled,
13232
+ classify,
13233
+ isAvailable: (provider, model) => this.modelExists(provider, model),
13234
+ fallback: this.fallbackFromSession(session, override)
13235
+ });
13236
+ } catch (error) {
13237
+ if (error instanceof AutoRouteUnconfiguredError) {
13238
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED", error.message);
13239
+ }
13240
+ throw error;
13241
+ }
13242
+ if (!this.modelExists(mapped.provider, mapped.model) || isAutoModel(mapped)) {
13243
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED");
13244
+ }
12247
13245
  if (feature === "session") {
12248
13246
  setSessionResolvedRouteForSession(session, {
12249
13247
  provider: mapped.provider,
@@ -12378,6 +13376,9 @@ var AuxiliaryModels = class {
12378
13376
  } catch (error) {
12379
13377
  if (controller.signal.aborted) throw controller.signal.reason;
12380
13378
  if (error instanceof AuxiliaryError) throw error;
13379
+ if (error instanceof AutoRouteUnconfiguredError) {
13380
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED", error.message);
13381
+ }
12381
13382
  throw new AuxiliaryError("MODEL_FAILED");
12382
13383
  } finally {
12383
13384
  signal.removeEventListener("abort", abort);
@@ -13159,7 +14160,7 @@ function mergeUsageCalls(stored, history) {
13159
14160
  }
13160
14161
 
13161
14162
  // src/host/usage/ledger.ts
13162
- import { randomUUID as randomUUID7 } from "node:crypto";
14163
+ import { randomUUID as randomUUID8 } from "node:crypto";
13163
14164
  import { chmod as chmod4, mkdir as mkdir5, readFile as readFile5, rename as rename4, unlink as unlink5, writeFile as writeFile4 } from "node:fs/promises";
13164
14165
  import { basename as basename14, join as join29 } from "node:path";
13165
14166
  import { z as z3 } from "zod";
@@ -13191,7 +14192,7 @@ async function removeIfPresent5(path) {
13191
14192
  }
13192
14193
  }
13193
14194
  async function writeAtomic4(path, value) {
13194
- const temporary = join29(join29(path, ".."), `.${basename14(path)}.${randomUUID7()}.tmp`);
14195
+ const temporary = join29(join29(path, ".."), `.${basename14(path)}.${randomUUID8()}.tmp`);
13195
14196
  try {
13196
14197
  await writeFile4(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
13197
14198
  await rename4(temporary, path);
@@ -13316,11 +14317,6 @@ function installUsageObserver(ctx, recorder) {
13316
14317
  // src/host/rpc.ts
13317
14318
  import { createTypertRemoteInfo } from "@deepseek-ai/dsh-typert-protocol/remote-info";
13318
14319
  import { z as z4 } from "zod";
13319
-
13320
- // src/host/update/types.ts
13321
- var APPLY_UPDATE_CODES = ["restart", "link", "manual", "none", "failed"];
13322
-
13323
- // src/host/rpc.ts
13324
14320
  var sessionIdSchema3 = z4.string().min(1).transform((value) => value);
13325
14321
  var recentExchangeSchema = z4.strictObject({
13326
14322
  turn: z4.number().int().nonnegative(),
@@ -13494,10 +14490,58 @@ var webChatTurnSchema = z4.strictObject({
13494
14490
  role: z4.enum(["user", "assistant"]),
13495
14491
  text: z4.string()
13496
14492
  });
14493
+ var webChatSearchResultSchema = z4.strictObject({
14494
+ url: z4.string(),
14495
+ title: z4.string().nullable().optional(),
14496
+ snippet: z4.string().nullable().optional(),
14497
+ published_at: z4.string().nullable().optional()
14498
+ });
14499
+ var webChatFragmentSchema = z4.discriminatedUnion("type", [
14500
+ z4.strictObject({ type: z4.literal("REQUEST"), content: z4.string() }),
14501
+ z4.strictObject({ type: z4.literal("RESPONSE"), content: z4.string() }),
14502
+ z4.strictObject({
14503
+ type: z4.literal("THINK"),
14504
+ content: z4.string(),
14505
+ elapsed_secs: z4.number().nonnegative().nullable().optional()
14506
+ }),
14507
+ z4.strictObject({ type: z4.literal("TEMPLATE_RESPONSE"), content: z4.string() }),
14508
+ z4.strictObject({
14509
+ type: z4.literal("TOOL_SEARCH"),
14510
+ queries: z4.array(z4.string()),
14511
+ results: z4.array(webChatSearchResultSchema),
14512
+ status: z4.string().optional(),
14513
+ stage_id: z4.number().int().nullable().optional()
14514
+ }),
14515
+ z4.strictObject({
14516
+ type: z4.literal("TOOL_OPEN"),
14517
+ status: z4.string(),
14518
+ url: z4.string().nullable(),
14519
+ title: z4.string().nullable().optional(),
14520
+ stage_id: z4.number().int().nullable().optional()
14521
+ }),
14522
+ z4.strictObject({
14523
+ type: z4.literal("READ_LINK"),
14524
+ results: z4.array(z4.strictObject({
14525
+ url: z4.string().nullable().optional(),
14526
+ title: z4.string().nullable().optional()
14527
+ }))
14528
+ })
14529
+ ]);
14530
+ var webChatRichMessageSchema = z4.strictObject({
14531
+ id: z4.number().int(),
14532
+ parent_id: z4.number().int().nullable(),
14533
+ role: z4.enum(["USER", "ASSISTANT"]),
14534
+ status: z4.string(),
14535
+ inserted_at: z4.string().optional(),
14536
+ fragments: z4.array(webChatFragmentSchema)
14537
+ });
13497
14538
  var webChatTranscriptSchema = z4.strictObject({
13498
14539
  title: z4.string(),
13499
14540
  partial: z4.boolean(),
13500
14541
  turns: z4.array(webChatTurnSchema).min(1),
14542
+ /** Share / history_messages tree for Session seed fidelity (optional for DOM capture). */
14543
+ messages: z4.array(webChatRichMessageSchema).optional(),
14544
+ currentMessageId: z4.number().int().nullable().optional(),
13501
14545
  source: z4.strictObject({
13502
14546
  kind: z4.enum(["rendered-capture", "official-export", "share-link", "account-history"]),
13503
14547
  url: z4.string().optional(),
@@ -13755,21 +14799,6 @@ var listExtraFolderEntriesResultCodec = codec(
13755
14799
  "dsh-agent-enhancer#ListExtraFolderEntriesResult",
13756
14800
  listExtraFolderEntriesResultSchema
13757
14801
  );
13758
- var updateCheckResultSchema = z4.strictObject({
13759
- current: z4.string(),
13760
- latest: z4.string().nullable(),
13761
- updateAvailable: z4.boolean(),
13762
- installKind: z4.enum(["npm", "link", "unknown"]),
13763
- canAutoApply: z4.boolean(),
13764
- command: z4.string()
13765
- });
13766
- var applyUpdateResultSchema = z4.strictObject({
13767
- ok: z4.boolean(),
13768
- message: z4.enum(APPLY_UPDATE_CODES),
13769
- command: z4.string().optional()
13770
- });
13771
- var updateCheckResultCodec = codec("dsh-agent-enhancer#UpdateCheckResult", updateCheckResultSchema);
13772
- var applyUpdateResultCodec = codec("dsh-agent-enhancer#ApplyUpdateResult", applyUpdateResultSchema);
13773
14802
  var usageTokenFields = {
13774
14803
  inputTokens: z4.number().int().nonnegative(),
13775
14804
  outputTokens: z4.number().int().nonnegative(),
@@ -13921,6 +14950,15 @@ var browserAgentAuditEntrySchema = z4.strictObject({
13921
14950
  url: z4.string().optional(),
13922
14951
  outcome: z4.enum(["ok", "denied", "error", "needs_human"])
13923
14952
  });
14953
+ var browserAgentTabEntrySchema = z4.strictObject({
14954
+ tabId: z4.number().int().positive(),
14955
+ title: z4.string(),
14956
+ url: z4.string(),
14957
+ /** True when this is the driver's currently focused page. */
14958
+ active: z4.boolean(),
14959
+ /** True when any chat session is bound to this tab. */
14960
+ bound: z4.boolean()
14961
+ });
13924
14962
  var browserAgentSnapshotSchema = z4.strictObject({
13925
14963
  enabled: z4.boolean(),
13926
14964
  /** Settings preference (auto / chrome / edge / safari). */
@@ -13941,6 +14979,8 @@ var browserAgentSnapshotSchema = z4.strictObject({
13941
14979
  tabConflict: browserAgentTabConflictSchema.nullable(),
13942
14980
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
13943
14981
  boundTabId: z4.number().int().nullable(),
14982
+ /** Open tabs in the dedicated browser (empty when not launched). */
14983
+ tabs: z4.array(browserAgentTabEntrySchema),
13944
14984
  audit: z4.array(browserAgentAuditEntrySchema),
13945
14985
  /** Dedicated Chromium profile used by one-click launch (user-level). */
13946
14986
  profileDir: z4.string().min(1)
@@ -14068,6 +15108,26 @@ var browserAgentSetBrowserResultCodec = codec(
14068
15108
  "dsh-agent-enhancer#BrowserAgentSetBrowserResult",
14069
15109
  browserAgentSetBrowserResultSchema
14070
15110
  );
15111
+ var browserAgentSelectTabRequestSchema = z4.strictObject({
15112
+ tabId: z4.number().int().positive(),
15113
+ sessionId: z4.string().min(1).optional()
15114
+ });
15115
+ var browserAgentSelectTabRequestCodec = codec(
15116
+ "dsh-agent-enhancer#BrowserAgentSelectTabRequest",
15117
+ browserAgentSelectTabRequestSchema
15118
+ );
15119
+ var browserAgentSelectTabResultSchema = z4.strictObject({
15120
+ ok: z4.boolean(),
15121
+ tabId: z4.number().int().positive().optional(),
15122
+ url: z4.string().optional(),
15123
+ title: z4.string().optional(),
15124
+ error: z4.string().optional(),
15125
+ snapshot: browserAgentSnapshotSchema
15126
+ });
15127
+ var browserAgentSelectTabResultCodec = codec(
15128
+ "dsh-agent-enhancer#BrowserAgentSelectTabResult",
15129
+ browserAgentSelectTabResultSchema
15130
+ );
14071
15131
  var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
14072
15132
  var instructionFileEntrySchema = z4.strictObject({
14073
15133
  id: z4.string().min(1),
@@ -14290,8 +15350,28 @@ var mcpConnectorEntrySchema = z4.strictObject({
14290
15350
  createdAt: z4.number(),
14291
15351
  updatedAt: z4.number()
14292
15352
  });
15353
+ var mcpConnectorStatusStateSchema = z4.enum([
15354
+ "disabled",
15355
+ "unmounted",
15356
+ "connecting",
15357
+ "connected",
15358
+ "reconnecting",
15359
+ "waiting-credentials",
15360
+ "failed",
15361
+ "closed"
15362
+ ]);
15363
+ var mcpConnectorRuntimeStatusSchema = z4.strictObject({
15364
+ state: mcpConnectorStatusStateSchema,
15365
+ detail: z4.string().nullable(),
15366
+ toolCount: z4.number().int().nullable()
15367
+ });
15368
+ var mcpConnectorStatusRowSchema = z4.strictObject({
15369
+ id: z4.string().min(1),
15370
+ status: mcpConnectorRuntimeStatusSchema
15371
+ });
14293
15372
  var mcpConnectorsSnapshotSchema = z4.strictObject({
14294
15373
  connectors: z4.array(mcpConnectorEntrySchema),
15374
+ statuses: z4.array(mcpConnectorStatusRowSchema),
14295
15375
  bridgeAvailable: z4.boolean(),
14296
15376
  bridgeError: z4.string().nullable()
14297
15377
  });
@@ -14368,6 +15448,27 @@ var listMcpConnectorToolsResultSchema = z4.strictObject({
14368
15448
  description: z4.string()
14369
15449
  }))
14370
15450
  });
15451
+ var restartMcpConnectorRequestSchema = z4.strictObject({
15452
+ id: z4.string().min(1)
15453
+ });
15454
+ var restartMcpConnectorResultSchema = z4.strictObject({
15455
+ id: z4.string().min(1),
15456
+ ok: z4.boolean(),
15457
+ error: z4.string().nullable(),
15458
+ snapshot: mcpConnectorsSnapshotSchema
15459
+ });
15460
+ var probeMcpConnectorRequestSchema = z4.strictObject({
15461
+ id: z4.string().min(1)
15462
+ });
15463
+ var probeMcpConnectorResultSchema = z4.strictObject({
15464
+ id: z4.string().min(1),
15465
+ ok: z4.boolean(),
15466
+ message: z4.string(),
15467
+ toolNames: z4.array(z4.string()),
15468
+ truncated: z4.boolean(),
15469
+ durationMs: z4.number(),
15470
+ snapshot: mcpConnectorsSnapshotSchema
15471
+ });
14371
15472
  var listMcpConnectorsRequestCodec = codec(
14372
15473
  "dsh-agent-enhancer#ListMcpConnectorsRequest",
14373
15474
  listMcpConnectorsRequestSchema
@@ -14432,6 +15533,22 @@ var listMcpConnectorToolsResultCodec = codec(
14432
15533
  "dsh-agent-enhancer#ListMcpConnectorToolsResult",
14433
15534
  listMcpConnectorToolsResultSchema
14434
15535
  );
15536
+ var restartMcpConnectorRequestCodec = codec(
15537
+ "dsh-agent-enhancer#RestartMcpConnectorRequest",
15538
+ restartMcpConnectorRequestSchema
15539
+ );
15540
+ var restartMcpConnectorResultCodec = codec(
15541
+ "dsh-agent-enhancer#RestartMcpConnectorResult",
15542
+ restartMcpConnectorResultSchema
15543
+ );
15544
+ var probeMcpConnectorRequestCodec = codec(
15545
+ "dsh-agent-enhancer#ProbeMcpConnectorRequest",
15546
+ probeMcpConnectorRequestSchema
15547
+ );
15548
+ var probeMcpConnectorResultCodec = codec(
15549
+ "dsh-agent-enhancer#ProbeMcpConnectorResult",
15550
+ probeMcpConnectorResultSchema
15551
+ );
14435
15552
  var remoteInfo = createTypertRemoteInfo({
14436
15553
  package: "dsh-agent-enhancer",
14437
15554
  methods: {
@@ -14586,20 +15703,6 @@ var remoteInfo = createTypertRemoteInfo({
14586
15703
  cancellation: { parameter: "signal" },
14587
15704
  result: listExtraFolderEntriesResultCodec
14588
15705
  },
14589
- "agentEnhancer/checkUpdate": {
14590
- service: "agentEnhancer",
14591
- implementation: "checkUpdate",
14592
- invocation: { kind: "direct" },
14593
- parameters: [],
14594
- result: updateCheckResultCodec
14595
- },
14596
- "agentEnhancer/applyUpdate": {
14597
- service: "agentEnhancer",
14598
- implementation: "applyUpdate",
14599
- invocation: { kind: "direct" },
14600
- parameters: [],
14601
- result: applyUpdateResultCodec
14602
- },
14603
15706
  "agentEnhancer/usageSummary": {
14604
15707
  service: "agentEnhancer",
14605
15708
  implementation: "usageSummary",
@@ -14751,6 +15854,18 @@ var remoteInfo = createTypertRemoteInfo({
14751
15854
  }],
14752
15855
  result: browserAgentSetBrowserResultCodec
14753
15856
  },
15857
+ "agentEnhancer/browserAgentSelectTab": {
15858
+ service: "agentEnhancer",
15859
+ implementation: "browserAgentSelectTab",
15860
+ invocation: { kind: "direct" },
15861
+ parameters: [{
15862
+ name: "request",
15863
+ source: "json",
15864
+ codec: browserAgentSelectTabRequestCodec,
15865
+ strictCodec: browserAgentSelectTabRequestCodec
15866
+ }],
15867
+ result: browserAgentSelectTabResultCodec
15868
+ },
14754
15869
  "agentEnhancer/listInstructionsSkills": {
14755
15870
  service: "agentEnhancer",
14756
15871
  implementation: "listInstructionsSkills",
@@ -14972,6 +16087,32 @@ var remoteInfo = createTypertRemoteInfo({
14972
16087
  cancellation: { parameter: "signal" },
14973
16088
  result: listMcpConnectorToolsResultCodec
14974
16089
  },
16090
+ "agentEnhancer/restartMcpConnector": {
16091
+ service: "agentEnhancer",
16092
+ implementation: "restartMcpConnector",
16093
+ invocation: { kind: "direct" },
16094
+ parameters: [{
16095
+ name: "request",
16096
+ source: "json",
16097
+ codec: restartMcpConnectorRequestCodec,
16098
+ strictCodec: restartMcpConnectorRequestCodec
16099
+ }],
16100
+ cancellation: { parameter: "signal" },
16101
+ result: restartMcpConnectorResultCodec
16102
+ },
16103
+ "agentEnhancer/probeMcpConnector": {
16104
+ service: "agentEnhancer",
16105
+ implementation: "probeMcpConnector",
16106
+ invocation: { kind: "direct" },
16107
+ parameters: [{
16108
+ name: "request",
16109
+ source: "json",
16110
+ codec: probeMcpConnectorRequestCodec,
16111
+ strictCodec: probeMcpConnectorRequestCodec
16112
+ }],
16113
+ cancellation: { parameter: "signal" },
16114
+ result: probeMcpConnectorResultCodec
16115
+ },
14975
16116
  "agentEnhancer/listWebChatWorkspaces": {
14976
16117
  service: "agentEnhancer",
14977
16118
  implementation: "listWebChatWorkspaces",
@@ -15358,319 +16499,6 @@ async function showOsNotificationNow(input) {
15358
16499
  return { shown: false, channel: "none" };
15359
16500
  }
15360
16501
 
15361
- // src/host/update/check.ts
15362
- import { homedir as homedir6 } from "node:os";
15363
- import { join as join32 } from "node:path";
15364
-
15365
- // src/host/update/cli.ts
15366
- import { spawn as nodeSpawn } from "node:child_process";
15367
- import { existsSync as existsSync20 } from "node:fs";
15368
- import { homedir as homedir5 } from "node:os";
15369
- import { posix as pathPosix2 } from "node:path";
15370
- function defaultSpawn(command, args, options) {
15371
- return nodeSpawn(command, [...args], options ?? {});
15372
- }
15373
- var PROBE_TIMEOUT_MS = 5e3;
15374
- var RUN_ADD_TIMEOUT_MS = 12e4;
15375
- var STRICT_SEMVER = /^\d+\.\d+\.\d+$/;
15376
- function isStrictVersion(value) {
15377
- return STRICT_SEMVER.test(value);
15378
- }
15379
- function dshFromElectronExecPath(execPath) {
15380
- const normalized = execPath.replace(/\\/g, "/");
15381
- const marker = "/Contents/MacOS/";
15382
- const idx = normalized.lastIndexOf(marker);
15383
- if (idx < 0) return null;
15384
- const contentsRoot = normalized.slice(0, idx + "/Contents".length);
15385
- return pathPosix2.join(contentsRoot, "Resources", "runtime", "cli", "bin", "dsh");
15386
- }
15387
- function dshExecutableCandidates(options = {}) {
15388
- const platform = options.platform ?? process.platform;
15389
- const env = options.env ?? process.env;
15390
- const home = options.home ?? env.HOME?.trim() ?? homedir5();
15391
- const execPath = options.execPath ?? process.execPath;
15392
- const out = [];
15393
- const push = (value) => {
15394
- const trimmed = typeof value === "string" ? value.trim() : "";
15395
- if (trimmed === "" || out.includes(trimmed)) return;
15396
- out.push(trimmed);
15397
- };
15398
- push(env.DSH_CLI);
15399
- if (platform === "darwin") {
15400
- push(dshFromElectronExecPath(execPath));
15401
- push("/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
15402
- push(pathPosix2.join(
15403
- home,
15404
- "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh"
15405
- ));
15406
- }
15407
- push("dsh");
15408
- return out;
15409
- }
15410
- function isCommandMissingDetail(detail) {
15411
- return /ENOENT|not found|spawn .*(ENOENT|not found)/i.test(detail);
15412
- }
15413
- function dshSpawnOptions() {
15414
- const base = { stdio: ["ignore", "pipe", "pipe"] };
15415
- return process.platform === "win32" ? { ...base, shell: true, windowsHide: true } : base;
15416
- }
15417
- function pluginAddArgs(latest) {
15418
- return ["plugin", "--profile", "desktop", "add", `${PACKAGE_NAME}@${latest}`];
15419
- }
15420
- function pluginAddCommand(latest) {
15421
- return `dsh plugin --profile desktop add ${PACKAGE_NAME}@${latest}`;
15422
- }
15423
- function resolveCanAutoApply(input) {
15424
- return input.installKind === "npm" && input.dshAvailable;
15425
- }
15426
- function waitForExit(child, timeoutMs) {
15427
- return new Promise((resolve17) => {
15428
- let settled = false;
15429
- const chunks = [];
15430
- const finish = (ok, detail) => {
15431
- if (settled) return;
15432
- settled = true;
15433
- clearTimeout(timer);
15434
- resolve17({ ok, detail });
15435
- };
15436
- const timer = setTimeout(() => {
15437
- child.kill();
15438
- finish(false, "timeout");
15439
- }, timeoutMs);
15440
- child.stdout?.on("data", (chunk) => chunks.push(chunk));
15441
- child.stderr?.on("data", (chunk) => chunks.push(chunk));
15442
- child.on("error", (err) => {
15443
- finish(false, err.message);
15444
- });
15445
- child.on("close", (code) => {
15446
- const detail = Buffer.concat(chunks).toString("utf8").trim();
15447
- finish(code === 0, detail);
15448
- });
15449
- });
15450
- }
15451
- async function runDshOnce(command, args, spawnFn, timeoutMs) {
15452
- let child;
15453
- try {
15454
- child = spawnFn(command, args, dshSpawnOptions());
15455
- } catch (err) {
15456
- return { ok: false, detail: err instanceof Error ? err.message : String(err) };
15457
- }
15458
- return waitForExit(child, timeoutMs);
15459
- }
15460
- async function runDsh(args, spawnFn, timeoutMs, options = {}) {
15461
- const candidates = options.candidates ?? dshExecutableCandidates();
15462
- const exists = options.exists ?? existsSync20;
15463
- let last = { ok: false, detail: "dsh not found" };
15464
- for (const command of candidates) {
15465
- if (command !== "dsh" && !exists(command)) continue;
15466
- const result = await runDshOnce(command, args, spawnFn, timeoutMs);
15467
- if (result.ok) return result;
15468
- last = result;
15469
- if (!isCommandMissingDetail(result.detail)) return result;
15470
- }
15471
- return last;
15472
- }
15473
- async function probeDsh(spawnFn = defaultSpawn, options = {}) {
15474
- const result = await runDsh(["--version"], spawnFn, PROBE_TIMEOUT_MS, options);
15475
- return result.ok;
15476
- }
15477
- async function runPluginAdd(latest, spawnFn = defaultSpawn, options = {}) {
15478
- if (!isStrictVersion(latest)) return { ok: false, detail: "invalid version" };
15479
- return runDsh(pluginAddArgs(latest), spawnFn, RUN_ADD_TIMEOUT_MS, options);
15480
- }
15481
-
15482
- // src/host/update/install-kind.ts
15483
- import { lstatSync as lstatSync5 } from "node:fs";
15484
- import { join as join31 } from "node:path";
15485
- function detectInstallKind(profileDir) {
15486
- const pkgPath = join31(profileDir, "node_modules", PACKAGE_NAME);
15487
- try {
15488
- const stat = lstatSync5(pkgPath);
15489
- if (stat.isSymbolicLink()) return "link";
15490
- if (stat.isDirectory()) return "npm";
15491
- return "unknown";
15492
- } catch {
15493
- return "unknown";
15494
- }
15495
- }
15496
-
15497
- // src/host/update/registry.ts
15498
- function defaultSources() {
15499
- return [
15500
- { kind: "npm-dist-tag", baseUrl: "https://registry.npmjs.org" },
15501
- // CDN package.json is reliable when the npm registry is unreachable.
15502
- {
15503
- kind: "package-json",
15504
- url: `https://cdn.jsdelivr.net/npm/${encodeURIComponent(PACKAGE_NAME)}/package.json`
15505
- },
15506
- // Mainland mirror last — some packages publish a misleading `latest` tag there.
15507
- { kind: "npm-dist-tag", baseUrl: "https://registry.npmmirror.com" }
15508
- ];
15509
- }
15510
- function isUsableReleaseVersion(value) {
15511
- return /^\d+\.\d+\.\d+$/.test(value);
15512
- }
15513
- function abortSignal(timeoutMs) {
15514
- try {
15515
- return AbortSignal.timeout(timeoutMs);
15516
- } catch {
15517
- return void 0;
15518
- }
15519
- }
15520
- function readDistTagLatest(body) {
15521
- if (body === null || typeof body !== "object") return null;
15522
- const distTags = body["dist-tags"];
15523
- if (distTags === null || typeof distTags !== "object") return null;
15524
- const latest = distTags.latest;
15525
- if (typeof latest !== "string" || !isUsableReleaseVersion(latest)) return null;
15526
- return latest;
15527
- }
15528
- function readPackageJsonVersion(body) {
15529
- if (body === null || typeof body !== "object") return null;
15530
- const version = body.version;
15531
- if (typeof version !== "string" || !isUsableReleaseVersion(version)) return null;
15532
- return version;
15533
- }
15534
- async function fetchJson(fetchImpl, url, currentVersion, timeoutMs) {
15535
- try {
15536
- const response = await fetchImpl(url, {
15537
- signal: abortSignal(timeoutMs),
15538
- headers: {
15539
- Accept: "application/json",
15540
- "User-Agent": `dsh-agent-enhancer/${currentVersion}`
15541
- }
15542
- });
15543
- if (!response.ok) {
15544
- console.error(`agent-enhancer update: registry ${url} returned ${response.status}`);
15545
- return null;
15546
- }
15547
- return await response.json();
15548
- } catch (error) {
15549
- console.error(`agent-enhancer update: registry fetch failed for ${url}`, error);
15550
- return null;
15551
- }
15552
- }
15553
- async function fetchLatestVersion(packageName, opts = {}) {
15554
- const fetchImpl = opts.fetch ?? globalThis.fetch;
15555
- const currentVersion = opts.currentVersion ?? PACKAGE_VERSION;
15556
- const timeoutMs = opts.timeoutMs ?? 12e3;
15557
- const sources = opts.sources ?? defaultSources();
15558
- for (const source of sources) {
15559
- switch (source.kind) {
15560
- case "npm-dist-tag": {
15561
- const url = `${source.baseUrl.replace(/\/$/, "")}/${encodeURIComponent(packageName)}`;
15562
- const body = await fetchJson(fetchImpl, url, currentVersion, timeoutMs);
15563
- const latest = readDistTagLatest(body);
15564
- if (latest !== null) return latest;
15565
- break;
15566
- }
15567
- case "package-json": {
15568
- const body = await fetchJson(fetchImpl, source.url, currentVersion, timeoutMs);
15569
- const version = readPackageJsonVersion(body);
15570
- if (version !== null) return version;
15571
- break;
15572
- }
15573
- default: {
15574
- const _exhaustive = source;
15575
- return _exhaustive;
15576
- }
15577
- }
15578
- }
15579
- return null;
15580
- }
15581
-
15582
- // src/host/update/semver.ts
15583
- function parseSemver(version) {
15584
- const trimmed = version.startsWith("v") ? version.slice(1) : version;
15585
- const parts = trimmed.split(".");
15586
- if (parts.length !== 3) {
15587
- return null;
15588
- }
15589
- const nums = [];
15590
- for (const part of parts) {
15591
- if (!/^\d+$/.test(part)) {
15592
- return null;
15593
- }
15594
- nums.push(Number(part));
15595
- }
15596
- return nums;
15597
- }
15598
- function isNewerVersion(latest, current) {
15599
- const latestParts = parseSemver(latest);
15600
- const currentParts = parseSemver(current);
15601
- if (latestParts === null || currentParts === null) {
15602
- return false;
15603
- }
15604
- const [lMajor, lMinor, lPatch] = latestParts;
15605
- const [cMajor, cMinor, cPatch] = currentParts;
15606
- if (lMajor !== cMajor) {
15607
- return lMajor > cMajor;
15608
- }
15609
- if (lMinor !== cMinor) {
15610
- return lMinor > cMinor;
15611
- }
15612
- return lPatch > cPatch;
15613
- }
15614
-
15615
- // src/host/update/check.ts
15616
- function resolveDesktopProfileDir(env = process.env, home = homedir6()) {
15617
- const dshHome2 = env.DSH_HOME ?? join32(home, ".dsh");
15618
- return join32(dshHome2, "profiles", "desktop");
15619
- }
15620
- async function checkPluginUpdate(deps) {
15621
- const latest = await deps.fetchLatest();
15622
- const installKind = deps.detectKind(deps.profileDir);
15623
- const dshAvailable = await deps.dshAvailable().catch(() => false);
15624
- const updateAvailable = latest !== null && isNewerVersion(latest, deps.currentVersion);
15625
- const command = pluginAddCommand(latest ?? "latest");
15626
- const canAutoApply = resolveCanAutoApply({ installKind, dshAvailable });
15627
- return {
15628
- current: deps.currentVersion,
15629
- latest,
15630
- updateAvailable,
15631
- installKind,
15632
- canAutoApply,
15633
- command
15634
- };
15635
- }
15636
- async function applyPluginUpdate(input) {
15637
- const { check, runAdd, messages } = input;
15638
- if (check.latest === null || !check.updateAvailable) {
15639
- return { ok: false, message: messages.noUpdate, command: check.command };
15640
- }
15641
- if (!check.canAutoApply) {
15642
- const message = check.installKind === "link" ? messages.linkBlocked : messages.manualOnly ?? messages.failed;
15643
- return { ok: false, message, command: check.command };
15644
- }
15645
- const result = await runAdd(check.latest);
15646
- if (!result.ok) {
15647
- return { ok: false, message: messages.failed, command: check.command };
15648
- }
15649
- return { ok: true, message: messages.success };
15650
- }
15651
- function defaultCheckDeps(overrides = {}) {
15652
- const profileDir = overrides.profileDir ?? resolveDesktopProfileDir();
15653
- return {
15654
- currentVersion: PACKAGE_VERSION,
15655
- fetchLatest: () => fetchLatestVersion(PACKAGE_NAME),
15656
- detectKind: (dir) => detectInstallKind(dir),
15657
- dshAvailable: () => probeDsh(),
15658
- profileDir,
15659
- ...overrides
15660
- };
15661
- }
15662
- async function checkPluginUpdateForHost(overrides) {
15663
- return checkPluginUpdate(defaultCheckDeps(overrides));
15664
- }
15665
- async function applyPluginUpdateForHost(messages, overrides) {
15666
- const check = await checkPluginUpdate(defaultCheckDeps(overrides));
15667
- return applyPluginUpdate({
15668
- check,
15669
- runAdd: (latest) => runPluginAdd(latest),
15670
- messages
15671
- });
15672
- }
15673
-
15674
16502
  // src/host/index.ts
15675
16503
  function hostBrowserPreference(value) {
15676
16504
  return coerceBrowserAgentBrowserForPlatform(
@@ -15761,12 +16589,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
15761
16589
  };
15762
16590
  }
15763
16591
  }, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
15764
- join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
16592
+ join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
15765
16593
  ), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null, browserAgent = null, browserAgentSettings = () => ({
15766
16594
  enabled: false,
15767
16595
  browser: "auto"
15768
16596
  }), setBrowserAgentBrowser = () => void 0, browserAgentProfileDir = defaultBrowserAgentProfileDir(
15769
- join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
16597
+ join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
15770
16598
  )) {
15771
16599
  super(ctx, "agentEnhancer");
15772
16600
  this.models = models;
@@ -15796,7 +16624,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
15796
16624
  browserAgentSettings;
15797
16625
  setBrowserAgentBrowser;
15798
16626
  browserAgentProfileDir;
15799
- browserSnapshotNow() {
16627
+ async browserSnapshotNow() {
15800
16628
  const settings = this.browserAgentSettings();
15801
16629
  const driverStatus = this.browserAgent?.driverStatus();
15802
16630
  const pending = this.browserAgent?.approval.current() ?? null;
@@ -15806,8 +16634,11 @@ var AgentEnhancerService = class extends TypertRemoteService {
15806
16634
  sessionId: waiting.sessionId,
15807
16635
  detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail
15808
16636
  } : 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;
16637
+ 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
16638
  const connected = driverStatus?.ready === true;
16639
+ const listed = connected ? await this.browserAgent?.listTabs() : void 0;
16640
+ const tabs = listed?.tabs ?? [];
16641
+ const boundTabId = overlayBound ?? listed?.boundTabId ?? null;
15811
16642
  const endpoint = driverStatus?.endpoint ?? "playwright:unlaunched";
15812
16643
  const launched = endpoint === "playwright:msedge" ? "edge" : endpoint === "playwright:chrome" ? "chrome" : endpoint === "playwright:webkit" ? "safari" : null;
15813
16644
  return {
@@ -15834,6 +16665,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
15834
16665
  tabConflict: conflict,
15835
16666
  needsHuman,
15836
16667
  boundTabId,
16668
+ tabs: [...tabs],
15837
16669
  audit: [...this.browserAgent?.sessions.recentAudit(12) ?? []],
15838
16670
  profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir
15839
16671
  };
@@ -15868,7 +16700,8 @@ var AgentEnhancerService = class extends TypertRemoteService {
15868
16700
  } catch (error) {
15869
16701
  if (signal.aborted) throw error;
15870
16702
  const code = error instanceof AuxiliaryError ? error.code : "MODEL_FAILED";
15871
- throw new RemoteError2("agent-enhancer/failed", "Agent Enhance request failed", { code });
16703
+ const detail = error instanceof AuxiliaryError ? error.message : "Agent Enhance request failed";
16704
+ throw new RemoteError2("agent-enhancer/failed", detail || "Agent Enhance request failed", { code });
15872
16705
  }
15873
16706
  }
15874
16707
  /** Same Desktop catalog the official model selector uses (`llm` registry). */
@@ -16011,7 +16844,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16011
16844
  }
16012
16845
  }
16013
16846
  webChatPluginDataRoot() {
16014
- return this.installLedgerRoot ?? join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
16847
+ return this.installLedgerRoot ?? join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
16015
16848
  }
16016
16849
  /** User-level web chat guest login snapshot (non-HttpOnly storage only). */
16017
16850
  async loadWebChatLoginSnapshot(_request, signal) {
@@ -16163,10 +16996,6 @@ var AgentEnhancerService = class extends TypertRemoteService {
16163
16996
  throw new RemoteError2("agent-enhancer/failed", detail || "Context compaction failed", { code });
16164
16997
  }
16165
16998
  }
16166
- /** Read-only version probe — same gate policy as `listCatalog` (settings-safe). */
16167
- async checkUpdate() {
16168
- return checkPluginUpdateForHost();
16169
- }
16170
16999
  async usageSummary(range) {
16171
17000
  this.assertOwner();
16172
17001
  return this.usage.summarize(range);
@@ -16383,6 +17212,26 @@ var AgentEnhancerService = class extends TypertRemoteService {
16383
17212
  throw instructionsSkillsRemoteError(error);
16384
17213
  }
16385
17214
  }
17215
+ async restartMcpConnector(request, signal) {
17216
+ this.assertOwner();
17217
+ signal.throwIfAborted();
17218
+ try {
17219
+ return await restartMcpConnectorNow(this.requireMcpHost(), request);
17220
+ } catch (error) {
17221
+ if (signal.aborted) throw error;
17222
+ throw instructionsSkillsRemoteError(error);
17223
+ }
17224
+ }
17225
+ async probeMcpConnector(request, signal) {
17226
+ this.assertOwner();
17227
+ signal.throwIfAborted();
17228
+ try {
17229
+ return await probeMcpConnectorNow(this.requireMcpHost(), request, signal);
17230
+ } catch (error) {
17231
+ if (signal.aborted) throw error;
17232
+ throw instructionsSkillsRemoteError(error);
17233
+ }
17234
+ }
16386
17235
  async listMcpConnectorTools(request, signal) {
16387
17236
  this.assertOwner();
16388
17237
  signal.throwIfAborted();
@@ -16420,22 +17269,22 @@ var AgentEnhancerService = class extends TypertRemoteService {
16420
17269
  }
16421
17270
  async browserAgentSnapshot() {
16422
17271
  this.assertOwner();
16423
- return this.browserSnapshotNow();
17272
+ return await this.browserSnapshotNow();
16424
17273
  }
16425
17274
  async browserAgentResolve(request) {
16426
17275
  this.assertOwner();
16427
17276
  const ok = this.browserAgent?.approval.resolve(request.id, request.decision) ?? false;
16428
- return { ok, snapshot: this.browserSnapshotNow() };
17277
+ return { ok, snapshot: await this.browserSnapshotNow() };
16429
17278
  }
16430
17279
  async browserAgentResolveTabConflict(request) {
16431
17280
  this.assertOwner();
16432
17281
  const result = await this.browserAgent?.resolveTabConflict(request.decision);
16433
- return { ok: result?.ok === true, snapshot: this.browserSnapshotNow() };
17282
+ return { ok: result?.ok === true, snapshot: await this.browserSnapshotNow() };
16434
17283
  }
16435
17284
  async browserAgentAcknowledgeHuman(request) {
16436
17285
  this.assertOwner();
16437
17286
  const ok = this.browserAgent?.acknowledgeHuman(request.sessionId) === true;
16438
- return { ok, snapshot: this.browserSnapshotNow() };
17287
+ return { ok, snapshot: await this.browserSnapshotNow() };
16439
17288
  }
16440
17289
  async browserAgentOpenUrl(request) {
16441
17290
  this.assertOwner();
@@ -16448,7 +17297,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16448
17297
  ...result?.url === void 0 ? {} : { url: result.url },
16449
17298
  ...result?.title === void 0 ? {} : { title: result.title },
16450
17299
  ...result?.error === void 0 ? {} : { error: result.error },
16451
- snapshot: this.browserSnapshotNow()
17300
+ snapshot: await this.browserSnapshotNow()
16452
17301
  };
16453
17302
  }
16454
17303
  async browserAgentQuotePage(request) {
@@ -16460,7 +17309,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16460
17309
  ...result?.url === void 0 ? {} : { url: result.url },
16461
17310
  ...result?.title === void 0 ? {} : { title: result.title },
16462
17311
  ...result?.error === void 0 ? {} : { error: result.error },
16463
- snapshot: this.browserSnapshotNow()
17312
+ snapshot: await this.browserSnapshotNow()
16464
17313
  };
16465
17314
  }
16466
17315
  async browserAgentLaunchBrowser(request) {
@@ -16471,13 +17320,13 @@ var AgentEnhancerService = class extends TypertRemoteService {
16471
17320
  ok: false,
16472
17321
  profileDir: this.browserAgentProfileDir,
16473
17322
  error: "Browser agent is disabled in settings.",
16474
- snapshot: this.browserSnapshotNow()
17323
+ snapshot: await this.browserSnapshotNow()
16475
17324
  };
16476
17325
  }
16477
17326
  const preference = hostBrowserPreference(request.browser ?? settings.browser);
16478
17327
  this.setBrowserAgentBrowser(preference);
16479
17328
  const launched = await this.browserAgent?.launchDedicated(void 0, preference);
16480
- const snapshot = this.browserSnapshotNow();
17329
+ const snapshot = await this.browserSnapshotNow();
16481
17330
  return {
16482
17331
  ok: launched?.ok === true,
16483
17332
  profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir,
@@ -16497,31 +17346,36 @@ var AgentEnhancerService = class extends TypertRemoteService {
16497
17346
  return {
16498
17347
  ok: true,
16499
17348
  browser: preference,
16500
- snapshot: this.browserSnapshotNow()
17349
+ snapshot: await this.browserSnapshotNow()
16501
17350
  };
16502
17351
  }
16503
- async applyUpdate() {
17352
+ async browserAgentSelectTab(request) {
16504
17353
  this.assertOwner();
16505
- return applyPluginUpdateForHost({
16506
- linkBlocked: "link",
16507
- success: "restart",
16508
- failed: "failed",
16509
- noUpdate: "none",
16510
- manualOnly: "manual"
17354
+ const result = await this.browserAgent?.selectTab({
17355
+ tabId: request.tabId,
17356
+ ...request.sessionId === void 0 ? {} : { sessionId: request.sessionId }
16511
17357
  });
17358
+ return {
17359
+ ok: result?.ok === true,
17360
+ ...result?.tabId === void 0 ? {} : { tabId: result.tabId },
17361
+ ...result?.url === void 0 ? {} : { url: result.url },
17362
+ ...result?.title === void 0 ? {} : { title: result.title },
17363
+ ...result?.error === void 0 ? {} : { error: result.error },
17364
+ snapshot: await this.browserSnapshotNow()
17365
+ };
16512
17366
  }
16513
17367
  };
16514
17368
  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");
16519
- if (!existsSync21(next) && existsSync21(prev)) {
16520
- mkdirSync11(nextPkg, { recursive: true });
17369
+ const base = join30(dshHome2, "profiles", "desktop", "plugin-data");
17370
+ const nextPkg = join30(base, PACKAGE_NAME);
17371
+ const next = join30(nextPkg, "checkpoint");
17372
+ const prev = join30(base, LEGACY_PACKAGE_NAME, "checkpoint");
17373
+ if (!existsSync20(next) && existsSync20(prev)) {
17374
+ mkdirSync12(nextPkg, { recursive: true });
16521
17375
  renameSync9(prev, next);
16522
- const prevPkg = join33(base, LEGACY_PACKAGE_NAME);
17376
+ const prevPkg = join30(base, LEGACY_PACKAGE_NAME);
16523
17377
  try {
16524
- if (existsSync21(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
17378
+ if (existsSync20(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
16525
17379
  } catch {
16526
17380
  }
16527
17381
  }
@@ -16624,9 +17478,9 @@ function apply(ctx, config) {
16624
17478
  const settings = () => readSettings(config);
16625
17479
  const models = new AuxiliaryModels(ctx, settings);
16626
17480
  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) => {
17481
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join30(homedir5(), ".dsh"));
17482
+ const pluginDataPackageRoot = join30(storageRoot, "..");
17483
+ const usage = new UsageLedger(join30(storageRoot, "..", "usage"), (message) => {
16630
17484
  ctx.logger.warn(message);
16631
17485
  });
16632
17486
  const balancesFacade = (() => {
@@ -16656,12 +17510,12 @@ function apply(ctx, config) {
16656
17510
  })();
16657
17511
  installUsageObserver(ctx, usage);
16658
17512
  const store = new CheckpointStore(storageRoot);
16659
- const cutStore = new SessionCutStore(join33(storageRoot, "cuts"));
17513
+ const cutStore = new SessionCutStore(join30(storageRoot, "cuts"));
16660
17514
  const cutCache = /* @__PURE__ */ new Map();
16661
17515
  const sessionCleanup = new SessionCleanupRegistry();
16662
17516
  sessionCleanup.register(createCheckpointCleaner({ store, cutStore, storageRoot }));
16663
- sessionCleanup.register(createContextExcludeCleaner(join33(storageRoot, "..")));
16664
- const extraFoldersStore = createExtraFoldersStore(join33(storageRoot, "..", "extra-folders"));
17517
+ sessionCleanup.register(createContextExcludeCleaner(join30(storageRoot, "..")));
17518
+ const extraFoldersStore = createExtraFoldersStore(join30(storageRoot, "..", "extra-folders"));
16665
17519
  const softPauseGate = new SoftPauseGate();
16666
17520
  const mcpStore = createMcpConnectorsStore(mcpConnectorsRoot(pluginDataPackageRoot));
16667
17521
  const mcpRuntime = new McpConnectorRuntime(ctx, mcpStore);
@@ -16741,13 +17595,11 @@ function apply(ctx, config) {
16741
17595
  const detail = error instanceof Error ? error.message : String(error);
16742
17596
  ctx.logger.warn(`agent-enhancer: MCP connector sync after settings update failed: ${detail}`);
16743
17597
  });
16744
- const prevEnabled = browserAgentLive.enabled;
16745
17598
  const prevBrowser = browserAgentLive.browser;
16746
17599
  browserAgentLive.enabled = cfg.browserAgentEnabled.get();
16747
17600
  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) {
17601
+ browserAgent.refresh();
17602
+ if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
16751
17603
  void browserAgent.alignToPreference().catch((error) => {
16752
17604
  const detail = error instanceof Error ? error.message : String(error);
16753
17605
  ctx.logger.warn(`agent-enhancer: browser preference align after settings failed: ${detail}`);