dsh-agent-enhancer 0.3.10 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.en.md +22 -7
  2. package/README.md +22 -7
  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-features.d.ts.map +1 -1
  8. package/lib/client/index.d.ts.map +1 -1
  9. package/lib/client/locales.d.ts +79 -17
  10. package/lib/client/locales.d.ts.map +1 -1
  11. package/lib/client/mcp-connectors/remote.d.ts +7 -1
  12. package/lib/client/mcp-connectors/remote.d.ts.map +1 -1
  13. package/lib/client/mcp-connectors/tab.d.ts.map +1 -1
  14. package/lib/client/quote/position.d.ts +8 -6
  15. package/lib/client/quote/position.d.ts.map +1 -1
  16. package/lib/client/remote.d.ts +4 -1
  17. package/lib/client/remote.d.ts.map +1 -1
  18. package/lib/client/soft-pause/action.d.ts.map +1 -1
  19. package/lib/client/web-chat-bridge/capture.d.ts +2 -0
  20. package/lib/client/web-chat-bridge/capture.d.ts.map +1 -1
  21. package/lib/client/web-chat-bridge/dom-to-markdown.d.ts +13 -0
  22. package/lib/client/web-chat-bridge/dom-to-markdown.d.ts.map +1 -0
  23. package/lib/client/web-chat-bridge/panel.d.ts.map +1 -1
  24. package/lib/client/web-chat-bridge/preview.d.ts.map +1 -1
  25. package/lib/client/web-chat-bridge/remote.d.ts.map +1 -1
  26. package/lib/client/web-chat-bridge/share-fetch.d.ts +4 -0
  27. package/lib/client/web-chat-bridge/share-fetch.d.ts.map +1 -1
  28. package/lib/client.js +944 -195
  29. package/lib/client.js.map +1 -1
  30. package/lib/config.d.ts +15 -3
  31. package/lib/config.d.ts.map +1 -1
  32. package/lib/errors.d.ts +1 -1
  33. package/lib/errors.d.ts.map +1 -1
  34. package/lib/host/auto-route/errors.d.ts +8 -0
  35. package/lib/host/auto-route/errors.d.ts.map +1 -0
  36. package/lib/host/auto-route/router.d.ts.map +1 -1
  37. package/lib/host/auto-route/session-hook.d.ts.map +1 -1
  38. package/lib/host/browser-agent/driver.d.ts +3 -1
  39. package/lib/host/browser-agent/driver.d.ts.map +1 -1
  40. package/lib/host/browser-agent/install.d.ts +17 -0
  41. package/lib/host/browser-agent/install.d.ts.map +1 -1
  42. package/lib/host/browser-agent/launch.d.ts +26 -6
  43. package/lib/host/browser-agent/launch.d.ts.map +1 -1
  44. package/lib/host/browser-agent/playwright-driver.d.ts +12 -1
  45. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  46. package/lib/host/browser-agent/prompt.d.ts.map +1 -1
  47. package/lib/host/browser-agent/tools.d.ts +2 -2
  48. package/lib/host/browser-agent/tools.d.ts.map +1 -1
  49. package/lib/host/context-compact.d.ts.map +1 -1
  50. package/lib/host/index.d.ts +7 -4
  51. package/lib/host/index.d.ts.map +1 -1
  52. package/lib/host/mcp-connectors/io.d.ts +3 -1
  53. package/lib/host/mcp-connectors/io.d.ts.map +1 -1
  54. package/lib/host/mcp-connectors/probe-message.d.ts +7 -0
  55. package/lib/host/mcp-connectors/probe-message.d.ts.map +1 -0
  56. package/lib/host/mcp-connectors/runtime.d.ts +11 -0
  57. package/lib/host/mcp-connectors/runtime.d.ts.map +1 -1
  58. package/lib/host/mcp-connectors/status.d.ts +32 -0
  59. package/lib/host/mcp-connectors/status.d.ts.map +1 -0
  60. package/lib/host/mcp-connectors/types.d.ts +33 -0
  61. package/lib/host/mcp-connectors/types.d.ts.map +1 -1
  62. package/lib/host/model.d.ts.map +1 -1
  63. package/lib/host/rpc.d.ts +392 -0
  64. package/lib/host/rpc.d.ts.map +1 -1
  65. package/lib/host/update/cli.d.ts +28 -2
  66. package/lib/host/update/cli.d.ts.map +1 -1
  67. package/lib/host/web-chat-bridge/import-session.d.ts +10 -1
  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/identity.d.ts +1 -1
  72. package/lib/index.js +1009 -267
  73. package/lib/index.js.map +4 -4
  74. package/package.json +56 -56
  75. package/lib/client/web-chat-bridge/export-markdown.test.d.ts +0 -2
  76. package/lib/client/web-chat-bridge/export-markdown.test.d.ts.map +0 -1
  77. package/lib/client/web-chat-bridge/guest-policy-clipboard.test.d.ts +0 -2
  78. package/lib/client/web-chat-bridge/guest-policy-clipboard.test.d.ts.map +0 -1
  79. package/lib/host/browser-agent/auto-nav.test.d.ts +0 -2
  80. package/lib/host/browser-agent/auto-nav.test.d.ts.map +0 -1
  81. package/lib/host/browser-agent/extract.test.d.ts +0 -2
  82. package/lib/host/browser-agent/extract.test.d.ts.map +0 -1
  83. package/lib/host/browser-agent/human-gate.test.d.ts +0 -2
  84. package/lib/host/browser-agent/human-gate.test.d.ts.map +0 -1
  85. package/lib/host/browser-agent/page-links.test.d.ts +0 -2
  86. package/lib/host/browser-agent/page-links.test.d.ts.map +0 -1
  87. package/lib/host/browser-agent/path-key.test.d.ts +0 -2
  88. package/lib/host/browser-agent/path-key.test.d.ts.map +0 -1
  89. package/lib/host/browser-agent/pick-auto-nav.test.d.ts +0 -2
  90. package/lib/host/browser-agent/pick-auto-nav.test.d.ts.map +0 -1
  91. package/lib/host/extra-folders/pick.test.d.ts +0 -2
  92. package/lib/host/extra-folders/pick.test.d.ts.map +0 -1
  93. package/lib/host/web-chat-bridge/parse-export.test.d.ts +0 -2
  94. package/lib/host/web-chat-bridge/parse-export.test.d.ts.map +0 -1
  95. package/lib/host/web-chat-bridge/share-link.test.d.ts +0 -2
  96. package/lib/host/web-chat-bridge/share-link.test.d.ts.map +0 -1
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/host/index.ts
2
- import { existsSync as existsSync19, mkdirSync as mkdirSync11, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
- import { homedir as homedir6 } from "node:os";
2
+ import { existsSync as existsSync21, mkdirSync as mkdirSync12, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
+ import { homedir as homedir7 } from "node:os";
4
4
  import { join as join32 } from "node:path";
5
5
  import z5 from "@deepseek-ai/schemastery";
6
6
  import { RemoteError as RemoteError2, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
@@ -25,11 +25,29 @@ function resolveBrowserAgentBrowser(value) {
25
25
  case "auto":
26
26
  case "chrome":
27
27
  case "edge":
28
+ case "safari":
28
29
  return value;
29
30
  default:
30
31
  return "auto";
31
32
  }
32
33
  }
34
+ function browserAgentBrowsersForPlatform(platform) {
35
+ switch (platform) {
36
+ case "darwin":
37
+ return ["auto", "chrome", "safari"];
38
+ case "win32":
39
+ return ["auto", "chrome", "edge"];
40
+ default:
41
+ return ["auto", "chrome"];
42
+ }
43
+ }
44
+ function coerceBrowserAgentBrowserForPlatform(value, platform) {
45
+ const allowed = browserAgentBrowsersForPlatform(platform);
46
+ if (allowed.includes(value)) return value;
47
+ if (value === "edge" && platform === "darwin") return "safari";
48
+ if (value === "safari" && platform === "win32") return "edge";
49
+ return "auto";
50
+ }
33
51
  var DEFAULT_AUXILIARY_MODEL = {
34
52
  provider: "",
35
53
  model: "",
@@ -385,7 +403,16 @@ var BrowserHumanGate = class {
385
403
  import { execFileSync } from "node:child_process";
386
404
  import { existsSync } from "node:fs";
387
405
  import { homedir } from "node:os";
388
- import { join } from "node:path";
406
+ import { join, posix as pathPosix } from "node:path";
407
+ var BROWSER_AGENT_PROFILE_SLOTS = [
408
+ "auto",
409
+ "auto-chrome",
410
+ "auto-msedge",
411
+ "auto-webkit",
412
+ "chrome",
413
+ "edge",
414
+ "safari"
415
+ ];
389
416
  function windowsEnv(name2, env = process.env) {
390
417
  const variants = [
391
418
  name2,
@@ -404,8 +431,23 @@ function windowsEnv(name2, env = process.env) {
404
431
  }
405
432
  return void 0;
406
433
  }
434
+ function uniquePaths(paths) {
435
+ const out = [];
436
+ for (const path of paths) {
437
+ if (path.trim() === "" || out.includes(path)) continue;
438
+ out.push(path);
439
+ }
440
+ return out;
441
+ }
442
+ function darwinAppExecutable(appName, binaryName, home) {
443
+ const relative4 = pathPosix.join(`${appName}.app`, "Contents", "MacOS", binaryName);
444
+ return [
445
+ pathPosix.join("/Applications", relative4),
446
+ pathPosix.join(home, "Applications", relative4)
447
+ ];
448
+ }
407
449
  function browserExecutableCandidates(kind, platform = process.platform, env = process.env) {
408
- const home = homedir();
450
+ const home = env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();
409
451
  if (platform === "win32") {
410
452
  const local = windowsEnv("LocalAppData", env);
411
453
  const programFiles64 = windowsEnv("ProgramW6432", env) ?? "C:\\Program Files";
@@ -423,6 +465,7 @@ function browserExecutableCandidates(kind, platform = process.platform, env = pr
423
465
  join(home, "AppData", "Local", "Google", "Chrome", "Application", "chrome.exe")
424
466
  ];
425
467
  }
468
+ if (kind === "safari") return [];
426
469
  return [
427
470
  ...roots.map((root) => join(root, "Microsoft", "Edge", "Application", "msedge.exe")),
428
471
  "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
@@ -432,17 +475,33 @@ function browserExecutableCandidates(kind, platform = process.platform, env = pr
432
475
  }
433
476
  if (platform === "darwin") {
434
477
  if (kind === "chrome") {
435
- return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
478
+ return uniquePaths([
479
+ ...darwinAppExecutable("Google Chrome", "Google Chrome", home),
480
+ ...darwinAppExecutable("Google Chrome Canary", "Google Chrome Canary", home),
481
+ ...darwinAppExecutable("Chromium", "Chromium", home)
482
+ ]);
483
+ }
484
+ if (kind === "safari") {
485
+ return uniquePaths([
486
+ ...darwinAppExecutable("Safari", "Safari", home)
487
+ ]);
436
488
  }
437
- return ["/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];
489
+ return uniquePaths([
490
+ ...darwinAppExecutable("Microsoft Edge", "Microsoft Edge", home),
491
+ ...darwinAppExecutable("Microsoft Edge Beta", "Microsoft Edge Beta", home),
492
+ ...darwinAppExecutable("Microsoft Edge Dev", "Microsoft Edge Dev", home)
493
+ ]);
438
494
  }
439
495
  if (kind === "chrome") {
440
496
  return ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser"];
441
497
  }
498
+ if (kind === "safari") {
499
+ return [];
500
+ }
442
501
  return ["/usr/bin/microsoft-edge", "/usr/bin/microsoft-edge-stable"];
443
502
  }
444
503
  function lookUpOnPath(kind, platform, where, exists) {
445
- const names = platform === "win32" ? kind === "chrome" ? ["chrome.exe", "chrome"] : ["msedge.exe", "msedge"] : kind === "chrome" ? ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"] : ["microsoft-edge", "microsoft-edge-stable", "msedge"];
504
+ const names = platform === "win32" ? kind === "chrome" ? ["chrome.exe", "chrome"] : kind === "edge" ? ["msedge.exe", "msedge"] : [] : kind === "chrome" ? ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"] : kind === "edge" ? ["microsoft-edge", "microsoft-edge-stable", "msedge"] : [];
446
505
  for (const name2 of names) {
447
506
  const hit = where(name2);
448
507
  if (hit !== null && exists(hit)) return hit;
@@ -471,7 +530,7 @@ function resolveBrowserExecutable(preference = "auto", options = {}) {
471
530
  const exists = options.exists ?? existsSync;
472
531
  const platform = options.platform ?? process.platform;
473
532
  const env = options.env ?? process.env;
474
- const order = preference === "auto" ? platform === "win32" ? ["edge", "chrome"] : ["chrome", "edge"] : [preference];
533
+ const order = preference === "auto" ? platform === "win32" ? ["edge", "chrome"] : platform === "darwin" ? ["safari", "chrome"] : ["chrome"] : [preference];
475
534
  for (const kind of order) {
476
535
  const seen = /* @__PURE__ */ new Set();
477
536
  for (const executable of browserExecutableCandidates(kind, platform, env)) {
@@ -487,14 +546,29 @@ function resolveBrowserExecutable(preference = "auto", options = {}) {
487
546
  function defaultBrowserAgentProfileDir(pluginDataPackageRoot) {
488
547
  return browserAgentProfileDirFor(pluginDataPackageRoot, "auto");
489
548
  }
490
- function browserAgentProfileDirFor(pluginDataPackageRoot, preference) {
491
- const slot = preference === "chrome" || preference === "edge" ? preference : "auto";
549
+ function browserAgentProfileSlotDir(pluginDataPackageRoot, slot) {
492
550
  return join(pluginDataPackageRoot, "browser-agent", `profile-${slot}`);
493
551
  }
552
+ function browserAgentProfileDirFor(pluginDataPackageRoot, preference, channel) {
553
+ if (preference === "chrome" || preference === "edge" || preference === "safari") {
554
+ return browserAgentProfileSlotDir(pluginDataPackageRoot, preference);
555
+ }
556
+ if (channel === "chrome" || channel === "msedge" || channel === "webkit") {
557
+ return browserAgentProfileSlotDir(pluginDataPackageRoot, `auto-${channel}`);
558
+ }
559
+ return browserAgentProfileSlotDir(pluginDataPackageRoot, "auto");
560
+ }
494
561
  function playwrightChannelOrder(preference, platform = process.platform) {
495
562
  if (preference === "chrome") return ["chrome"];
496
563
  if (preference === "edge") return ["msedge"];
497
- return platform === "win32" ? ["msedge", "chrome"] : ["chrome", "msedge"];
564
+ if (preference === "safari") return ["webkit"];
565
+ if (platform === "win32") return ["msedge", "chrome"];
566
+ if (platform === "darwin") return ["webkit", "chrome"];
567
+ return ["chrome"];
568
+ }
569
+ function playwrightChannelSatisfiesPreference(channel, preference, platform = process.platform) {
570
+ if (channel === null || channel === void 0) return false;
571
+ return playwrightChannelOrder(preference, platform).includes(channel);
498
572
  }
499
573
  function stopAgentBrowserProcesses(profileDir) {
500
574
  if (profileDir.trim() === "") return;
@@ -530,8 +604,8 @@ function stopAgentBrowserProcesses(profileDir) {
530
604
  }
531
605
 
532
606
  // src/host/browser-agent/playwright-driver.ts
533
- import { mkdirSync } from "node:fs";
534
- import { chromium } from "playwright-core";
607
+ import { existsSync as existsSync2, mkdirSync } from "node:fs";
608
+ import { chromium, webkit } from "playwright-core";
535
609
 
536
610
  // src/host/browser-agent/proximity.ts
537
611
  function attachHrefByProximity(nodes, anchors) {
@@ -957,6 +1031,13 @@ var PlaywrightDriver = class {
957
1031
  currentProfileDir() {
958
1032
  return typeof this.profileDirOption === "function" ? this.profileDirOption() : this.profileDirOption;
959
1033
  }
1034
+ /** Resolve the on-disk profile for a preference (+ auto channel isolation). */
1035
+ profileDirFor(preference, channel) {
1036
+ if (this.profileRoot !== void 0) {
1037
+ return browserAgentProfileDirFor(this.profileRoot, preference, channel);
1038
+ }
1039
+ return this.currentProfileDir();
1040
+ }
960
1041
  /** Latest snapshot refs — used by the click/type path. */
961
1042
  refOf(ref) {
962
1043
  return this.lastRefs.get(ref);
@@ -974,9 +1055,8 @@ var PlaywrightDriver = class {
974
1055
  }
975
1056
  async ensureReady(startUrl) {
976
1057
  const preference = this.currentPreference();
977
- const profileDir = this.currentProfileDir();
978
- const wantChannel = playwrightChannelOrder(preference, process.platform)[0];
979
- const runningOk = this.context !== null && this.page !== null && !this.page.isClosed() && this.channel === wantChannel && this.launchedProfileDir === profileDir;
1058
+ const order = [...playwrightChannelOrder(preference, process.platform)];
1059
+ const runningOk = this.context !== null && this.page !== null && !this.page.isClosed() && playwrightChannelSatisfiesPreference(this.channel, preference, process.platform) && this.launchedProfileDir !== null && this.channel !== null && this.launchedProfileDir === this.profileDirFor(preference, this.channel);
980
1060
  if (runningOk) {
981
1061
  if (typeof startUrl === "string" && /^https?:\/\//i.test(startUrl)) {
982
1062
  const current = this.page.url();
@@ -989,34 +1069,18 @@ var PlaywrightDriver = class {
989
1069
  if (this.context !== null) {
990
1070
  await this.dispose().catch(() => void 0);
991
1071
  }
992
- this.stopPreferenceProfiles(profileDir);
993
- mkdirSync(profileDir, { recursive: true });
994
- const order = [...playwrightChannelOrder(preference, process.platform)];
1072
+ this.stopPreferenceProfiles(this.profileDirFor(preference));
995
1073
  let lastDetail = "";
996
1074
  for (const channel of order) {
997
- const kind = channel === "msedge" ? "edge" : "chrome";
998
- const resolved = resolveBrowserExecutable(kind);
999
- if (preference === "chrome" || preference === "edge") {
1000
- if (resolved === null || resolved.kind !== preference) {
1001
- lastDetail = `${preference} is not installed or not found on PATH`;
1002
- this.lastError = lastDetail;
1075
+ const profileDir = this.profileDirFor(preference, channel);
1076
+ mkdirSync(profileDir, { recursive: true });
1077
+ stopAgentBrowserProcesses(profileDir);
1078
+ try {
1079
+ const context = channel === "webkit" ? await this.launchWebkit(profileDir, preference) : await this.launchChromium(profileDir, preference, channel);
1080
+ if (context === null) {
1081
+ lastDetail = this.lastError ?? `${channel} is not available`;
1003
1082
  continue;
1004
1083
  }
1005
- } else if (resolved === null) {
1006
- lastDetail = `${kind} is not installed or not found on PATH`;
1007
- this.lastError = lastDetail;
1008
- continue;
1009
- }
1010
- try {
1011
- const context = await chromium.launchPersistentContext(profileDir, {
1012
- executablePath: resolved.executable,
1013
- headless: this.headless,
1014
- // Avoid Edge/Chrome infobar: "unsupported command-line flag: --no-sandbox".
1015
- chromiumSandbox: true,
1016
- ignoreDefaultArgs: ["--no-sandbox"],
1017
- viewport: this.headless ? { width: 1280, height: 800 } : null,
1018
- args: ["--no-first-run", "--no-default-browser-check", "--disable-default-apps"]
1019
- });
1020
1084
  this.context = context;
1021
1085
  this.channel = channel;
1022
1086
  this.launchedProfileDir = profileDir;
@@ -1037,19 +1101,72 @@ var PlaywrightDriver = class {
1037
1101
  this.lastError = lastDetail;
1038
1102
  }
1039
1103
  }
1040
- const hint = preference === "chrome" || preference === "edge" ? ` Preference is locked to ${preference} (no silent fallback).` : "";
1104
+ const hint = preference === "chrome" || preference === "edge" || preference === "safari" ? ` Preference is locked to ${preference} (no silent fallback).` : "";
1041
1105
  throw new Error(
1042
1106
  `Playwright could not launch a persistent browser (tried ${order.join(", ")}): ${lastDetail}.${hint}`
1043
1107
  );
1044
1108
  }
1109
+ /**
1110
+ * Safari preference uses Playwright WebKit (Safari engine). Branded Safari.app
1111
+ * cannot be driven by Playwright; require system Safari to be present as a
1112
+ * platform gate, then launch the WebKit automation build.
1113
+ */
1114
+ async launchWebkit(profileDir, preference) {
1115
+ if (preference === "safari") {
1116
+ const safari = resolveBrowserExecutable("safari", {
1117
+ platform: process.platform
1118
+ });
1119
+ if (safari === null) {
1120
+ this.lastError = "Safari is not installed";
1121
+ return null;
1122
+ }
1123
+ }
1124
+ let webkitExe;
1125
+ try {
1126
+ webkitExe = webkit.executablePath();
1127
+ } catch (error) {
1128
+ this.lastError = error instanceof Error ? error.message : "Playwright WebKit is unavailable";
1129
+ return null;
1130
+ }
1131
+ if (!existsSync2(webkitExe)) {
1132
+ this.lastError = "WEBKIT_MISSING: Playwright WebKit is not installed. Run: npx playwright install webkit";
1133
+ return null;
1134
+ }
1135
+ return webkit.launchPersistentContext(profileDir, {
1136
+ headless: this.headless,
1137
+ viewport: this.headless ? { width: 1280, height: 800 } : null
1138
+ });
1139
+ }
1140
+ async launchChromium(profileDir, preference, channel) {
1141
+ const kind = channel === "msedge" ? "edge" : "chrome";
1142
+ const resolved = resolveBrowserExecutable(kind);
1143
+ if (preference === "chrome" || preference === "edge") {
1144
+ if (resolved === null || resolved.kind !== preference) {
1145
+ this.lastError = `${preference} is not installed or not found on PATH`;
1146
+ return null;
1147
+ }
1148
+ } else if (resolved === null) {
1149
+ this.lastError = `${kind} is not installed or not found on PATH`;
1150
+ return null;
1151
+ }
1152
+ return chromium.launchPersistentContext(profileDir, {
1153
+ executablePath: resolved.executable,
1154
+ headless: this.headless,
1155
+ // Avoid Edge/Chrome infobar: "unsupported command-line flag: --no-sandbox".
1156
+ chromiumSandbox: true,
1157
+ ignoreDefaultArgs: ["--no-sandbox"],
1158
+ viewport: this.headless ? { width: 1280, height: 800 } : null,
1159
+ args: ["--no-first-run", "--no-default-browser-check", "--disable-default-apps"]
1160
+ });
1161
+ }
1045
1162
  stopPreferenceProfiles(activeProfileDir) {
1046
1163
  stopAgentBrowserProcesses(activeProfileDir);
1047
1164
  if (this.launchedProfileDir !== null && this.launchedProfileDir !== activeProfileDir) {
1048
1165
  stopAgentBrowserProcesses(this.launchedProfileDir);
1049
1166
  }
1050
1167
  if (this.profileRoot !== void 0) {
1051
- for (const slot of ["auto", "chrome", "edge"]) {
1052
- const dir = browserAgentProfileDirFor(this.profileRoot, slot);
1168
+ for (const slot of BROWSER_AGENT_PROFILE_SLOTS) {
1169
+ const dir = browserAgentProfileSlotDir(this.profileRoot, slot);
1053
1170
  if (dir !== activeProfileDir) stopAgentBrowserProcesses(dir);
1054
1171
  }
1055
1172
  }
@@ -1067,26 +1184,33 @@ var PlaywrightDriver = class {
1067
1184
  connected: true,
1068
1185
  url: page.url(),
1069
1186
  title: await page.title().catch(() => ""),
1070
- tabId: 1,
1187
+ tabId: tabIdOf(page.context(), page),
1071
1188
  bound: true
1072
1189
  };
1073
1190
  }
1074
- async navigate(url) {
1075
- 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
+ }
1076
1200
  await page.goto(url, { waitUntil: "domcontentloaded" });
1077
1201
  await settlePage(page);
1078
1202
  this.lastRefs.clear();
1079
1203
  return {
1080
1204
  url: page.url(),
1081
1205
  title: await page.title().catch(() => ""),
1082
- tabId: 1
1206
+ tabId: tabIdOf(page.context(), page)
1083
1207
  };
1084
1208
  }
1085
1209
  async snapshot() {
1086
1210
  const page = await this.requirePage();
1087
1211
  const { body, refs } = await capturePlaywrightSnapshot(page);
1088
1212
  this.lastRefs = new Map(refs);
1089
- return body;
1213
+ return { ...body, tabId: tabIdOf(page.context(), page) };
1090
1214
  }
1091
1215
  async extract(input = {}) {
1092
1216
  const page = await this.requirePage();
@@ -1099,7 +1223,7 @@ var PlaywrightDriver = class {
1099
1223
  text: clipped.slice(0, maxChars),
1100
1224
  truncated: clipped.length > maxChars,
1101
1225
  ...input.focus === void 0 || input.focus.trim() === "" ? {} : { focus: input.focus.trim() },
1102
- tabId: 1
1226
+ tabId: tabIdOf(page.context(), page)
1103
1227
  };
1104
1228
  }
1105
1229
  async click(ref) {
@@ -1129,7 +1253,7 @@ var PlaywrightDriver = class {
1129
1253
  title: await page.title().catch(() => ""),
1130
1254
  changed: pathsDiffer(beforeUrl, after),
1131
1255
  href,
1132
- tabId: 1,
1256
+ tabId: tabIdOf(page.context(), page),
1133
1257
  warning: "Opened this ref's href after snapshot bound a nearby document link."
1134
1258
  };
1135
1259
  }
@@ -1181,7 +1305,7 @@ var PlaywrightDriver = class {
1181
1305
  url: afterUrl,
1182
1306
  title: await page.title().catch(() => ""),
1183
1307
  changed,
1184
- tabId: 1,
1308
+ tabId: tabIdOf(page.context(), page),
1185
1309
  ...href !== "" ? { href } : {},
1186
1310
  ...pageLinks.length > 0 ? { pageLinks: pageLinks.slice(0, 8) } : {},
1187
1311
  ...followedHref ? { warning: "Click missed; opened this ref's own href via navigation." } : !changed ? {
@@ -1200,7 +1324,7 @@ var PlaywrightDriver = class {
1200
1324
  title: await page.title().catch(() => ""),
1201
1325
  changed: pathsDiffer(beforeUrl, after),
1202
1326
  href,
1203
- tabId: 1,
1327
+ tabId: tabIdOf(page.context(), page),
1204
1328
  warning: "Ref stamp missing; opened this ref's href directly."
1205
1329
  };
1206
1330
  }
@@ -1215,7 +1339,7 @@ var PlaywrightDriver = class {
1215
1339
  url: afterUrl,
1216
1340
  title: await page.title().catch(() => ""),
1217
1341
  changed,
1218
- tabId: 1,
1342
+ tabId: tabIdOf(page.context(), page),
1219
1343
  ...href !== "" ? { href } : {},
1220
1344
  ...!changed ? {
1221
1345
  warning: "Pathname unchanged after coordinate click. browser_snapshot again or browser_navigate by href."
@@ -1245,14 +1369,19 @@ var PlaywrightDriver = class {
1245
1369
  url: page.url(),
1246
1370
  title: await page.title().catch(() => ""),
1247
1371
  changed: false,
1248
- tabId: 1
1372
+ tabId: tabIdOf(page.context(), page)
1249
1373
  };
1250
1374
  }
1251
1375
  async scroll(dy) {
1252
1376
  const page = await this.requirePage();
1253
1377
  await page.mouse.wheel(0, dy);
1254
1378
  await sleep(80);
1255
- 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
+ };
1256
1385
  }
1257
1386
  async wait(input = {}) {
1258
1387
  const page = await this.requirePage();
@@ -1272,23 +1401,30 @@ var PlaywrightDriver = class {
1272
1401
  url: page.url(),
1273
1402
  title: await page.title().catch(() => ""),
1274
1403
  matched,
1275
- tabId: 1
1404
+ tabId: tabIdOf(page.context(), page)
1276
1405
  };
1277
1406
  }
1278
1407
  async screenshot() {
1279
1408
  const page = await this.requirePage();
1280
1409
  const buf = await page.screenshot({ type: "png", fullPage: false });
1281
- 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
+ };
1282
1415
  }
1283
1416
  async listTabs() {
1284
- await this.ensureReady();
1285
1417
  const pages = this.context?.pages() ?? [];
1418
+ if (pages.length === 0) {
1419
+ return { tabs: [], boundTabId: null };
1420
+ }
1286
1421
  return {
1287
1422
  tabs: await Promise.all(pages.map(async (p, index) => ({
1288
1423
  tabId: index + 1,
1289
1424
  title: await p.title().catch(() => ""),
1290
1425
  url: p.url(),
1291
1426
  active: p === this.page,
1427
+ // Session bind is layered in install.listTabs; driver marks the live page.
1292
1428
  bound: p === this.page
1293
1429
  }))),
1294
1430
  boundTabId: this.page ? pages.indexOf(this.page) + 1 : null
@@ -1382,10 +1518,12 @@ async function listHttpAnchors(page) {
1382
1518
  // src/host/browser-agent/prompt.ts
1383
1519
  var SECTION_NAME = "agent-enhancer:browser-agent";
1384
1520
  var GUIDANCE = [
1385
- "## Browser agent (Desktop dedicated Chrome/Edge)",
1521
+ "## Browser agent (Desktop dedicated browser: Safari/Chrome on Mac, Chrome/Edge on Windows)",
1386
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.",
1387
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.",
1388
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.",
1389
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.",
1390
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.",
1391
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.",
@@ -1838,7 +1976,7 @@ function registerBrowserTools(ctx, options) {
1838
1976
  };
1839
1977
  disposers.push(ctx.tools.register(textTool(
1840
1978
  "browser_status",
1841
- "Check the Desktop dedicated-browser bridge (Chrome/Edge + extension): connection, bound tab URL/title/tabId. Use this for any real-browser / webpage / on-page task. Auto-launches the dedicated browser when disconnected \u2014 do not ask the user to launch manually first.",
1979
+ "Check the Desktop dedicated-browser bridge (Mac: Safari/Chrome; Windows: Chrome/Edge): connection, bound tab URL/title/tabId. Use this for any real-browser / webpage / on-page task. Auto-launches the dedicated browser when disconnected \u2014 do not ask the user to launch manually first.",
1842
1980
  {},
1843
1981
  async (_args, exec) => {
1844
1982
  guardEnabled();
@@ -1974,44 +2112,57 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
1974
2112
  )));
1975
2113
  disposers.push(ctx.tools.register(textTool(
1976
2114
  "browser_navigate",
1977
- "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.",
1978
2116
  {
1979
2117
  url: {
1980
2118
  type: "string",
1981
2119
  required: true,
1982
- 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)."
1983
2125
  }
1984
2126
  },
1985
2127
  async (args, exec) => {
1986
2128
  guardEnabled();
1987
2129
  const sessionId = sessionIdOf(exec);
1988
2130
  const url = String(args.url ?? "").trim();
2131
+ const newTab = args.newTab === true;
1989
2132
  if (url === "") throw new Error("url is required");
1990
2133
  await ensureConnected(url);
1991
2134
  await ensureSessionTab(sessionId);
1992
- 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
+ );
1993
2141
  try {
1994
- const result = await runBridge(() => driverOf(options).navigate(url));
2142
+ const result = await runBridge(() => driverOf(options).navigate(url, { newTab }));
1995
2143
  await rememberTab(sessionId, result.tabId);
1996
2144
  options.sessions.rememberHttpUrl(sessionId, result.url);
1997
2145
  options.sessions.record({
1998
2146
  sessionId,
1999
2147
  tool: "browser_navigate",
2000
- summary: `Navigate to ${url}`,
2148
+ summary: `${newTab ? "Open new tab" : "Navigate"} to ${url}`,
2001
2149
  url: result.url,
2002
2150
  outcome: "ok"
2003
2151
  });
2004
2152
  options.onMutation?.({ sessionId, tool: "browser_navigate", url: result.url });
2005
- return `navigated
2006
- url: ${result.url}
2007
- title: ${result.title}
2008
- 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");
2009
2160
  } catch (error) {
2010
2161
  noteHuman(sessionId, {}, error);
2011
2162
  options.sessions.record({
2012
2163
  sessionId,
2013
2164
  tool: "browser_navigate",
2014
- summary: `Navigate to ${url}`,
2165
+ summary: `${newTab ? "Open new tab" : "Navigate"} to ${url}`,
2015
2166
  url,
2016
2167
  outcome: "error"
2017
2168
  });
@@ -2493,8 +2644,8 @@ function installBrowserAgent(ctx, options) {
2493
2644
  options.browserPreference()
2494
2645
  );
2495
2646
  const stopAllProfileSlots = () => {
2496
- for (const slot of ["auto", "chrome", "edge"]) {
2497
- stopAgentBrowserProcesses(browserAgentProfileDirFor(options.profileRoot, slot));
2647
+ for (const slot of BROWSER_AGENT_PROFILE_SLOTS) {
2648
+ stopAgentBrowserProcesses(browserAgentProfileSlotDir(options.profileRoot, slot));
2498
2649
  }
2499
2650
  };
2500
2651
  const enqueueSwitch = (work) => {
@@ -2504,7 +2655,12 @@ function installBrowserAgent(ctx, options) {
2504
2655
  const detail = error instanceof Error ? error.message : String(error);
2505
2656
  ctx.logger.warn(`agent-enhancer: browser driver remount failed: ${detail}`);
2506
2657
  }).finally(() => {
2507
- 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
+ }
2508
2664
  });
2509
2665
  };
2510
2666
  const tearDownDriverAsync = async () => {
@@ -2537,8 +2693,10 @@ function installBrowserAgent(ctx, options) {
2537
2693
  if (activeDriver === null || mountedPreference !== preference) return false;
2538
2694
  const status = activeDriver.status();
2539
2695
  if (!status.ready) return true;
2540
- const want = playwrightChannelOrder(preference, process.platform)[0];
2541
- return status.endpoint === `playwright:${want}`;
2696
+ const endpoint = status.endpoint ?? "";
2697
+ if (!endpoint.startsWith("playwright:")) return false;
2698
+ const channel = endpoint.slice("playwright:".length);
2699
+ return playwrightChannelSatisfiesPreference(channel, preference, process.platform);
2542
2700
  };
2543
2701
  const createDriver = (_preference) => {
2544
2702
  mountedPreference = options.browserPreference();
@@ -2566,7 +2724,9 @@ function installBrowserAgent(ctx, options) {
2566
2724
  approval,
2567
2725
  human,
2568
2726
  sessions,
2569
- 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(),
2570
2730
  onMutation: options.onBrowserMutation
2571
2731
  });
2572
2732
  }
@@ -2616,16 +2776,25 @@ function installBrowserAgent(ctx, options) {
2616
2776
  const refresh = () => {
2617
2777
  const want = options.enabled();
2618
2778
  if (!want) {
2619
- if (!active && playwrightDriver === null && !switchPending) return;
2779
+ if (!active && playwrightDriver === null && unregisterTools === null && !switchPending) {
2780
+ return;
2781
+ }
2620
2782
  active = false;
2621
2783
  approval.clearAll();
2622
2784
  human.clearAll();
2623
2785
  enqueueSwitch(() => tearDownActiveAsync());
2624
2786
  return;
2625
2787
  }
2626
- 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
+ }
2627
2797
  active = true;
2628
- mount();
2629
2798
  };
2630
2799
  refresh();
2631
2800
  return {
@@ -2648,6 +2817,57 @@ function installBrowserAgent(ctx, options) {
2648
2817
  return alignToPreference(startUrl);
2649
2818
  },
2650
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
+ },
2651
2871
  async resolveTabConflict(decision) {
2652
2872
  const conflict = sessions.currentConflict();
2653
2873
  if (conflict === null || activeDriver === null) return { ok: false };
@@ -2768,6 +2988,7 @@ function installBrowserAgent(ctx, options) {
2768
2988
  // src/errors.ts
2769
2989
  var MESSAGES = {
2770
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.",
2771
2992
  MODEL_FAILED: "Auxiliary model request failed",
2772
2993
  INVALID_OUTPUT: "Auxiliary model returned invalid output",
2773
2994
  SESSION_CHANGED: "The session changed during the auxiliary request",
@@ -2797,7 +3018,7 @@ var AuxiliaryError = class extends Error {
2797
3018
  // src/identity.ts
2798
3019
  var PACKAGE_NAME = "dsh-agent-enhancer";
2799
3020
  var PLUGIN_ID = "agent-enhancer";
2800
- var PACKAGE_VERSION = "0.3.10";
3021
+ var PACKAGE_VERSION = "0.3.12";
2801
3022
  var LEGACY_PACKAGE_NAME = "dsh-composer-enhancer";
2802
3023
  var ROLLBACK_PREFIX = `${PACKAGE_NAME}:rollback:`;
2803
3024
  var UNDO_PREFIX = `${PACKAGE_NAME}:undo:`;
@@ -5537,6 +5758,16 @@ function createClassifier(llm, route) {
5537
5758
  });
5538
5759
  }
5539
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
+
5540
5771
  // src/host/auto-route/session-resolved-route.ts
5541
5772
  var byAgent = /* @__PURE__ */ new WeakMap();
5542
5773
  var bySession = /* @__PURE__ */ new WeakMap();
@@ -5746,7 +5977,9 @@ function pickTierHeuristic(input) {
5746
5977
  var TIER_ORDER = ["pro", "thinking", "instant"];
5747
5978
  function tiersFrom(start) {
5748
5979
  const idx = TIER_ORDER.indexOf(start);
5749
- 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];
5750
5983
  }
5751
5984
  function routeForTier(map, tier, isAvailable) {
5752
5985
  const route = map[tier];
@@ -5778,8 +6011,11 @@ async function resolveAutoRoute(options) {
5778
6011
  return { ...route, tier: candidate };
5779
6012
  }
5780
6013
  }
5781
- const fallback = options.fallback ?? options.map.thinking;
5782
- 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();
5783
6019
  }
5784
6020
 
5785
6021
  // src/host/context-compact.ts
@@ -5941,7 +6177,7 @@ var SessionCleanupRegistry = class {
5941
6177
 
5942
6178
  // src/host/session-delete/plugin-purge.ts
5943
6179
  import { createHash as createHash4 } from "node:crypto";
5944
- import { existsSync as existsSync2 } from "node:fs";
6180
+ import { existsSync as existsSync3 } from "node:fs";
5945
6181
  import { readdir as readdir3, readFile as readFile4, rm, unlink as unlink4 } from "node:fs/promises";
5946
6182
  import { join as join7 } from "node:path";
5947
6183
  function digest4(value) {
@@ -5951,7 +6187,7 @@ function shortDigest(value, length = 16) {
5951
6187
  return digest4(value).slice(0, length);
5952
6188
  }
5953
6189
  async function removeIfPresent4(path) {
5954
- if (!existsSync2(path)) return false;
6190
+ if (!existsSync3(path)) return false;
5955
6191
  await rm(path, { recursive: true, force: true });
5956
6192
  return true;
5957
6193
  }
@@ -6016,7 +6252,7 @@ function createContextExcludeCleaner(pluginDataRoot) {
6016
6252
 
6017
6253
  // src/host/session-delete/delete.ts
6018
6254
  import { createHash as createHash5 } from "node:crypto";
6019
- import { existsSync as existsSync3 } from "node:fs";
6255
+ import { existsSync as existsSync4 } from "node:fs";
6020
6256
  import { appendFile, mkdir as mkdir4, readdir as readdir4, rm as rm2 } from "node:fs/promises";
6021
6257
  import { homedir as homedir2, tmpdir } from "node:os";
6022
6258
  import { join as join8 } from "node:path";
@@ -6241,7 +6477,7 @@ async function forgetInRegistry(ctx, sessionId, options) {
6241
6477
  return removed;
6242
6478
  }
6243
6479
  async function removePathBestEffort(path) {
6244
- if (!existsSync3(path)) return false;
6480
+ if (!existsSync4(path)) return false;
6245
6481
  for (let attempt = 0; attempt < 3; attempt += 1) {
6246
6482
  try {
6247
6483
  await rm2(path, { recursive: true, force: true });
@@ -6256,10 +6492,10 @@ async function removePathBestEffort(path) {
6256
6492
  async function eraseSessionLog(sessionId) {
6257
6493
  const removed = [];
6258
6494
  const root = sessionsRoot();
6259
- if (!existsSync3(root)) return removed;
6495
+ if (!existsSync4(root)) return removed;
6260
6496
  for (const workspaceDir of await readdir4(root)) {
6261
6497
  const target = join8(root, workspaceDir, sessionId);
6262
- if (!existsSync3(target)) continue;
6498
+ if (!existsSync4(target)) continue;
6263
6499
  const normalizedRoot = root.toLowerCase();
6264
6500
  if (!target.toLowerCase().startsWith(normalizedRoot)) continue;
6265
6501
  if (await removePathBestEffort(target)) removed.push(target);
@@ -6278,7 +6514,7 @@ async function eraseSpill(sessionId) {
6278
6514
  for (const entry of entries) {
6279
6515
  if (!SPILL_ROOT_RE.test(entry)) continue;
6280
6516
  const target = join8(spillBase(), entry, name2);
6281
- if (!existsSync3(target)) continue;
6517
+ if (!existsSync4(target)) continue;
6282
6518
  if (await removePathBestEffort(target)) removed.push(target);
6283
6519
  }
6284
6520
  return removed;
@@ -6306,7 +6542,7 @@ async function eraseProjcache(ctx, sessionId) {
6306
6542
  join8(projcacheSessionsDir(), `${sessionId}.json`),
6307
6543
  join8(projcacheSessionsDir(), `${uuid}.json`)
6308
6544
  ]) {
6309
- if (!existsSync3(cacheFile)) continue;
6545
+ if (!existsSync4(cacheFile)) continue;
6310
6546
  if (await removePathBestEffort(cacheFile)) removed.push(cacheFile);
6311
6547
  }
6312
6548
  return removed;
@@ -6378,7 +6614,7 @@ async function deleteSessionNow(options) {
6378
6614
 
6379
6615
  // src/host/web-chat-bridge/import-session.ts
6380
6616
  import { randomUUID as randomUUID6 } from "node:crypto";
6381
- import { existsSync as existsSync4, statSync } from "node:fs";
6617
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, statSync } from "node:fs";
6382
6618
  import { resolve as resolve2 } from "node:path";
6383
6619
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
6384
6620
  import {
@@ -6720,27 +6956,31 @@ function appendSessionTitle(session, title, firstUserMessageSeq) {
6720
6956
  });
6721
6957
  }
6722
6958
  function appendAssistantMessage(session, turn, step, text3) {
6723
- session.append("step/start", { turn, step });
6724
6959
  const message = createAssistantMessage({
6725
6960
  content: [{ type: "text", text: text3 }],
6726
6961
  source: { provider: "web-chat-bridge", model: "imported-history" }
6727
6962
  });
6728
- session.append("assistant/message", {
6729
- turn,
6730
- step,
6731
- message,
6732
- stream: []
6733
- }, { surfaceOp: "append" });
6734
- session.append("step/end", { turn, step });
6963
+ session.append([
6964
+ ["step/start", { turn, step }],
6965
+ ["assistant/message", {
6966
+ turn,
6967
+ step,
6968
+ message,
6969
+ stream: []
6970
+ }, { surfaceOp: "append" }],
6971
+ ["step/end", { turn, step }]
6972
+ ]);
6735
6973
  }
6736
6974
  function appendProtectedSystemHead(session, turn, step) {
6737
- session.append("step/start", { turn, step });
6738
- session.append("system/message", {
6739
- turn,
6740
- step,
6741
- message: createSystemMessage("")
6742
- }, { surfaceOp: "append" });
6743
- session.append("step/end", { turn, step });
6975
+ session.append([
6976
+ ["step/start", { turn, step }],
6977
+ ["system/message", {
6978
+ turn,
6979
+ step,
6980
+ message: createSystemMessage("")
6981
+ }, { surfaceOp: "append" }],
6982
+ ["step/end", { turn, step }]
6983
+ ]);
6744
6984
  }
6745
6985
  function appendTranscript(session, transcript) {
6746
6986
  const provenance = importProvenancePrefix(transcript);
@@ -6802,17 +7042,28 @@ function appendTranscript(session, transcript) {
6802
7042
  }
6803
7043
  function buildWebChatImportSeed(transcript) {
6804
7044
  const events = [];
7045
+ const recordOne = (type, data, intent) => {
7046
+ const event = {
7047
+ type,
7048
+ seq: SessionSeq2(events.length),
7049
+ time: Date.now(),
7050
+ data,
7051
+ ...intent?.surfaceOp === void 0 ? {} : { surfaceOp: intent.surfaceOp }
7052
+ };
7053
+ events.push(event);
7054
+ return event;
7055
+ };
6805
7056
  const recorder = {
6806
- append(type, data, intent) {
6807
- const event = {
6808
- type,
6809
- seq: SessionSeq2(events.length),
6810
- time: Date.now(),
6811
- data,
6812
- ...intent?.surfaceOp === void 0 ? {} : { surfaceOp: intent.surfaceOp }
6813
- };
6814
- events.push(event);
6815
- return event;
7057
+ append(typeOrInputs, data, intent) {
7058
+ if (typeof typeOrInputs !== "string") {
7059
+ return typeOrInputs.map((input) => {
7060
+ const type = input[0];
7061
+ const payload = input[1];
7062
+ const surface = input[2];
7063
+ return recordOne(type, payload, surface);
7064
+ });
7065
+ }
7066
+ return recordOne(typeOrInputs, data, intent);
6816
7067
  }
6817
7068
  };
6818
7069
  appendTranscript(recorder, transcript);
@@ -6886,9 +7137,30 @@ async function openAgentWorkSession(input, cwd) {
6886
7137
  }
6887
7138
  return { session, dispose: onceDispose(() => handle.dispose()) };
6888
7139
  }
7140
+ function ensureResolvableWorkspaceCwd(cwd) {
7141
+ const absolute = resolve2(cwd);
7142
+ try {
7143
+ if (!existsSync5(absolute)) {
7144
+ mkdirSync2(absolute, { recursive: true });
7145
+ }
7146
+ if (!statSync(absolute).isDirectory()) {
7147
+ throw new WebChatImportError(
7148
+ "missing-cwd",
7149
+ `Workspace path exists but is not a directory: ${absolute}`
7150
+ );
7151
+ }
7152
+ } catch (error) {
7153
+ if (error instanceof WebChatImportError) throw error;
7154
+ throw new WebChatImportError(
7155
+ "missing-cwd",
7156
+ `Workspace folder could not be created or read: ${absolute}`
7157
+ );
7158
+ }
7159
+ return absolute;
7160
+ }
6889
7161
  async function importWebChatHistoryNow(input) {
6890
7162
  assertTranscript(input.transcript);
6891
- const cwd = resolve2(input.cwd);
7163
+ const cwd = ensureResolvableWorkspaceCwd(input.cwd);
6892
7164
  const opened = await openAgentWorkSession(input, cwd);
6893
7165
  try {
6894
7166
  const flushed = await input.sessions.flush(opened.session);
@@ -6972,7 +7244,7 @@ async function createWebChatWorkspaceNow(ctx, signal) {
6972
7244
  signal.throwIfAborted();
6973
7245
  const absolute = resolve2(picked.path);
6974
7246
  try {
6975
- if (!existsSync4(absolute) || !statSync(absolute).isDirectory()) {
7247
+ if (!existsSync5(absolute) || !statSync(absolute).isDirectory()) {
6976
7248
  throw new WebChatImportError(
6977
7249
  "import-failed",
6978
7250
  `Selected folder does not exist: ${absolute}`
@@ -7571,7 +7843,7 @@ async function fetchWebChatShareContent(shareId, signal) {
7571
7843
  }
7572
7844
 
7573
7845
  // src/host/web-chat-bridge/login-snapshot.ts
7574
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7846
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7575
7847
  import { dirname, join as join9 } from "node:path";
7576
7848
 
7577
7849
  // src/host/web-chat-bridge/login-snapshot-types.ts
@@ -7638,7 +7910,7 @@ function parseSnapshot(raw) {
7638
7910
  }
7639
7911
  function loadWebChatLoginSnapshot(pluginDataPackageRoot) {
7640
7912
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7641
- if (!existsSync5(path)) return null;
7913
+ if (!existsSync6(path)) return null;
7642
7914
  try {
7643
7915
  return parseSnapshot(readFileSync(path, "utf8"));
7644
7916
  } catch {
@@ -7665,7 +7937,7 @@ function saveWebChatLoginSnapshot(pluginDataPackageRoot, input, options) {
7665
7937
  savedAt: typeof input.savedAt === "string" && input.savedAt.trim() !== "" ? input.savedAt : (/* @__PURE__ */ new Date()).toISOString()
7666
7938
  };
7667
7939
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7668
- mkdirSync2(dirname(path), { recursive: true });
7940
+ mkdirSync3(dirname(path), { recursive: true });
7669
7941
  const tmp = `${path}.${process.pid}.tmp`;
7670
7942
  writeFileSync(tmp, `${JSON.stringify(snapshot, null, 2)}
7671
7943
  `, "utf8");
@@ -7674,7 +7946,7 @@ function saveWebChatLoginSnapshot(pluginDataPackageRoot, input, options) {
7674
7946
  }
7675
7947
  function clearWebChatLoginSnapshot(pluginDataPackageRoot) {
7676
7948
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7677
- if (!existsSync5(path)) return false;
7949
+ if (!existsSync6(path)) return false;
7678
7950
  try {
7679
7951
  unlinkSync(path);
7680
7952
  return true;
@@ -7945,7 +8217,7 @@ function loadExtraRootPaths(store, primaryCwd) {
7945
8217
  }
7946
8218
 
7947
8219
  // src/host/extra-folders/store.ts
7948
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
8220
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
7949
8221
  import { dirname as dirname2, join as join11 } from "node:path";
7950
8222
  function emptyDoc(primaryCwd) {
7951
8223
  return {
@@ -7978,7 +8250,7 @@ function parseDoc(raw, primaryCwd) {
7978
8250
  }
7979
8251
  }
7980
8252
  function createExtraFoldersStore(rootDir) {
7981
- mkdirSync3(rootDir, { recursive: true });
8253
+ mkdirSync4(rootDir, { recursive: true });
7982
8254
  const fileOf = (primaryCwd) => join11(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
7983
8255
  return {
7984
8256
  rootDir,
@@ -7999,7 +8271,7 @@ function createExtraFoldersStore(rootDir) {
7999
8271
  roots: [...roots]
8000
8272
  };
8001
8273
  const file = fileOf(primaryCwd);
8002
- mkdirSync3(dirname2(file), { recursive: true });
8274
+ mkdirSync4(dirname2(file), { recursive: true });
8003
8275
  const tmp = `${file}.${process.pid}.tmp`;
8004
8276
  writeFileSync2(tmp, `${JSON.stringify(doc, null, 2)}
8005
8277
  `, "utf8");
@@ -8187,7 +8459,7 @@ async function writeWorkspaceFileNow(options) {
8187
8459
  }
8188
8460
 
8189
8461
  // src/host/file-edit/monaco.ts
8190
- import { existsSync as existsSync6 } from "node:fs";
8462
+ import { existsSync as existsSync7 } from "node:fs";
8191
8463
  import { promises as fsp2 } from "node:fs";
8192
8464
  import { dirname as dirname3, extname, join as join12, resolve as resolve6, sep as sep5 } from "node:path";
8193
8465
  import { fileURLToPath } from "node:url";
@@ -8207,7 +8479,7 @@ function packageRootCandidates() {
8207
8479
  }
8208
8480
  function resolveMonacoVsDir() {
8209
8481
  for (const candidate of packageRootCandidates()) {
8210
- if (existsSync6(join12(candidate, "loader.js"))) return candidate;
8482
+ if (existsSync7(join12(candidate, "loader.js"))) return candidate;
8211
8483
  }
8212
8484
  return packageRootCandidates()[0];
8213
8485
  }
@@ -8344,15 +8616,15 @@ function installMonacoRoute(ctx) {
8344
8616
  }
8345
8617
 
8346
8618
  // src/host/instructions-skills/io.ts
8347
- import { existsSync as existsSync16, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
8619
+ import { existsSync as existsSync17, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
8348
8620
  import { basename as basename13, join as join26, resolve as resolve16, sep as sep7 } from "node:path";
8349
8621
 
8350
8622
  // src/host/instructions-skills/create.ts
8351
- import { existsSync as existsSync8, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
8623
+ import { existsSync as existsSync9, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
8352
8624
  import { dirname as dirname5, join as join14, resolve as resolve8 } from "node:path";
8353
8625
 
8354
8626
  // src/host/instructions-skills/paths.ts
8355
- import { existsSync as existsSync7, statSync as statSync2 } from "node:fs";
8627
+ import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
8356
8628
  import { basename as basename5, dirname as dirname4, join as join13, resolve as resolve7, sep as sep6 } from "node:path";
8357
8629
  import { homedir as homedir3 } from "node:os";
8358
8630
  var INSTRUCTION_CANDIDATES = [
@@ -8376,7 +8648,7 @@ function findProjectRoot(cwd, markers = PROJECT_ROOT_MARKERS) {
8376
8648
  let current = resolve7(cwd);
8377
8649
  for (; ; ) {
8378
8650
  for (const marker of markers) {
8379
- if (existsSync7(join13(current, marker))) return current;
8651
+ if (existsSync8(join13(current, marker))) return current;
8380
8652
  }
8381
8653
  const parent = dirname4(current);
8382
8654
  if (parent === current) return resolve7(cwd);
@@ -8473,10 +8745,10 @@ Instructions for the agent go here.
8473
8745
  }
8474
8746
  function createWorkspaceAgentsFile(projectRoot) {
8475
8747
  const path = resolve8(projectRoot, "AGENTS.md");
8476
- if (existsSync8(path)) {
8748
+ if (existsSync9(path)) {
8477
8749
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
8478
8750
  }
8479
- mkdirSync4(dirname5(path), { recursive: true });
8751
+ mkdirSync5(dirname5(path), { recursive: true });
8480
8752
  writeFileSync3(path, AGENTS_STUB, "utf8");
8481
8753
  return { path, created: true };
8482
8754
  }
@@ -8487,16 +8759,16 @@ function createWorkspaceSkill(projectRoot, rawName) {
8487
8759
  }
8488
8760
  const dir = join14(resolve8(projectRoot), ".agents", "skills", name2);
8489
8761
  const path = join14(dir, "SKILL.md");
8490
- if (existsSync8(path) || existsSync8(dir)) {
8762
+ if (existsSync9(path) || existsSync9(dir)) {
8491
8763
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
8492
8764
  }
8493
- mkdirSync4(dir, { recursive: true });
8765
+ mkdirSync5(dir, { recursive: true });
8494
8766
  writeFileSync3(path, skillStubMarkdown(name2), "utf8");
8495
8767
  return { path, created: true, name: name2 };
8496
8768
  }
8497
8769
 
8498
8770
  // src/host/instructions-skills/discover.ts
8499
- import { existsSync as existsSync12, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
8771
+ import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
8500
8772
  import { basename as basename9, dirname as dirname8, join as join19, resolve as resolve12 } from "node:path";
8501
8773
 
8502
8774
  // src/host/instructions-skills/types.ts
@@ -8510,7 +8782,7 @@ function defaultSkillInstallMeta() {
8510
8782
  }
8511
8783
 
8512
8784
  // src/host/instructions-skills/transient-paths.ts
8513
- import { existsSync as existsSync9, lstatSync, readdirSync, renameSync as renameSync3, rmSync, unlinkSync as unlinkSync2 } from "node:fs";
8785
+ import { existsSync as existsSync10, lstatSync, readdirSync, renameSync as renameSync3, rmSync, unlinkSync as unlinkSync2 } from "node:fs";
8514
8786
  import { tmpdir as tmpdir2 } from "node:os";
8515
8787
  import { basename as basename6, join as join15, resolve as resolve9 } from "node:path";
8516
8788
  var TRANSIENT_MARK = /\.__ae_(?:removing|installing)_/;
@@ -8565,7 +8837,7 @@ function removeQuietly(path) {
8565
8837
  } catch {
8566
8838
  return;
8567
8839
  }
8568
- if (!existsSync9(path)) return;
8840
+ if (!existsSync10(path)) return;
8569
8841
  try {
8570
8842
  rmSync(path, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 });
8571
8843
  } catch {
@@ -8577,14 +8849,14 @@ import { lstatSync as lstatSync3 } from "node:fs";
8577
8849
  import { basename as basename8, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
8578
8850
 
8579
8851
  // src/host/instructions-skills/install-ledger.ts
8580
- import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
8852
+ import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
8581
8853
  import { dirname as dirname6, join as join16 } from "node:path";
8582
8854
  function ledgerPath(dataRoot) {
8583
8855
  return join16(dataRoot, "skills-install", "registry.json");
8584
8856
  }
8585
8857
  function writeLedger(dataRoot, ledger) {
8586
8858
  const path = ledgerPath(dataRoot);
8587
- mkdirSync5(dirname6(path), { recursive: true });
8859
+ mkdirSync6(dirname6(path), { recursive: true });
8588
8860
  const tmp = `${path}.${process.pid}.tmp`;
8589
8861
  writeFileSync4(tmp, `${JSON.stringify(ledger, null, 2)}
8590
8862
  `, "utf8");
@@ -8592,7 +8864,7 @@ function writeLedger(dataRoot, ledger) {
8592
8864
  }
8593
8865
  function readInstallLedger(dataRoot) {
8594
8866
  const path = ledgerPath(dataRoot);
8595
- if (!existsSync10(path)) return {};
8867
+ if (!existsSync11(path)) return {};
8596
8868
  try {
8597
8869
  const raw = readFileSync3(path, "utf8").trim();
8598
8870
  if (raw === "") return {};
@@ -8616,7 +8888,7 @@ function removeInstallRecord(dataRoot, name2) {
8616
8888
  import { execFileSync as execFileSync2 } from "node:child_process";
8617
8889
  import {
8618
8890
  chmodSync,
8619
- existsSync as existsSync11,
8891
+ existsSync as existsSync12,
8620
8892
  lstatSync as lstatSync2,
8621
8893
  readdirSync as readdirSync2,
8622
8894
  readlinkSync,
@@ -8698,12 +8970,12 @@ function isReparseOrSymlink(path) {
8698
8970
  }
8699
8971
  }
8700
8972
  function effectivelyGone(target) {
8701
- if (!pathPresent(target) && !existsSync11(target)) return true;
8973
+ if (!pathPresent(target) && !existsSync12(target)) return true;
8702
8974
  try {
8703
8975
  const stat = lstatSync2(target);
8704
8976
  if (stat.isSymbolicLink()) return false;
8705
8977
  if (!stat.isDirectory()) return false;
8706
- if (existsSync11(join17(target, "SKILL.md"))) return false;
8978
+ if (existsSync12(join17(target, "SKILL.md"))) return false;
8707
8979
  let names;
8708
8980
  try {
8709
8981
  names = readdirSync2(target);
@@ -8733,7 +9005,7 @@ function unlinkMountOnly(absolute) {
8733
9005
  return false;
8734
9006
  }
8735
9007
  }
8736
- return !pathPresent(absolute) && !existsSync11(absolute);
9008
+ return !pathPresent(absolute) && !existsSync12(absolute);
8737
9009
  }
8738
9010
  function tryUnlinkReparseOrFile(absolute) {
8739
9011
  let preferUnlink = false;
@@ -8753,7 +9025,7 @@ function removePathRobust(target) {
8753
9025
  if (isProtectedExternalSkillPath(absolute)) {
8754
9026
  return;
8755
9027
  }
8756
- if (!pathPresent(absolute) && !existsSync11(absolute)) return;
9028
+ if (!pathPresent(absolute) && !existsSync12(absolute)) return;
8757
9029
  if (isReparseOrSymlink(absolute)) {
8758
9030
  if (unlinkMountOnly(absolute)) return;
8759
9031
  if (effectivelyGone(absolute)) return;
@@ -8771,7 +9043,7 @@ function removePathRobust(target) {
8771
9043
  } catch (error) {
8772
9044
  if (!isWindowsPathBusyError(error) && effectivelyGone(absolute)) return;
8773
9045
  }
8774
- if (!pathPresent(absolute) && !existsSync11(absolute)) return;
9046
+ if (!pathPresent(absolute) && !existsSync12(absolute)) return;
8775
9047
  try {
8776
9048
  const aside = renameAsideToTemp(absolute, "removing");
8777
9049
  removeQuietly(aside);
@@ -8791,10 +9063,10 @@ function removePathRobust(target) {
8791
9063
  } catch {
8792
9064
  }
8793
9065
  }
8794
- if (!pathPresent(absolute) && !existsSync11(absolute)) return;
9066
+ if (!pathPresent(absolute) && !existsSync12(absolute)) return;
8795
9067
  if (effectivelyGone(absolute)) return;
8796
9068
  }
8797
- if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync11(absolute)) return;
9069
+ if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync12(absolute)) return;
8798
9070
  throw new AuxiliaryError("FILE_EDIT_FAILED", busyPathHint(basename7(absolute)));
8799
9071
  }
8800
9072
 
@@ -8920,7 +9192,7 @@ function discoverInstructionFiles(options) {
8920
9192
  scope: "global",
8921
9193
  name: "AGENTS.md",
8922
9194
  path: globalPath,
8923
- exists: existsSync12(globalPath),
9195
+ exists: existsSync13(globalPath),
8924
9196
  bytes: fileBytes(globalPath),
8925
9197
  createable: false
8926
9198
  });
@@ -8930,7 +9202,7 @@ function discoverInstructionFiles(options) {
8930
9202
  scope: "shared",
8931
9203
  name: "AGENTS.md",
8932
9204
  path: sharedPath,
8933
- exists: existsSync12(sharedPath),
9205
+ exists: existsSync13(sharedPath),
8934
9206
  bytes: fileBytes(sharedPath),
8935
9207
  createable: false
8936
9208
  });
@@ -8940,14 +9212,14 @@ function discoverInstructionFiles(options) {
8940
9212
  scope: "project",
8941
9213
  name: "AGENTS.md",
8942
9214
  path: rootAgents,
8943
- exists: existsSync12(rootAgents),
9215
+ exists: existsSync13(rootAgents),
8944
9216
  bytes: fileBytes(rootAgents),
8945
- createable: !existsSync12(rootAgents)
9217
+ createable: !existsSync13(rootAgents)
8946
9218
  });
8947
9219
  for (const dir of projectChainDirs(projectRoot, cwd)) {
8948
9220
  for (const name2 of INSTRUCTION_CANDIDATES) {
8949
9221
  const path = join19(dir, name2);
8950
- if (!existsSync12(path)) continue;
9222
+ if (!existsSync13(path)) continue;
8951
9223
  if (samePath2(path, rootAgents)) continue;
8952
9224
  pushUnique(instructions, seen, {
8953
9225
  id: entryId("project", path),
@@ -8992,7 +9264,7 @@ function discoverFilesystemSkills(options) {
8992
9264
  for (const name2 of names) {
8993
9265
  if (isTransientSkillEntryName(name2)) continue;
8994
9266
  const skillMd = join19(root, name2, "SKILL.md");
8995
- if (!existsSync12(skillMd)) continue;
9267
+ if (!existsSync13(skillMd)) continue;
8996
9268
  if (byName.has(name2)) continue;
8997
9269
  byName.set(name2, {
8998
9270
  id: `fs:${resolve12(skillMd).toLowerCase()}`,
@@ -9052,23 +9324,23 @@ function normalizeRegistrySkills(raw) {
9052
9324
  function coerceSkillDocumentPath(path, _name) {
9053
9325
  if (path === null || path.trim() === "") return null;
9054
9326
  const absolute = resolve12(path.trim());
9055
- if (existsSync12(absolute)) {
9327
+ if (existsSync13(absolute)) {
9056
9328
  try {
9057
9329
  if (statSync3(absolute).isFile()) return absolute;
9058
9330
  } catch {
9059
9331
  }
9060
9332
  const asFile = join19(absolute, "SKILL.md");
9061
- if (existsSync12(asFile)) return asFile;
9333
+ if (existsSync13(asFile)) return asFile;
9062
9334
  }
9063
9335
  const lower = absolute.toLowerCase();
9064
9336
  if (lower.endsWith("skill.md") || lower.endsWith(".md")) return absolute;
9065
9337
  const nested = join19(absolute, "SKILL.md");
9066
- return existsSync12(nested) ? nested : absolute;
9338
+ return existsSync13(nested) ? nested : absolute;
9067
9339
  }
9068
9340
  function resolveSkillPathFromRoots(name2, cwd, projectRoot, env) {
9069
9341
  for (const root of previewSkillSearchRoots(cwd, projectRoot, env)) {
9070
9342
  const skillMd = join19(root, name2, "SKILL.md");
9071
- if (existsSync12(skillMd)) return resolve12(skillMd);
9343
+ if (existsSync13(skillMd)) return resolve12(skillMd);
9072
9344
  }
9073
9345
  return null;
9074
9346
  }
@@ -9229,7 +9501,7 @@ function parseGitSkillSource(raw) {
9229
9501
 
9230
9502
  // src/host/instructions-skills/install.ts
9231
9503
  import { execFile as execFile3, spawn } from "node:child_process";
9232
- import { existsSync as existsSync14, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
9504
+ import { existsSync as existsSync15, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
9233
9505
  import { tmpdir as tmpdir3 } from "node:os";
9234
9506
  import { basename as basename11, dirname as dirname10, join as join23, resolve as resolve14 } from "node:path";
9235
9507
  import { promisify as promisify3 } from "node:util";
@@ -9238,7 +9510,7 @@ import { promisify as promisify3 } from "node:util";
9238
9510
  import { execFile as execFile2 } from "node:child_process";
9239
9511
  import {
9240
9512
  createWriteStream,
9241
- mkdirSync as mkdirSync6,
9513
+ mkdirSync as mkdirSync7,
9242
9514
  readdirSync as readdirSync4,
9243
9515
  renameSync as renameSync5,
9244
9516
  rmSync as rmSync3,
@@ -9289,7 +9561,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
9289
9561
  }
9290
9562
  async function extractZip(zipPath, destDir, signal) {
9291
9563
  signal.throwIfAborted();
9292
- mkdirSync6(destDir, { recursive: true });
9564
+ mkdirSync7(destDir, { recursive: true });
9293
9565
  try {
9294
9566
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
9295
9567
  windowsHide: true,
@@ -9347,10 +9619,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
9347
9619
  }
9348
9620
  async function fetchGithubRepoArchive(options) {
9349
9621
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
9350
- mkdirSync6(workDir, { recursive: true });
9622
+ mkdirSync7(workDir, { recursive: true });
9351
9623
  const zipPath = join20(workDir, "repo.zip");
9352
9624
  const extractDir = join20(workDir, "extract");
9353
- mkdirSync6(extractDir, { recursive: true });
9625
+ mkdirSync7(extractDir, { recursive: true });
9354
9626
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
9355
9627
  const candidates = archiveCandidates(owner, repo, defaultBranch);
9356
9628
  const errors = [];
@@ -9361,7 +9633,7 @@ async function fetchGithubRepoArchive(options) {
9361
9633
  try {
9362
9634
  rmSync3(zipPath, { force: true });
9363
9635
  rmSync3(extractDir, { recursive: true, force: true });
9364
- mkdirSync6(extractDir, { recursive: true });
9636
+ mkdirSync7(extractDir, { recursive: true });
9365
9637
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
9366
9638
  if (!downloadStarted) {
9367
9639
  onStage?.("downloading", detail);
@@ -9403,9 +9675,9 @@ async function fetchGithubRepoArchive(options) {
9403
9675
  // src/host/instructions-skills/install-fs.ts
9404
9676
  import {
9405
9677
  cpSync,
9406
- existsSync as existsSync13,
9678
+ existsSync as existsSync14,
9407
9679
  lstatSync as lstatSync4,
9408
- mkdirSync as mkdirSync7,
9680
+ mkdirSync as mkdirSync8,
9409
9681
  readdirSync as readdirSync5,
9410
9682
  readFileSync as readFileSync5,
9411
9683
  renameSync as renameSync6,
@@ -9435,9 +9707,9 @@ function directoryBundleName(dir, folderName) {
9435
9707
  }
9436
9708
  function findSkillBundles(root) {
9437
9709
  const absolute = resolve13(root);
9438
- if (!existsSync13(absolute)) return [];
9710
+ if (!existsSync14(absolute)) return [];
9439
9711
  const rootSkill = join21(absolute, "SKILL.md");
9440
- if (existsSync13(rootSkill)) {
9712
+ if (existsSync14(rootSkill)) {
9441
9713
  const folderName = basename10(absolute);
9442
9714
  const name2 = directoryBundleName(absolute, folderName);
9443
9715
  if (isKebabCaseName(name2)) {
@@ -9454,7 +9726,7 @@ function findSkillBundles(root) {
9454
9726
  for (const entry of entries) {
9455
9727
  if (isTransientSkillEntryName(entry)) continue;
9456
9728
  const full = join21(absolute, entry);
9457
- if (existsSync13(join21(full, "SKILL.md"))) {
9729
+ if (existsSync14(join21(full, "SKILL.md"))) {
9458
9730
  const name2 = directoryBundleName(full, entry);
9459
9731
  if (!isKebabCaseName(name2)) continue;
9460
9732
  out.push({ name: name2, sourcePath: full, kind: "directory" });
@@ -9476,10 +9748,10 @@ function findSkillBundles(root) {
9476
9748
  }
9477
9749
  function resolveBundlesFromClone(cloneRoot, subpath) {
9478
9750
  const base = subpath === null || subpath === "" ? resolve13(cloneRoot) : resolve13(cloneRoot, subpath);
9479
- if (!existsSync13(base)) {
9751
+ if (!existsSync14(base)) {
9480
9752
  throw new AuxiliaryError("FILE_NOT_FOUND", `Path not found in repository: ${subpath ?? "."}`);
9481
9753
  }
9482
- if (base.toLowerCase().endsWith("skill.md") && existsSync13(base)) {
9754
+ if (base.toLowerCase().endsWith("skill.md") && existsSync14(base)) {
9483
9755
  const dir = dirname9(base);
9484
9756
  const name2 = directoryBundleName(dir, basename10(dir));
9485
9757
  if (!isKebabCaseName(name2)) {
@@ -9531,13 +9803,13 @@ function isStaleSkillDestination(dest, kind) {
9531
9803
  if (kind === "file") {
9532
9804
  try {
9533
9805
  const stat = lstatSync4(dest);
9534
- if (stat.isSymbolicLink()) return !existsSync13(dest);
9806
+ if (stat.isSymbolicLink()) return !existsSync14(dest);
9535
9807
  return !stat.isFile();
9536
9808
  } catch {
9537
9809
  return true;
9538
9810
  }
9539
9811
  }
9540
- return !existsSync13(join21(dest, "SKILL.md"));
9812
+ return !existsSync14(join21(dest, "SKILL.md"));
9541
9813
  }
9542
9814
  function copySkillTree(source, dest) {
9543
9815
  try {
@@ -9554,7 +9826,7 @@ function copySkillTree(source, dest) {
9554
9826
  }
9555
9827
  }
9556
9828
  function copySkillTreeAtomic(source, dest, kind) {
9557
- mkdirSync7(dirname9(dest), { recursive: true });
9829
+ mkdirSync8(dirname9(dest), { recursive: true });
9558
9830
  if (kind === "file") {
9559
9831
  if (destinationPresent(dest)) removeDestination(dest);
9560
9832
  copySkillTree(source, dest);
@@ -9582,7 +9854,7 @@ function copySkillTreeAtomic(source, dest, kind) {
9582
9854
  }
9583
9855
  }
9584
9856
  function linkOrCopy(source, dest, mode, kind) {
9585
- mkdirSync7(dirname9(dest), { recursive: true });
9857
+ mkdirSync8(dirname9(dest), { recursive: true });
9586
9858
  if (mode === "copy") {
9587
9859
  copySkillTreeAtomic(source, dest, kind);
9588
9860
  return "copy";
@@ -9590,7 +9862,7 @@ function linkOrCopy(source, dest, mode, kind) {
9590
9862
  try {
9591
9863
  if (process.platform === "win32") {
9592
9864
  const stat = lstatSync4(source);
9593
- if (stat.isDirectory() || stat.isSymbolicLink() && existsSync13(join21(source, "SKILL.md"))) {
9865
+ if (stat.isDirectory() || stat.isSymbolicLink() && existsSync14(join21(source, "SKILL.md"))) {
9594
9866
  symlinkSync(source, dest, "junction");
9595
9867
  return "link";
9596
9868
  }
@@ -10057,7 +10329,7 @@ async function checkGithubSkillUpdate(record2, options) {
10057
10329
 
10058
10330
  // src/host/instructions-skills/zip-install.ts
10059
10331
  import { execFile as execFile4 } from "node:child_process";
10060
- import { existsSync as existsSync15, mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
10332
+ import { existsSync as existsSync16, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
10061
10333
  import { tmpdir as tmpdir5 } from "node:os";
10062
10334
  import { basename as basename12, join as join25, resolve as resolve15 } from "node:path";
10063
10335
  import { promisify as promisify4 } from "node:util";
@@ -10072,7 +10344,7 @@ function tempWorkDir3(prefix) {
10072
10344
  }
10073
10345
  async function extractZipArchive(zipPath, destDir, signal) {
10074
10346
  signal.throwIfAborted();
10075
- mkdirSync8(destDir, { recursive: true });
10347
+ mkdirSync9(destDir, { recursive: true });
10076
10348
  try {
10077
10349
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
10078
10350
  windowsHide: true,
@@ -10086,7 +10358,7 @@ async function extractZipArchive(zipPath, destDir, signal) {
10086
10358
  }
10087
10359
  async function installSkillsFromZipFile(options) {
10088
10360
  const zipPath = resolve15(options.zipPath);
10089
- if (!existsSync15(zipPath)) {
10361
+ if (!existsSync16(zipPath)) {
10090
10362
  throw new AuxiliaryError("FILE_NOT_FOUND", `Zip not found: ${zipPath}`);
10091
10363
  }
10092
10364
  if (!zipPath.toLowerCase().endsWith(".zip")) {
@@ -10261,7 +10533,7 @@ function inferSkillInstallTarget(name2, cwd, projectRoot, env = process.env) {
10261
10533
  const userAgents = join26(agentsHomeOf(env), "skills");
10262
10534
  const userDsh = join26(dshHomeOf(env), "skills");
10263
10535
  for (const root of roots) {
10264
- const present = existsSync16(join26(root, name2, "SKILL.md")) || existsSync16(join26(root, `${name2}.md`));
10536
+ const present = existsSync17(join26(root, name2, "SKILL.md")) || existsSync17(join26(root, `${name2}.md`));
10265
10537
  if (!present) continue;
10266
10538
  if (samePath2(root, projectAgents)) return "project";
10267
10539
  if (samePath2(root, projectDsh)) return "project-dsh";
@@ -10499,7 +10771,7 @@ async function readSkillDocumentNow(options) {
10499
10771
  throw new AuxiliaryError("FILE_DENIED", "Only SKILL.md may be previewed");
10500
10772
  }
10501
10773
  options.signal.throwIfAborted();
10502
- if (!existsSync16(absolutePath2)) {
10774
+ if (!existsSync17(absolutePath2)) {
10503
10775
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
10504
10776
  }
10505
10777
  try {
@@ -10534,7 +10806,7 @@ async function readSkillDocumentNow(options) {
10534
10806
  }
10535
10807
 
10536
10808
  // src/host/mcp-connectors/io.ts
10537
- import { existsSync as existsSync18 } from "node:fs";
10809
+ import { existsSync as existsSync19 } from "node:fs";
10538
10810
 
10539
10811
  // src/host/mcp-connectors/validate.ts
10540
10812
  var MCP_SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
@@ -10656,7 +10928,7 @@ function parseMcpJsonText(jsonText) {
10656
10928
  }
10657
10929
 
10658
10930
  // src/host/mcp-connectors/install-git.ts
10659
- import { existsSync as existsSync17, mkdirSync as mkdirSync9, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
10931
+ import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
10660
10932
  import { join as join28 } from "node:path";
10661
10933
 
10662
10934
  // src/host/mcp-connectors/paths.ts
@@ -10689,7 +10961,7 @@ function inferStdioFromPackageJson(installDir, override) {
10689
10961
  };
10690
10962
  }
10691
10963
  const pkgPath = join28(installDir, "package.json");
10692
- if (!existsSync17(pkgPath)) {
10964
+ if (!existsSync18(pkgPath)) {
10693
10965
  return {
10694
10966
  transport: "stdio",
10695
10967
  command: "npx",
@@ -10748,17 +11020,17 @@ function inferStdioFromPackageJson(installDir, override) {
10748
11020
  async function installMcpServerFromGit(options) {
10749
11021
  const parsed = parseGitSkillSource(options.source);
10750
11022
  const installDir = mcpServerInstallDir(options.rootDir, options.id);
10751
- if (existsSync17(installDir)) {
11023
+ if (existsSync18(installDir)) {
10752
11024
  if (!options.force) {
10753
11025
  throw new AuxiliaryError("FILE_EDIT_FAILED", `MCP install dir already exists: ${installDir}`);
10754
11026
  }
10755
11027
  removePathRobust(installDir);
10756
11028
  }
10757
- mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
11029
+ mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
10758
11030
  const staging = `${installDir}.staging.${process.pid}`;
10759
11031
  try {
10760
- if (existsSync17(staging)) removePathRobust(staging);
10761
- mkdirSync9(staging, { recursive: true });
11032
+ if (existsSync18(staging)) removePathRobust(staging);
11033
+ mkdirSync10(staging, { recursive: true });
10762
11034
  if (parsed.github === null) {
10763
11035
  throw new AuxiliaryError(
10764
11036
  "FILE_EDIT_FAILED",
@@ -10775,12 +11047,12 @@ async function installMcpServerFromGit(options) {
10775
11047
  let contentRoot = repoDir;
10776
11048
  if (parsed.subpath !== null) {
10777
11049
  const nested = join28(repoDir, parsed.subpath);
10778
- if (!existsSync17(nested)) {
11050
+ if (!existsSync18(nested)) {
10779
11051
  throw new AuxiliaryError("FILE_EDIT_FAILED", `Subpath not found in repo: ${parsed.subpath}`);
10780
11052
  }
10781
11053
  contentRoot = nested;
10782
11054
  }
10783
- mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
11055
+ mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
10784
11056
  if (contentRoot !== repoDir) {
10785
11057
  const nestedStaging = `${installDir}.nested.${process.pid}`;
10786
11058
  renameSync7(contentRoot, nestedStaging);
@@ -10795,11 +11067,11 @@ async function installMcpServerFromGit(options) {
10795
11067
  }
10796
11068
  } catch (error) {
10797
11069
  try {
10798
- if (existsSync17(staging)) rmSync7(staging, { recursive: true, force: true });
11070
+ if (existsSync18(staging)) rmSync7(staging, { recursive: true, force: true });
10799
11071
  } catch {
10800
11072
  }
10801
11073
  try {
10802
- if (existsSync17(installDir)) removePathRobust(installDir);
11074
+ if (existsSync18(installDir)) removePathRobust(installDir);
10803
11075
  } catch {
10804
11076
  }
10805
11077
  if (error instanceof AuxiliaryError) throw error;
@@ -10817,6 +11089,7 @@ async function installMcpServerFromGit(options) {
10817
11089
  function snapshotOf2(host) {
10818
11090
  return {
10819
11091
  connectors: host.store.load().connectors,
11092
+ statuses: host.runtime.statusRows(),
10820
11093
  bridgeAvailable: host.runtime.bridgeAvailable,
10821
11094
  bridgeError: host.runtime.lastBridgeError
10822
11095
  };
@@ -10897,7 +11170,7 @@ async function uninstallMcpConnectorNow(host, request) {
10897
11170
  }
10898
11171
  const next = doc.connectors.filter((entry) => entry.id !== request.id);
10899
11172
  const installDir = mcpServerInstallDir(host.store.rootDir, request.id);
10900
- if (existsSync18(installDir)) {
11173
+ if (existsSync19(installDir)) {
10901
11174
  try {
10902
11175
  removePathRobust(installDir);
10903
11176
  } catch (error) {
@@ -11027,9 +11300,25 @@ function listMcpConnectorToolsNow(host, request) {
11027
11300
  }));
11028
11301
  return { serverName, tools };
11029
11302
  }
11303
+ async function restartMcpConnectorNow(host, request) {
11304
+ const restarted = await host.runtime.restart(request.id);
11305
+ return {
11306
+ id: request.id,
11307
+ ok: restarted.ok,
11308
+ error: restarted.error,
11309
+ snapshot: snapshotOf2(host)
11310
+ };
11311
+ }
11312
+ async function probeMcpConnectorNow(host, request, signal) {
11313
+ const probed = await host.runtime.probe(request.id, signal);
11314
+ return {
11315
+ ...probed,
11316
+ snapshot: snapshotOf2(host)
11317
+ };
11318
+ }
11030
11319
 
11031
11320
  // src/host/mcp-connectors/store.ts
11032
- import { mkdirSync as mkdirSync10, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
11321
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
11033
11322
  import { dirname as dirname11 } from "node:path";
11034
11323
 
11035
11324
  // src/host/mcp-connectors/types.ts
@@ -11112,7 +11401,7 @@ function parseDoc2(raw) {
11112
11401
  }
11113
11402
  }
11114
11403
  function createMcpConnectorsStore(rootDir) {
11115
- mkdirSync10(rootDir, { recursive: true });
11404
+ mkdirSync11(rootDir, { recursive: true });
11116
11405
  const file = mcpConnectorsLedgerPath(rootDir);
11117
11406
  return {
11118
11407
  rootDir,
@@ -11131,7 +11420,7 @@ function createMcpConnectorsStore(rootDir) {
11131
11420
  version: MCP_CONNECTORS_VERSION,
11132
11421
  connectors: [...connectors]
11133
11422
  };
11134
- mkdirSync10(dirname11(file), { recursive: true });
11423
+ mkdirSync11(dirname11(file), { recursive: true });
11135
11424
  const tmp = `${file}.${process.pid}.tmp`;
11136
11425
  writeFileSync5(tmp, `${JSON.stringify(doc, null, 2)}
11137
11426
  `, "utf8");
@@ -11141,6 +11430,80 @@ function createMcpConnectorsStore(rootDir) {
11141
11430
  };
11142
11431
  }
11143
11432
 
11433
+ // src/host/mcp-connectors/probe-message.ts
11434
+ function classifyMcpProbeFailure(message) {
11435
+ const lower = message.toLowerCase();
11436
+ if (lower.includes("url is expired") || lower.includes("url expired") || lower.includes('"url is expired"')) {
11437
+ return "url-expired";
11438
+ }
11439
+ return "generic";
11440
+ }
11441
+ function rewriteMcpProbeFailure(message) {
11442
+ const code = classifyMcpProbeFailure(message);
11443
+ switch (code) {
11444
+ case "url-expired":
11445
+ return "url-expired";
11446
+ case "generic":
11447
+ return message;
11448
+ default: {
11449
+ const _exhaustive = code;
11450
+ return _exhaustive;
11451
+ }
11452
+ }
11453
+ }
11454
+
11455
+ // src/host/mcp-connectors/status.ts
11456
+ function summarizeMcpConnectionStatus(status) {
11457
+ if (status === null || status === void 0) {
11458
+ return { state: "unmounted", detail: null, toolCount: null };
11459
+ }
11460
+ switch (status.state) {
11461
+ case "connected":
11462
+ return {
11463
+ state: "connected",
11464
+ detail: null,
11465
+ toolCount: status.toolCount
11466
+ };
11467
+ case "connecting":
11468
+ return {
11469
+ state: "connecting",
11470
+ detail: status.attempt > 0 ? `attempt ${status.attempt + 1}` : null,
11471
+ toolCount: null
11472
+ };
11473
+ case "reconnecting":
11474
+ return {
11475
+ state: "reconnecting",
11476
+ detail: status.lastError.trim() !== "" ? status.lastError : `attempt ${status.attempt}/${status.maxAttempts}`,
11477
+ toolCount: null
11478
+ };
11479
+ case "waiting-credentials":
11480
+ return {
11481
+ state: "waiting-credentials",
11482
+ detail: status.lastError.trim() !== "" ? status.lastError : null,
11483
+ toolCount: null
11484
+ };
11485
+ case "failed":
11486
+ return {
11487
+ state: "failed",
11488
+ detail: status.lastError?.trim() ? `${status.reason}: ${status.lastError}` : status.reason,
11489
+ toolCount: null
11490
+ };
11491
+ case "closed":
11492
+ return {
11493
+ state: "closed",
11494
+ detail: status.result?.cleanupError ?? null,
11495
+ toolCount: null
11496
+ };
11497
+ default: {
11498
+ const _exhaustive = status;
11499
+ return _exhaustive;
11500
+ }
11501
+ }
11502
+ }
11503
+ function disabledMcpStatus() {
11504
+ return { state: "disabled", detail: null, toolCount: null };
11505
+ }
11506
+
11144
11507
  // src/host/mcp-connectors/runtime.ts
11145
11508
  function toPluginConfig(entry) {
11146
11509
  const base = {
@@ -11177,6 +11540,7 @@ var McpConnectorRuntime = class {
11177
11540
  store;
11178
11541
  mounts = /* @__PURE__ */ new Map();
11179
11542
  module = null;
11543
+ clientApi = null;
11180
11544
  bridgeError = null;
11181
11545
  featureEnabled = true;
11182
11546
  get bridgeAvailable() {
@@ -11195,23 +11559,155 @@ var McpConnectorRuntime = class {
11195
11559
  if (typeof loaded.apply !== "function") {
11196
11560
  this.bridgeError = "@deepseek-ai/dsh-mcp-client apply() missing";
11197
11561
  this.module = null;
11562
+ this.clientApi = null;
11198
11563
  return false;
11199
11564
  }
11200
11565
  this.module = loaded;
11566
+ this.clientApi = loaded;
11201
11567
  this.bridgeError = null;
11202
11568
  return true;
11203
11569
  } catch (error) {
11204
11570
  const detail = error instanceof Error ? error.message : String(error);
11205
11571
  this.bridgeError = detail;
11206
11572
  this.module = null;
11573
+ this.clientApi = null;
11207
11574
  this.ctx.logger.warn(`agent-enhancer: dsh-mcp-client unavailable: ${detail}`);
11208
11575
  return false;
11209
11576
  }
11210
11577
  }
11578
+ statusOf(id, entry) {
11579
+ const connector = entry ?? this.store.load().connectors.find((row) => row.id === id);
11580
+ if (connector === void 0) {
11581
+ return summarizeMcpConnectionStatus(void 0);
11582
+ }
11583
+ if (!connector.enabled || !this.featureEnabled) {
11584
+ return disabledMcpStatus();
11585
+ }
11586
+ const mount = this.mounts.get(id);
11587
+ if (mount === void 0) {
11588
+ return summarizeMcpConnectionStatus(void 0);
11589
+ }
11590
+ try {
11591
+ const handle = this.clientApi?.connectionStatusOf?.(mount.fiber);
11592
+ return summarizeMcpConnectionStatus(handle?.current());
11593
+ } catch {
11594
+ return summarizeMcpConnectionStatus(void 0);
11595
+ }
11596
+ }
11597
+ statusRows() {
11598
+ return this.store.load().connectors.map((entry) => ({
11599
+ id: entry.id,
11600
+ status: this.statusOf(entry.id, entry)
11601
+ }));
11602
+ }
11603
+ async restart(id) {
11604
+ const entry = this.store.load().connectors.find((row) => row.id === id);
11605
+ if (entry === void 0) {
11606
+ return { ok: false, error: `MCP connector not found: ${id}` };
11607
+ }
11608
+ if (!entry.enabled) {
11609
+ return { ok: false, error: "Connector is disabled" };
11610
+ }
11611
+ if (!this.featureEnabled) {
11612
+ return { ok: false, error: "MCP connectors feature is disabled" };
11613
+ }
11614
+ const ok = await this.ensureBridge();
11615
+ if (!ok) {
11616
+ return { ok: false, error: this.bridgeError ?? "mcp-client bridge unavailable" };
11617
+ }
11618
+ await this.disposeOne(id);
11619
+ await this.mountOne(entry);
11620
+ if (!this.mounts.has(id)) {
11621
+ return { ok: false, error: "Restart failed to remount connector" };
11622
+ }
11623
+ return { ok: true, error: null };
11624
+ }
11625
+ async probe(id, signal) {
11626
+ const entry = this.store.load().connectors.find((row) => row.id === id);
11627
+ if (entry === void 0) {
11628
+ return {
11629
+ id,
11630
+ ok: false,
11631
+ message: `MCP connector not found: ${id}`,
11632
+ toolNames: [],
11633
+ truncated: false,
11634
+ durationMs: 0
11635
+ };
11636
+ }
11637
+ const live = this.statusOf(id, entry);
11638
+ if (live.state === "connected") {
11639
+ const toolNames = this.liveToolNames(entry.serverName);
11640
+ const count = live.toolCount ?? toolNames.length;
11641
+ return {
11642
+ id,
11643
+ ok: true,
11644
+ message: `live \xB7 ${count} tools`,
11645
+ toolNames,
11646
+ truncated: false,
11647
+ durationMs: 0
11648
+ };
11649
+ }
11650
+ const ok = await this.ensureBridge();
11651
+ if (!ok || this.clientApi?.probeServer === void 0) {
11652
+ return {
11653
+ id,
11654
+ ok: false,
11655
+ message: this.bridgeError ?? "mcp-client probeServer unavailable",
11656
+ toolNames: [],
11657
+ truncated: false,
11658
+ durationMs: 0
11659
+ };
11660
+ }
11661
+ try {
11662
+ const result = await this.clientApi.probeServer(this.ctx, toPluginConfig(entry), {
11663
+ timeoutMs: 15e3,
11664
+ ...signal === void 0 ? {} : { signal }
11665
+ });
11666
+ if (result.ok) {
11667
+ const toolNames = result.toolNames ?? [];
11668
+ return {
11669
+ id,
11670
+ ok: true,
11671
+ message: result.serverInfo === void 0 ? `ok \xB7 ${toolNames.length} tools` : `ok \xB7 ${result.serverInfo.name}@${result.serverInfo.version} \xB7 ${toolNames.length} tools`,
11672
+ toolNames,
11673
+ truncated: result.truncated === true,
11674
+ durationMs: result.durationMs ?? 0
11675
+ };
11676
+ }
11677
+ const raw = `${result.stage ?? "probe"}: ${result.message ?? "failed"}`;
11678
+ return {
11679
+ id,
11680
+ ok: false,
11681
+ message: rewriteMcpProbeFailure(raw),
11682
+ toolNames: [],
11683
+ truncated: false,
11684
+ durationMs: result.durationMs ?? 0
11685
+ };
11686
+ } catch (error) {
11687
+ const detail = error instanceof Error ? error.message : String(error);
11688
+ return {
11689
+ id,
11690
+ ok: false,
11691
+ message: rewriteMcpProbeFailure(detail),
11692
+ toolNames: [],
11693
+ truncated: false,
11694
+ durationMs: 0
11695
+ };
11696
+ }
11697
+ }
11698
+ liveToolNames(serverName) {
11699
+ const prefix = `mcp__${serverName}__`;
11700
+ try {
11701
+ const definitions = this.ctx.tools.definitions();
11702
+ return definitions.filter((def) => def.name.startsWith(prefix)).map((def) => def.name.slice(prefix.length)).filter((name2) => name2.length > 0);
11703
+ } catch {
11704
+ return [];
11705
+ }
11706
+ }
11211
11707
  async disposeAll() {
11212
11708
  const ids = [...this.mounts.keys()];
11213
- for (const id of ids) {
11214
- await this.disposeOne(id);
11709
+ for (const nextId of ids) {
11710
+ await this.disposeOne(nextId);
11215
11711
  }
11216
11712
  }
11217
11713
  async disposeOne(id) {
@@ -11567,7 +12063,7 @@ var AutoCatalogAdapter = class extends LlmAdapter {
11567
12063
  stream(_options) {
11568
12064
  throw new LlmError(
11569
12065
  "Auto is a routing sentinel and is not sent to a provider",
11570
- "AUTO_SENTINEL"
12066
+ "UNSUPPORTED_OPTION"
11571
12067
  );
11572
12068
  }
11573
12069
  };
@@ -11725,17 +12221,28 @@ function installAutoSessionRoute(ctx, options) {
11725
12221
  const map = autoRouteMapOf(settings);
11726
12222
  const note = (agent === void 0 ? void 0 : notes.get(agent)) ?? loggedTurn(asAgent(agent));
11727
12223
  const classify = settings.autoClassifierEnabled ? createClassifier({ prepareCall: innerPrepare }, map.classifier) : void 0;
11728
- const mapped = await resolveAutoRoute({
11729
- text: note?.text ?? "",
11730
- feature,
11731
- toolHeavy: note?.toolHeavy ?? false,
11732
- map,
11733
- classifierEnabled: settings.autoClassifierEnabled,
11734
- classify,
11735
- isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
11736
- signal,
11737
- fallback: fallbackRoute(ctx, asAgent(agent))
11738
- });
12224
+ let mapped;
12225
+ try {
12226
+ mapped = await resolveAutoRoute({
12227
+ text: note?.text ?? "",
12228
+ feature,
12229
+ toolHeavy: note?.toolHeavy ?? false,
12230
+ map,
12231
+ classifierEnabled: settings.autoClassifierEnabled,
12232
+ classify,
12233
+ isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
12234
+ signal,
12235
+ fallback: fallbackRoute(ctx, asAgent(agent))
12236
+ });
12237
+ } catch (error) {
12238
+ if (error instanceof AutoRouteUnconfiguredError) {
12239
+ throw new LlmError(AUTO_ROUTE_UNCONFIGURED_LLM_MESSAGE, "INVALID_CONFIG");
12240
+ }
12241
+ throw error;
12242
+ }
12243
+ if (mapped.provider === "" || mapped.model === "" || isAutoModel({ provider: mapped.provider, model: mapped.model })) {
12244
+ throw new LlmError(AUTO_ROUTE_UNCONFIGURED_LLM_MESSAGE, "INVALID_CONFIG");
12245
+ }
11739
12246
  if (agent !== void 0 && feature === "session") setSessionResolvedRoute(agent, mapped);
11740
12247
  return mapped;
11741
12248
  };
@@ -12115,16 +12622,27 @@ var AuxiliaryModels = class {
12115
12622
  const settings = this.enhancerSettings();
12116
12623
  const map = autoRouteMapOf(settings);
12117
12624
  const classify = settings.autoClassifierEnabled ? createClassifier(this.ctx.llm, map.classifier) : void 0;
12118
- const mapped = await resolveAutoRoute({
12119
- text: text3,
12120
- feature,
12121
- toolHeavy,
12122
- map,
12123
- classifierEnabled: settings.autoClassifierEnabled,
12124
- classify,
12125
- isAvailable: (provider, model) => this.modelExists(provider, model),
12126
- fallback: this.fallbackFromSession(session, override)
12127
- });
12625
+ let mapped;
12626
+ try {
12627
+ mapped = await resolveAutoRoute({
12628
+ text: text3,
12629
+ feature,
12630
+ toolHeavy,
12631
+ map,
12632
+ classifierEnabled: settings.autoClassifierEnabled,
12633
+ classify,
12634
+ isAvailable: (provider, model) => this.modelExists(provider, model),
12635
+ fallback: this.fallbackFromSession(session, override)
12636
+ });
12637
+ } catch (error) {
12638
+ if (error instanceof AutoRouteUnconfiguredError) {
12639
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED", error.message);
12640
+ }
12641
+ throw error;
12642
+ }
12643
+ if (!this.modelExists(mapped.provider, mapped.model) || isAutoModel(mapped)) {
12644
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED");
12645
+ }
12128
12646
  if (feature === "session") {
12129
12647
  setSessionResolvedRouteForSession(session, {
12130
12648
  provider: mapped.provider,
@@ -12259,6 +12777,9 @@ var AuxiliaryModels = class {
12259
12777
  } catch (error) {
12260
12778
  if (controller.signal.aborted) throw controller.signal.reason;
12261
12779
  if (error instanceof AuxiliaryError) throw error;
12780
+ if (error instanceof AutoRouteUnconfiguredError) {
12781
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED", error.message);
12782
+ }
12262
12783
  throw new AuxiliaryError("MODEL_FAILED");
12263
12784
  } finally {
12264
12785
  signal.removeEventListener("abort", abort);
@@ -13802,12 +14323,21 @@ var browserAgentAuditEntrySchema = z4.strictObject({
13802
14323
  url: z4.string().optional(),
13803
14324
  outcome: z4.enum(["ok", "denied", "error", "needs_human"])
13804
14325
  });
14326
+ var browserAgentTabEntrySchema = z4.strictObject({
14327
+ tabId: z4.number().int().positive(),
14328
+ title: z4.string(),
14329
+ url: z4.string(),
14330
+ /** True when this is the driver's currently focused page. */
14331
+ active: z4.boolean(),
14332
+ /** True when any chat session is bound to this tab. */
14333
+ bound: z4.boolean()
14334
+ });
13805
14335
  var browserAgentSnapshotSchema = z4.strictObject({
13806
14336
  enabled: z4.boolean(),
13807
- /** Settings preference (auto / chrome / edge). */
13808
- browser: z4.enum(["auto", "chrome", "edge"]),
14337
+ /** Settings preference (auto / chrome / edge / safari). */
14338
+ browser: z4.enum(["auto", "chrome", "edge", "safari"]),
13809
14339
  /** Actually launched channel once ready; null when not running. */
13810
- launchedBrowser: z4.enum(["chrome", "edge"]).nullable(),
14340
+ launchedBrowser: z4.enum(["chrome", "edge", "safari"]).nullable(),
13811
14341
  /** Shipping driver (Playwright only after MV3 retirement). */
13812
14342
  driver: z4.literal("playwright"),
13813
14343
  allowedOrigins: z4.array(z4.string()),
@@ -13822,6 +14352,8 @@ var browserAgentSnapshotSchema = z4.strictObject({
13822
14352
  tabConflict: browserAgentTabConflictSchema.nullable(),
13823
14353
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
13824
14354
  boundTabId: z4.number().int().nullable(),
14355
+ /** Open tabs in the dedicated browser (empty when not launched). */
14356
+ tabs: z4.array(browserAgentTabEntrySchema),
13825
14357
  audit: z4.array(browserAgentAuditEntrySchema),
13826
14358
  /** Dedicated Chromium profile used by one-click launch (user-level). */
13827
14359
  profileDir: z4.string().min(1)
@@ -13915,7 +14447,7 @@ var browserAgentQuotePageResultCodec = codec(
13915
14447
  browserAgentQuotePageResultSchema
13916
14448
  );
13917
14449
  var browserAgentLaunchBrowserRequestSchema = z4.strictObject({
13918
- browser: z4.enum(["auto", "chrome", "edge"]).optional()
14450
+ browser: z4.enum(["auto", "chrome", "edge", "safari"]).optional()
13919
14451
  });
13920
14452
  var browserAgentLaunchBrowserRequestCodec = codec(
13921
14453
  "dsh-agent-enhancer#BrowserAgentLaunchBrowserRequest",
@@ -13923,7 +14455,7 @@ var browserAgentLaunchBrowserRequestCodec = codec(
13923
14455
  );
13924
14456
  var browserAgentLaunchBrowserResultSchema = z4.strictObject({
13925
14457
  ok: z4.boolean(),
13926
- browser: z4.enum(["chrome", "edge"]).optional(),
14458
+ browser: z4.enum(["chrome", "edge", "safari"]).optional(),
13927
14459
  executable: z4.string().optional(),
13928
14460
  profileDir: z4.string().min(1),
13929
14461
  error: z4.string().optional(),
@@ -13934,7 +14466,7 @@ var browserAgentLaunchBrowserResultCodec = codec(
13934
14466
  browserAgentLaunchBrowserResultSchema
13935
14467
  );
13936
14468
  var browserAgentSetBrowserRequestSchema = z4.strictObject({
13937
- browser: z4.enum(["auto", "chrome", "edge"])
14469
+ browser: z4.enum(["auto", "chrome", "edge", "safari"])
13938
14470
  });
13939
14471
  var browserAgentSetBrowserRequestCodec = codec(
13940
14472
  "dsh-agent-enhancer#BrowserAgentSetBrowserRequest",
@@ -13942,13 +14474,33 @@ var browserAgentSetBrowserRequestCodec = codec(
13942
14474
  );
13943
14475
  var browserAgentSetBrowserResultSchema = z4.strictObject({
13944
14476
  ok: z4.boolean(),
13945
- browser: z4.enum(["auto", "chrome", "edge"]),
14477
+ browser: z4.enum(["auto", "chrome", "edge", "safari"]),
13946
14478
  snapshot: browserAgentSnapshotSchema
13947
14479
  });
13948
14480
  var browserAgentSetBrowserResultCodec = codec(
13949
14481
  "dsh-agent-enhancer#BrowserAgentSetBrowserResult",
13950
14482
  browserAgentSetBrowserResultSchema
13951
14483
  );
14484
+ var browserAgentSelectTabRequestSchema = z4.strictObject({
14485
+ tabId: z4.number().int().positive(),
14486
+ sessionId: z4.string().min(1).optional()
14487
+ });
14488
+ var browserAgentSelectTabRequestCodec = codec(
14489
+ "dsh-agent-enhancer#BrowserAgentSelectTabRequest",
14490
+ browserAgentSelectTabRequestSchema
14491
+ );
14492
+ var browserAgentSelectTabResultSchema = z4.strictObject({
14493
+ ok: z4.boolean(),
14494
+ tabId: z4.number().int().positive().optional(),
14495
+ url: z4.string().optional(),
14496
+ title: z4.string().optional(),
14497
+ error: z4.string().optional(),
14498
+ snapshot: browserAgentSnapshotSchema
14499
+ });
14500
+ var browserAgentSelectTabResultCodec = codec(
14501
+ "dsh-agent-enhancer#BrowserAgentSelectTabResult",
14502
+ browserAgentSelectTabResultSchema
14503
+ );
13952
14504
  var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
13953
14505
  var instructionFileEntrySchema = z4.strictObject({
13954
14506
  id: z4.string().min(1),
@@ -14171,8 +14723,28 @@ var mcpConnectorEntrySchema = z4.strictObject({
14171
14723
  createdAt: z4.number(),
14172
14724
  updatedAt: z4.number()
14173
14725
  });
14726
+ var mcpConnectorStatusStateSchema = z4.enum([
14727
+ "disabled",
14728
+ "unmounted",
14729
+ "connecting",
14730
+ "connected",
14731
+ "reconnecting",
14732
+ "waiting-credentials",
14733
+ "failed",
14734
+ "closed"
14735
+ ]);
14736
+ var mcpConnectorRuntimeStatusSchema = z4.strictObject({
14737
+ state: mcpConnectorStatusStateSchema,
14738
+ detail: z4.string().nullable(),
14739
+ toolCount: z4.number().int().nullable()
14740
+ });
14741
+ var mcpConnectorStatusRowSchema = z4.strictObject({
14742
+ id: z4.string().min(1),
14743
+ status: mcpConnectorRuntimeStatusSchema
14744
+ });
14174
14745
  var mcpConnectorsSnapshotSchema = z4.strictObject({
14175
14746
  connectors: z4.array(mcpConnectorEntrySchema),
14747
+ statuses: z4.array(mcpConnectorStatusRowSchema),
14176
14748
  bridgeAvailable: z4.boolean(),
14177
14749
  bridgeError: z4.string().nullable()
14178
14750
  });
@@ -14249,6 +14821,27 @@ var listMcpConnectorToolsResultSchema = z4.strictObject({
14249
14821
  description: z4.string()
14250
14822
  }))
14251
14823
  });
14824
+ var restartMcpConnectorRequestSchema = z4.strictObject({
14825
+ id: z4.string().min(1)
14826
+ });
14827
+ var restartMcpConnectorResultSchema = z4.strictObject({
14828
+ id: z4.string().min(1),
14829
+ ok: z4.boolean(),
14830
+ error: z4.string().nullable(),
14831
+ snapshot: mcpConnectorsSnapshotSchema
14832
+ });
14833
+ var probeMcpConnectorRequestSchema = z4.strictObject({
14834
+ id: z4.string().min(1)
14835
+ });
14836
+ var probeMcpConnectorResultSchema = z4.strictObject({
14837
+ id: z4.string().min(1),
14838
+ ok: z4.boolean(),
14839
+ message: z4.string(),
14840
+ toolNames: z4.array(z4.string()),
14841
+ truncated: z4.boolean(),
14842
+ durationMs: z4.number(),
14843
+ snapshot: mcpConnectorsSnapshotSchema
14844
+ });
14252
14845
  var listMcpConnectorsRequestCodec = codec(
14253
14846
  "dsh-agent-enhancer#ListMcpConnectorsRequest",
14254
14847
  listMcpConnectorsRequestSchema
@@ -14313,6 +14906,22 @@ var listMcpConnectorToolsResultCodec = codec(
14313
14906
  "dsh-agent-enhancer#ListMcpConnectorToolsResult",
14314
14907
  listMcpConnectorToolsResultSchema
14315
14908
  );
14909
+ var restartMcpConnectorRequestCodec = codec(
14910
+ "dsh-agent-enhancer#RestartMcpConnectorRequest",
14911
+ restartMcpConnectorRequestSchema
14912
+ );
14913
+ var restartMcpConnectorResultCodec = codec(
14914
+ "dsh-agent-enhancer#RestartMcpConnectorResult",
14915
+ restartMcpConnectorResultSchema
14916
+ );
14917
+ var probeMcpConnectorRequestCodec = codec(
14918
+ "dsh-agent-enhancer#ProbeMcpConnectorRequest",
14919
+ probeMcpConnectorRequestSchema
14920
+ );
14921
+ var probeMcpConnectorResultCodec = codec(
14922
+ "dsh-agent-enhancer#ProbeMcpConnectorResult",
14923
+ probeMcpConnectorResultSchema
14924
+ );
14316
14925
  var remoteInfo = createTypertRemoteInfo({
14317
14926
  package: "dsh-agent-enhancer",
14318
14927
  methods: {
@@ -14632,6 +15241,18 @@ var remoteInfo = createTypertRemoteInfo({
14632
15241
  }],
14633
15242
  result: browserAgentSetBrowserResultCodec
14634
15243
  },
15244
+ "agentEnhancer/browserAgentSelectTab": {
15245
+ service: "agentEnhancer",
15246
+ implementation: "browserAgentSelectTab",
15247
+ invocation: { kind: "direct" },
15248
+ parameters: [{
15249
+ name: "request",
15250
+ source: "json",
15251
+ codec: browserAgentSelectTabRequestCodec,
15252
+ strictCodec: browserAgentSelectTabRequestCodec
15253
+ }],
15254
+ result: browserAgentSelectTabResultCodec
15255
+ },
14635
15256
  "agentEnhancer/listInstructionsSkills": {
14636
15257
  service: "agentEnhancer",
14637
15258
  implementation: "listInstructionsSkills",
@@ -14853,6 +15474,32 @@ var remoteInfo = createTypertRemoteInfo({
14853
15474
  cancellation: { parameter: "signal" },
14854
15475
  result: listMcpConnectorToolsResultCodec
14855
15476
  },
15477
+ "agentEnhancer/restartMcpConnector": {
15478
+ service: "agentEnhancer",
15479
+ implementation: "restartMcpConnector",
15480
+ invocation: { kind: "direct" },
15481
+ parameters: [{
15482
+ name: "request",
15483
+ source: "json",
15484
+ codec: restartMcpConnectorRequestCodec,
15485
+ strictCodec: restartMcpConnectorRequestCodec
15486
+ }],
15487
+ cancellation: { parameter: "signal" },
15488
+ result: restartMcpConnectorResultCodec
15489
+ },
15490
+ "agentEnhancer/probeMcpConnector": {
15491
+ service: "agentEnhancer",
15492
+ implementation: "probeMcpConnector",
15493
+ invocation: { kind: "direct" },
15494
+ parameters: [{
15495
+ name: "request",
15496
+ source: "json",
15497
+ codec: probeMcpConnectorRequestCodec,
15498
+ strictCodec: probeMcpConnectorRequestCodec
15499
+ }],
15500
+ cancellation: { parameter: "signal" },
15501
+ result: probeMcpConnectorResultCodec
15502
+ },
14856
15503
  "agentEnhancer/listWebChatWorkspaces": {
14857
15504
  service: "agentEnhancer",
14858
15505
  implementation: "listWebChatWorkspaces",
@@ -15240,11 +15887,14 @@ async function showOsNotificationNow(input) {
15240
15887
  }
15241
15888
 
15242
15889
  // src/host/update/check.ts
15243
- import { homedir as homedir5 } from "node:os";
15890
+ import { homedir as homedir6 } from "node:os";
15244
15891
  import { join as join31 } from "node:path";
15245
15892
 
15246
15893
  // src/host/update/cli.ts
15247
15894
  import { spawn as nodeSpawn } from "node:child_process";
15895
+ import { existsSync as existsSync20 } from "node:fs";
15896
+ import { homedir as homedir5 } from "node:os";
15897
+ import { posix as pathPosix2 } from "node:path";
15248
15898
  function defaultSpawn(command, args, options) {
15249
15899
  return nodeSpawn(command, [...args], options ?? {});
15250
15900
  }
@@ -15254,6 +15904,40 @@ var STRICT_SEMVER = /^\d+\.\d+\.\d+$/;
15254
15904
  function isStrictVersion(value) {
15255
15905
  return STRICT_SEMVER.test(value);
15256
15906
  }
15907
+ function dshFromElectronExecPath(execPath) {
15908
+ const normalized = execPath.replace(/\\/g, "/");
15909
+ const marker = "/Contents/MacOS/";
15910
+ const idx = normalized.lastIndexOf(marker);
15911
+ if (idx < 0) return null;
15912
+ const contentsRoot = normalized.slice(0, idx + "/Contents".length);
15913
+ return pathPosix2.join(contentsRoot, "Resources", "runtime", "cli", "bin", "dsh");
15914
+ }
15915
+ function dshExecutableCandidates(options = {}) {
15916
+ const platform = options.platform ?? process.platform;
15917
+ const env = options.env ?? process.env;
15918
+ const home = options.home ?? env.HOME?.trim() ?? homedir5();
15919
+ const execPath = options.execPath ?? process.execPath;
15920
+ const out = [];
15921
+ const push = (value) => {
15922
+ const trimmed = typeof value === "string" ? value.trim() : "";
15923
+ if (trimmed === "" || out.includes(trimmed)) return;
15924
+ out.push(trimmed);
15925
+ };
15926
+ push(env.DSH_CLI);
15927
+ if (platform === "darwin") {
15928
+ push(dshFromElectronExecPath(execPath));
15929
+ push("/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
15930
+ push(pathPosix2.join(
15931
+ home,
15932
+ "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh"
15933
+ ));
15934
+ }
15935
+ push("dsh");
15936
+ return out;
15937
+ }
15938
+ function isCommandMissingDetail(detail) {
15939
+ return /ENOENT|not found|spawn .*(ENOENT|not found)/i.test(detail);
15940
+ }
15257
15941
  function dshSpawnOptions() {
15258
15942
  const base = { stdio: ["ignore", "pipe", "pipe"] };
15259
15943
  return process.platform === "win32" ? { ...base, shell: true, windowsHide: true } : base;
@@ -15292,22 +15976,35 @@ function waitForExit(child, timeoutMs) {
15292
15976
  });
15293
15977
  });
15294
15978
  }
15295
- async function runDsh(args, spawnFn, timeoutMs) {
15979
+ async function runDshOnce(command, args, spawnFn, timeoutMs) {
15296
15980
  let child;
15297
15981
  try {
15298
- child = spawnFn("dsh", args, dshSpawnOptions());
15982
+ child = spawnFn(command, args, dshSpawnOptions());
15299
15983
  } catch (err) {
15300
15984
  return { ok: false, detail: err instanceof Error ? err.message : String(err) };
15301
15985
  }
15302
15986
  return waitForExit(child, timeoutMs);
15303
15987
  }
15304
- async function probeDsh(spawnFn = defaultSpawn) {
15305
- const result = await runDsh(["--version"], spawnFn, PROBE_TIMEOUT_MS);
15988
+ async function runDsh(args, spawnFn, timeoutMs, options = {}) {
15989
+ const candidates = options.candidates ?? dshExecutableCandidates();
15990
+ const exists = options.exists ?? existsSync20;
15991
+ let last = { ok: false, detail: "dsh not found" };
15992
+ for (const command of candidates) {
15993
+ if (command !== "dsh" && !exists(command)) continue;
15994
+ const result = await runDshOnce(command, args, spawnFn, timeoutMs);
15995
+ if (result.ok) return result;
15996
+ last = result;
15997
+ if (!isCommandMissingDetail(result.detail)) return result;
15998
+ }
15999
+ return last;
16000
+ }
16001
+ async function probeDsh(spawnFn = defaultSpawn, options = {}) {
16002
+ const result = await runDsh(["--version"], spawnFn, PROBE_TIMEOUT_MS, options);
15306
16003
  return result.ok;
15307
16004
  }
15308
- async function runPluginAdd(latest, spawnFn = defaultSpawn) {
16005
+ async function runPluginAdd(latest, spawnFn = defaultSpawn, options = {}) {
15309
16006
  if (!isStrictVersion(latest)) return { ok: false, detail: "invalid version" };
15310
- return runDsh(pluginAddArgs(latest), spawnFn, RUN_ADD_TIMEOUT_MS);
16007
+ return runDsh(pluginAddArgs(latest), spawnFn, RUN_ADD_TIMEOUT_MS, options);
15311
16008
  }
15312
16009
 
15313
16010
  // src/host/update/install-kind.ts
@@ -15444,7 +16141,7 @@ function isNewerVersion(latest, current) {
15444
16141
  }
15445
16142
 
15446
16143
  // src/host/update/check.ts
15447
- function resolveDesktopProfileDir(env = process.env, home = homedir5()) {
16144
+ function resolveDesktopProfileDir(env = process.env, home = homedir6()) {
15448
16145
  const dshHome2 = env.DSH_HOME ?? join31(home, ".dsh");
15449
16146
  return join31(dshHome2, "profiles", "desktop");
15450
16147
  }
@@ -15503,6 +16200,12 @@ async function applyPluginUpdateForHost(messages, overrides) {
15503
16200
  }
15504
16201
 
15505
16202
  // src/host/index.ts
16203
+ function hostBrowserPreference(value) {
16204
+ return coerceBrowserAgentBrowserForPlatform(
16205
+ resolveBrowserAgentBrowser(value),
16206
+ process.platform
16207
+ );
16208
+ }
15506
16209
  var name = PLUGIN_ID;
15507
16210
  var inject = [
15508
16211
  "llm",
@@ -15586,12 +16289,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
15586
16289
  };
15587
16290
  }
15588
16291
  }, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
15589
- join32(homedir6(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
16292
+ join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
15590
16293
  ), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null, browserAgent = null, browserAgentSettings = () => ({
15591
16294
  enabled: false,
15592
16295
  browser: "auto"
15593
16296
  }), setBrowserAgentBrowser = () => void 0, browserAgentProfileDir = defaultBrowserAgentProfileDir(
15594
- join32(homedir6(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
16297
+ join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
15595
16298
  )) {
15596
16299
  super(ctx, "agentEnhancer");
15597
16300
  this.models = models;
@@ -15621,7 +16324,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
15621
16324
  browserAgentSettings;
15622
16325
  setBrowserAgentBrowser;
15623
16326
  browserAgentProfileDir;
15624
- browserSnapshotNow() {
16327
+ async browserSnapshotNow() {
15625
16328
  const settings = this.browserAgentSettings();
15626
16329
  const driverStatus = this.browserAgent?.driverStatus();
15627
16330
  const pending = this.browserAgent?.approval.current() ?? null;
@@ -15631,10 +16334,13 @@ var AgentEnhancerService = class extends TypertRemoteService {
15631
16334
  sessionId: waiting.sessionId,
15632
16335
  detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail
15633
16336
  } : this.browserAgent?.sessions.anyNeedsHuman() ?? null;
15634
- const boundTabId = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
16337
+ const overlayBound = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
15635
16338
  const connected = driverStatus?.ready === true;
16339
+ const listed = connected ? await this.browserAgent?.listTabs() : void 0;
16340
+ const tabs = listed?.tabs ?? [];
16341
+ const boundTabId = overlayBound ?? listed?.boundTabId ?? null;
15636
16342
  const endpoint = driverStatus?.endpoint ?? "playwright:unlaunched";
15637
- const launched = endpoint === "playwright:msedge" ? "edge" : endpoint === "playwright:chrome" ? "chrome" : null;
16343
+ const launched = endpoint === "playwright:msedge" ? "edge" : endpoint === "playwright:chrome" ? "chrome" : endpoint === "playwright:webkit" ? "safari" : null;
15638
16344
  return {
15639
16345
  enabled: settings.enabled,
15640
16346
  browser: settings.browser,
@@ -15659,6 +16365,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
15659
16365
  tabConflict: conflict,
15660
16366
  needsHuman,
15661
16367
  boundTabId,
16368
+ tabs: [...tabs],
15662
16369
  audit: [...this.browserAgent?.sessions.recentAudit(12) ?? []],
15663
16370
  profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir
15664
16371
  };
@@ -15693,7 +16400,8 @@ var AgentEnhancerService = class extends TypertRemoteService {
15693
16400
  } catch (error) {
15694
16401
  if (signal.aborted) throw error;
15695
16402
  const code = error instanceof AuxiliaryError ? error.code : "MODEL_FAILED";
15696
- throw new RemoteError2("agent-enhancer/failed", "Agent Enhance request failed", { code });
16403
+ const detail = error instanceof AuxiliaryError ? error.message : "Agent Enhance request failed";
16404
+ throw new RemoteError2("agent-enhancer/failed", detail || "Agent Enhance request failed", { code });
15697
16405
  }
15698
16406
  }
15699
16407
  /** Same Desktop catalog the official model selector uses (`llm` registry). */
@@ -15836,7 +16544,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
15836
16544
  }
15837
16545
  }
15838
16546
  webChatPluginDataRoot() {
15839
- return this.installLedgerRoot ?? join32(homedir6(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
16547
+ return this.installLedgerRoot ?? join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
15840
16548
  }
15841
16549
  /** User-level web chat guest login snapshot (non-HttpOnly storage only). */
15842
16550
  async loadWebChatLoginSnapshot(_request, signal) {
@@ -16208,6 +16916,26 @@ var AgentEnhancerService = class extends TypertRemoteService {
16208
16916
  throw instructionsSkillsRemoteError(error);
16209
16917
  }
16210
16918
  }
16919
+ async restartMcpConnector(request, signal) {
16920
+ this.assertOwner();
16921
+ signal.throwIfAborted();
16922
+ try {
16923
+ return await restartMcpConnectorNow(this.requireMcpHost(), request);
16924
+ } catch (error) {
16925
+ if (signal.aborted) throw error;
16926
+ throw instructionsSkillsRemoteError(error);
16927
+ }
16928
+ }
16929
+ async probeMcpConnector(request, signal) {
16930
+ this.assertOwner();
16931
+ signal.throwIfAborted();
16932
+ try {
16933
+ return await probeMcpConnectorNow(this.requireMcpHost(), request, signal);
16934
+ } catch (error) {
16935
+ if (signal.aborted) throw error;
16936
+ throw instructionsSkillsRemoteError(error);
16937
+ }
16938
+ }
16211
16939
  async listMcpConnectorTools(request, signal) {
16212
16940
  this.assertOwner();
16213
16941
  signal.throwIfAborted();
@@ -16245,22 +16973,22 @@ var AgentEnhancerService = class extends TypertRemoteService {
16245
16973
  }
16246
16974
  async browserAgentSnapshot() {
16247
16975
  this.assertOwner();
16248
- return this.browserSnapshotNow();
16976
+ return await this.browserSnapshotNow();
16249
16977
  }
16250
16978
  async browserAgentResolve(request) {
16251
16979
  this.assertOwner();
16252
16980
  const ok = this.browserAgent?.approval.resolve(request.id, request.decision) ?? false;
16253
- return { ok, snapshot: this.browserSnapshotNow() };
16981
+ return { ok, snapshot: await this.browserSnapshotNow() };
16254
16982
  }
16255
16983
  async browserAgentResolveTabConflict(request) {
16256
16984
  this.assertOwner();
16257
16985
  const result = await this.browserAgent?.resolveTabConflict(request.decision);
16258
- return { ok: result?.ok === true, snapshot: this.browserSnapshotNow() };
16986
+ return { ok: result?.ok === true, snapshot: await this.browserSnapshotNow() };
16259
16987
  }
16260
16988
  async browserAgentAcknowledgeHuman(request) {
16261
16989
  this.assertOwner();
16262
16990
  const ok = this.browserAgent?.acknowledgeHuman(request.sessionId) === true;
16263
- return { ok, snapshot: this.browserSnapshotNow() };
16991
+ return { ok, snapshot: await this.browserSnapshotNow() };
16264
16992
  }
16265
16993
  async browserAgentOpenUrl(request) {
16266
16994
  this.assertOwner();
@@ -16273,7 +17001,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16273
17001
  ...result?.url === void 0 ? {} : { url: result.url },
16274
17002
  ...result?.title === void 0 ? {} : { title: result.title },
16275
17003
  ...result?.error === void 0 ? {} : { error: result.error },
16276
- snapshot: this.browserSnapshotNow()
17004
+ snapshot: await this.browserSnapshotNow()
16277
17005
  };
16278
17006
  }
16279
17007
  async browserAgentQuotePage(request) {
@@ -16285,7 +17013,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16285
17013
  ...result?.url === void 0 ? {} : { url: result.url },
16286
17014
  ...result?.title === void 0 ? {} : { title: result.title },
16287
17015
  ...result?.error === void 0 ? {} : { error: result.error },
16288
- snapshot: this.browserSnapshotNow()
17016
+ snapshot: await this.browserSnapshotNow()
16289
17017
  };
16290
17018
  }
16291
17019
  async browserAgentLaunchBrowser(request) {
@@ -16296,13 +17024,13 @@ var AgentEnhancerService = class extends TypertRemoteService {
16296
17024
  ok: false,
16297
17025
  profileDir: this.browserAgentProfileDir,
16298
17026
  error: "Browser agent is disabled in settings.",
16299
- snapshot: this.browserSnapshotNow()
17027
+ snapshot: await this.browserSnapshotNow()
16300
17028
  };
16301
17029
  }
16302
- const preference = request.browser ?? settings.browser;
17030
+ const preference = hostBrowserPreference(request.browser ?? settings.browser);
16303
17031
  this.setBrowserAgentBrowser(preference);
16304
17032
  const launched = await this.browserAgent?.launchDedicated(void 0, preference);
16305
- const snapshot = this.browserSnapshotNow();
17033
+ const snapshot = await this.browserSnapshotNow();
16306
17034
  return {
16307
17035
  ok: launched?.ok === true,
16308
17036
  profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir,
@@ -16313,15 +17041,31 @@ var AgentEnhancerService = class extends TypertRemoteService {
16313
17041
  }
16314
17042
  async browserAgentSetBrowser(request) {
16315
17043
  this.assertOwner();
16316
- this.setBrowserAgentBrowser(request.browser);
17044
+ const preference = hostBrowserPreference(request.browser);
17045
+ this.setBrowserAgentBrowser(preference);
16317
17046
  const settings = this.browserAgentSettings();
16318
17047
  if (settings.enabled && this.browserAgent?.driverStatus()?.ready === true) {
16319
17048
  await this.browserAgent.alignToPreference();
16320
17049
  }
16321
17050
  return {
16322
17051
  ok: true,
16323
- browser: request.browser,
16324
- snapshot: this.browserSnapshotNow()
17052
+ browser: preference,
17053
+ snapshot: await this.browserSnapshotNow()
17054
+ };
17055
+ }
17056
+ async browserAgentSelectTab(request) {
17057
+ this.assertOwner();
17058
+ const result = await this.browserAgent?.selectTab({
17059
+ tabId: request.tabId,
17060
+ ...request.sessionId === void 0 ? {} : { sessionId: request.sessionId }
17061
+ });
17062
+ return {
17063
+ ok: result?.ok === true,
17064
+ ...result?.tabId === void 0 ? {} : { tabId: result.tabId },
17065
+ ...result?.url === void 0 ? {} : { url: result.url },
17066
+ ...result?.title === void 0 ? {} : { title: result.title },
17067
+ ...result?.error === void 0 ? {} : { error: result.error },
17068
+ snapshot: await this.browserSnapshotNow()
16325
17069
  };
16326
17070
  }
16327
17071
  async applyUpdate() {
@@ -16340,12 +17084,12 @@ function resolveCheckpointRoot(dshHome2) {
16340
17084
  const nextPkg = join32(base, PACKAGE_NAME);
16341
17085
  const next = join32(nextPkg, "checkpoint");
16342
17086
  const prev = join32(base, LEGACY_PACKAGE_NAME, "checkpoint");
16343
- if (!existsSync19(next) && existsSync19(prev)) {
16344
- mkdirSync11(nextPkg, { recursive: true });
17087
+ if (!existsSync21(next) && existsSync21(prev)) {
17088
+ mkdirSync12(nextPkg, { recursive: true });
16345
17089
  renameSync9(prev, next);
16346
17090
  const prevPkg = join32(base, LEGACY_PACKAGE_NAME);
16347
17091
  try {
16348
- if (existsSync19(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
17092
+ if (existsSync21(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
16349
17093
  } catch {
16350
17094
  }
16351
17095
  }
@@ -16416,7 +17160,7 @@ function readSettings(config) {
16416
17160
  runAlertsEnabled: config.runAlertsEnabled.get(),
16417
17161
  runAlertsLevel: resolveRunAlertsLevel(config.runAlertsLevel.get()),
16418
17162
  browserAgentEnabled: config.browserAgentEnabled.get(),
16419
- browserAgentBrowser: resolveBrowserAgentBrowser(config.browserAgentBrowser.get()),
17163
+ browserAgentBrowser: hostBrowserPreference(config.browserAgentBrowser.get()),
16420
17164
  webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
16421
17165
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
16422
17166
  mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
@@ -16448,7 +17192,7 @@ function apply(ctx, config) {
16448
17192
  const settings = () => readSettings(config);
16449
17193
  const models = new AuxiliaryModels(ctx, settings);
16450
17194
  installAutoSessionRoute(ctx, { settings });
16451
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join32(homedir6(), ".dsh"));
17195
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join32(homedir7(), ".dsh"));
16452
17196
  const pluginDataPackageRoot = join32(storageRoot, "..");
16453
17197
  const usage = new UsageLedger(join32(storageRoot, "..", "usage"), (message) => {
16454
17198
  ctx.logger.warn(message);
@@ -16552,7 +17296,7 @@ function apply(ctx, config) {
16552
17296
  browser: browserAgentLive.browser
16553
17297
  }),
16554
17298
  (browser) => {
16555
- browserAgentLive.browser = resolveBrowserAgentBrowser(browser);
17299
+ browserAgentLive.browser = hostBrowserPreference(browser);
16556
17300
  },
16557
17301
  browserAgentProfileDir
16558
17302
  );
@@ -16565,13 +17309,11 @@ function apply(ctx, config) {
16565
17309
  const detail = error instanceof Error ? error.message : String(error);
16566
17310
  ctx.logger.warn(`agent-enhancer: MCP connector sync after settings update failed: ${detail}`);
16567
17311
  });
16568
- const prevEnabled = browserAgentLive.enabled;
16569
17312
  const prevBrowser = browserAgentLive.browser;
16570
17313
  browserAgentLive.enabled = cfg.browserAgentEnabled.get();
16571
- browserAgentLive.browser = resolveBrowserAgentBrowser(cfg.browserAgentBrowser.get());
16572
- if (prevEnabled !== browserAgentLive.enabled) {
16573
- browserAgent.refresh();
16574
- } else if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
17314
+ browserAgentLive.browser = hostBrowserPreference(cfg.browserAgentBrowser.get());
17315
+ browserAgent.refresh();
17316
+ if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
16575
17317
  void browserAgent.alignToPreference().catch((error) => {
16576
17318
  const detail = error instanceof Error ? error.message : String(error);
16577
17319
  ctx.logger.warn(`agent-enhancer: browser preference align after settings failed: ${detail}`);