dsh-agent-enhancer 0.3.9 → 0.3.11

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 (95) hide show
  1. package/README.en.md +29 -13
  2. package/README.md +27 -11
  3. package/lib/client/browser-agent/tab.d.ts.map +1 -1
  4. package/lib/client/dsh/settings-catalog.d.ts +2 -2
  5. package/lib/client/dsh/settings-catalog.d.ts.map +1 -1
  6. package/lib/client/dsh/settings-features.d.ts.map +1 -1
  7. package/lib/client/dsh/settings.d.ts.map +1 -1
  8. package/lib/client/index.d.ts.map +1 -1
  9. package/lib/client/locales.d.ts +288 -178
  10. package/lib/client/locales.d.ts.map +1 -1
  11. package/lib/client/manager-shell.d.ts +1 -0
  12. package/lib/client/manager-shell.d.ts.map +1 -1
  13. package/lib/client/remote.d.ts +24 -0
  14. package/lib/client/remote.d.ts.map +1 -1
  15. package/lib/client/web-chat-bridge/capture-selectors.d.ts +47 -0
  16. package/lib/client/web-chat-bridge/capture-selectors.d.ts.map +1 -0
  17. package/lib/client/web-chat-bridge/capture.d.ts +14 -0
  18. package/lib/client/web-chat-bridge/capture.d.ts.map +1 -0
  19. package/lib/client/web-chat-bridge/export-markdown.d.ts +8 -0
  20. package/lib/client/web-chat-bridge/export-markdown.d.ts.map +1 -0
  21. package/lib/client/web-chat-bridge/guest-capture.d.ts +10 -0
  22. package/lib/client/web-chat-bridge/guest-capture.d.ts.map +1 -0
  23. package/lib/client/web-chat-bridge/guest-policy.d.ts +56 -0
  24. package/lib/client/web-chat-bridge/guest-policy.d.ts.map +1 -0
  25. package/lib/client/web-chat-bridge/guest.d.ts +39 -0
  26. package/lib/client/web-chat-bridge/guest.d.ts.map +1 -0
  27. package/lib/client/web-chat-bridge/guide-icon.d.ts +4 -0
  28. package/lib/client/web-chat-bridge/guide-icon.d.ts.map +1 -0
  29. package/lib/client/web-chat-bridge/kind.d.ts +4 -0
  30. package/lib/client/web-chat-bridge/kind.d.ts.map +1 -0
  31. package/lib/client/web-chat-bridge/left-nav.d.ts +27 -0
  32. package/lib/client/web-chat-bridge/left-nav.d.ts.map +1 -0
  33. package/lib/client/web-chat-bridge/panel.d.ts +13 -0
  34. package/lib/client/web-chat-bridge/panel.d.ts.map +1 -0
  35. package/lib/client/web-chat-bridge/preview-model.d.ts +7 -0
  36. package/lib/client/web-chat-bridge/preview-model.d.ts.map +1 -0
  37. package/lib/client/web-chat-bridge/preview.d.ts +14 -0
  38. package/lib/client/web-chat-bridge/preview.d.ts.map +1 -0
  39. package/lib/client/web-chat-bridge/remote.d.ts +33 -0
  40. package/lib/client/web-chat-bridge/remote.d.ts.map +1 -0
  41. package/lib/client/web-chat-bridge/share-fetch.d.ts +7 -0
  42. package/lib/client/web-chat-bridge/share-fetch.d.ts.map +1 -0
  43. package/lib/client/web-chat-bridge/slot-types.d.ts +16 -0
  44. package/lib/client/web-chat-bridge/slot-types.d.ts.map +1 -0
  45. package/lib/client.js +3024 -1133
  46. package/lib/client.js.map +1 -1
  47. package/lib/config.d.ts +16 -4
  48. package/lib/config.d.ts.map +1 -1
  49. package/lib/host/browser-agent/install.d.ts.map +1 -1
  50. package/lib/host/browser-agent/launch.d.ts +26 -6
  51. package/lib/host/browser-agent/launch.d.ts.map +1 -1
  52. package/lib/host/browser-agent/playwright-driver.d.ts +9 -0
  53. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  54. package/lib/host/browser-agent/tools.d.ts +2 -2
  55. package/lib/host/extra-folders/pick.d.ts +7 -0
  56. package/lib/host/extra-folders/pick.d.ts.map +1 -1
  57. package/lib/host/index.d.ts +48 -2
  58. package/lib/host/index.d.ts.map +1 -1
  59. package/lib/host/rpc.d.ts +208 -0
  60. package/lib/host/rpc.d.ts.map +1 -1
  61. package/lib/host/update/cli.d.ts +28 -2
  62. package/lib/host/update/cli.d.ts.map +1 -1
  63. package/lib/host/web-chat-bridge/import-session.d.ts +112 -0
  64. package/lib/host/web-chat-bridge/import-session.d.ts.map +1 -0
  65. package/lib/host/web-chat-bridge/limits.d.ts +9 -0
  66. package/lib/host/web-chat-bridge/limits.d.ts.map +1 -0
  67. package/lib/host/web-chat-bridge/login-snapshot-policy.d.ts +5 -0
  68. package/lib/host/web-chat-bridge/login-snapshot-policy.d.ts.map +1 -0
  69. package/lib/host/web-chat-bridge/login-snapshot-types.d.ts +11 -0
  70. package/lib/host/web-chat-bridge/login-snapshot-types.d.ts.map +1 -0
  71. package/lib/host/web-chat-bridge/login-snapshot.d.ts +14 -0
  72. package/lib/host/web-chat-bridge/login-snapshot.d.ts.map +1 -0
  73. package/lib/host/web-chat-bridge/parse-export.d.ts +6 -0
  74. package/lib/host/web-chat-bridge/parse-export.d.ts.map +1 -0
  75. package/lib/host/web-chat-bridge/share-link.d.ts +29 -0
  76. package/lib/host/web-chat-bridge/share-link.d.ts.map +1 -0
  77. package/lib/host/web-chat-bridge/types.d.ts +37 -0
  78. package/lib/host/web-chat-bridge/types.d.ts.map +1 -0
  79. package/lib/identity.d.ts +1 -1
  80. package/lib/identity.d.ts.map +1 -1
  81. package/lib/index.js +2095 -470
  82. package/lib/index.js.map +4 -4
  83. package/package.json +1 -1
  84. package/lib/host/browser-agent/auto-nav.test.d.ts +0 -2
  85. package/lib/host/browser-agent/auto-nav.test.d.ts.map +0 -1
  86. package/lib/host/browser-agent/extract.test.d.ts +0 -2
  87. package/lib/host/browser-agent/extract.test.d.ts.map +0 -1
  88. package/lib/host/browser-agent/human-gate.test.d.ts +0 -2
  89. package/lib/host/browser-agent/human-gate.test.d.ts.map +0 -1
  90. package/lib/host/browser-agent/page-links.test.d.ts +0 -2
  91. package/lib/host/browser-agent/page-links.test.d.ts.map +0 -1
  92. package/lib/host/browser-agent/path-key.test.d.ts +0 -2
  93. package/lib/host/browser-agent/path-key.test.d.ts.map +0 -1
  94. package/lib/host/browser-agent/pick-auto-nav.test.d.ts +0 -2
  95. package/lib/host/browser-agent/pick-auto-nav.test.d.ts.map +0 -1
package/lib/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // src/host/index.ts
2
- import { existsSync as existsSync17, mkdirSync as mkdirSync10, readdirSync as readdirSync7, renameSync as renameSync8, rmdirSync } from "node:fs";
3
- import { homedir as homedir6 } from "node:os";
4
- import { join as join31 } from "node:path";
2
+ import { existsSync as existsSync21, mkdirSync as mkdirSync11, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
+ import { homedir as homedir7 } from "node:os";
4
+ import { join as join33 } from "node:path";
5
5
  import z5 from "@deepseek-ai/schemastery";
6
- import { RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
6
+ import { RemoteError as RemoteError2, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
7
7
 
8
8
  // src/host/auto-route/sentinel.ts
9
9
  var AUTO_PROVIDER = "agent-enhancer";
@@ -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: "",
@@ -50,6 +68,7 @@ var DEFAULT_SETTINGS = {
50
68
  runAlertsLevel: "unfocused",
51
69
  browserAgentEnabled: false,
52
70
  browserAgentBrowser: "auto",
71
+ webChatBridgeEnabled: true,
53
72
  instructionsSkillsEnabled: true,
54
73
  mcpConnectorsEnabled: true,
55
74
  optimizeProvider: "",
@@ -94,6 +113,7 @@ function resolveSettings(value) {
94
113
  runAlertsLevel: resolveRunAlertsLevel(value?.runAlertsLevel),
95
114
  browserAgentEnabled: value?.browserAgentEnabled ?? false,
96
115
  browserAgentBrowser: resolveBrowserAgentBrowser(value?.browserAgentBrowser),
116
+ webChatBridgeEnabled: value?.webChatBridgeEnabled ?? true,
97
117
  instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
98
118
  mcpConnectorsEnabled: value?.mcpConnectorsEnabled ?? true,
99
119
  optimizeProvider: text(value?.optimizeProvider),
@@ -253,7 +273,7 @@ var BrowserApprovalGate = class {
253
273
  ...input.url === void 0 ? {} : { url: input.url },
254
274
  ...origin === void 0 ? {} : { origin }
255
275
  };
256
- const decision = await new Promise((resolve16, reject) => {
276
+ const decision = await new Promise((resolve17, reject) => {
257
277
  const onAbort = () => {
258
278
  const entry = this.pending.get(id);
259
279
  if (entry === void 0) return;
@@ -267,7 +287,7 @@ var BrowserApprovalGate = class {
267
287
  };
268
288
  this.pending.set(id, {
269
289
  request,
270
- resolve: resolve16,
290
+ resolve: resolve17,
271
291
  reject,
272
292
  detachAbort
273
293
  });
@@ -342,7 +362,7 @@ var BrowserHumanGate = class {
342
362
  detail: input.detail,
343
363
  ...input.url === void 0 ? {} : { url: input.url }
344
364
  };
345
- return await new Promise((resolve16, reject) => {
365
+ return await new Promise((resolve17, reject) => {
346
366
  const onAbort = () => {
347
367
  const entry = this.pending.get(id);
348
368
  if (entry === void 0) return;
@@ -356,7 +376,7 @@ var BrowserHumanGate = class {
356
376
  };
357
377
  this.pending.set(id, {
358
378
  request,
359
- resolve: resolve16,
379
+ resolve: resolve17,
360
380
  reject,
361
381
  detachAbort
362
382
  });
@@ -383,7 +403,16 @@ var BrowserHumanGate = class {
383
403
  import { execFileSync } from "node:child_process";
384
404
  import { existsSync } from "node:fs";
385
405
  import { homedir } from "node:os";
386
- 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
+ ];
387
416
  function windowsEnv(name2, env = process.env) {
388
417
  const variants = [
389
418
  name2,
@@ -402,8 +431,23 @@ function windowsEnv(name2, env = process.env) {
402
431
  }
403
432
  return void 0;
404
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
+ }
405
449
  function browserExecutableCandidates(kind, platform = process.platform, env = process.env) {
406
- const home = homedir();
450
+ const home = env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();
407
451
  if (platform === "win32") {
408
452
  const local = windowsEnv("LocalAppData", env);
409
453
  const programFiles64 = windowsEnv("ProgramW6432", env) ?? "C:\\Program Files";
@@ -421,6 +465,7 @@ function browserExecutableCandidates(kind, platform = process.platform, env = pr
421
465
  join(home, "AppData", "Local", "Google", "Chrome", "Application", "chrome.exe")
422
466
  ];
423
467
  }
468
+ if (kind === "safari") return [];
424
469
  return [
425
470
  ...roots.map((root) => join(root, "Microsoft", "Edge", "Application", "msedge.exe")),
426
471
  "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
@@ -430,17 +475,33 @@ function browserExecutableCandidates(kind, platform = process.platform, env = pr
430
475
  }
431
476
  if (platform === "darwin") {
432
477
  if (kind === "chrome") {
433
- 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
+ ]);
434
488
  }
435
- 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
+ ]);
436
494
  }
437
495
  if (kind === "chrome") {
438
496
  return ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser"];
439
497
  }
498
+ if (kind === "safari") {
499
+ return [];
500
+ }
440
501
  return ["/usr/bin/microsoft-edge", "/usr/bin/microsoft-edge-stable"];
441
502
  }
442
503
  function lookUpOnPath(kind, platform, where, exists) {
443
- 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"] : [];
444
505
  for (const name2 of names) {
445
506
  const hit = where(name2);
446
507
  if (hit !== null && exists(hit)) return hit;
@@ -469,7 +530,7 @@ function resolveBrowserExecutable(preference = "auto", options = {}) {
469
530
  const exists = options.exists ?? existsSync;
470
531
  const platform = options.platform ?? process.platform;
471
532
  const env = options.env ?? process.env;
472
- 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];
473
534
  for (const kind of order) {
474
535
  const seen = /* @__PURE__ */ new Set();
475
536
  for (const executable of browserExecutableCandidates(kind, platform, env)) {
@@ -485,14 +546,29 @@ function resolveBrowserExecutable(preference = "auto", options = {}) {
485
546
  function defaultBrowserAgentProfileDir(pluginDataPackageRoot) {
486
547
  return browserAgentProfileDirFor(pluginDataPackageRoot, "auto");
487
548
  }
488
- function browserAgentProfileDirFor(pluginDataPackageRoot, preference) {
489
- const slot = preference === "chrome" || preference === "edge" ? preference : "auto";
549
+ function browserAgentProfileSlotDir(pluginDataPackageRoot, slot) {
490
550
  return join(pluginDataPackageRoot, "browser-agent", `profile-${slot}`);
491
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
+ }
492
561
  function playwrightChannelOrder(preference, platform = process.platform) {
493
562
  if (preference === "chrome") return ["chrome"];
494
563
  if (preference === "edge") return ["msedge"];
495
- 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);
496
572
  }
497
573
  function stopAgentBrowserProcesses(profileDir) {
498
574
  if (profileDir.trim() === "") return;
@@ -528,8 +604,8 @@ function stopAgentBrowserProcesses(profileDir) {
528
604
  }
529
605
 
530
606
  // src/host/browser-agent/playwright-driver.ts
531
- import { mkdirSync } from "node:fs";
532
- import { chromium } from "playwright-core";
607
+ import { existsSync as existsSync2, mkdirSync } from "node:fs";
608
+ import { chromium, webkit } from "playwright-core";
533
609
 
534
610
  // src/host/browser-agent/proximity.ts
535
611
  function attachHrefByProximity(nodes, anchors) {
@@ -955,6 +1031,13 @@ var PlaywrightDriver = class {
955
1031
  currentProfileDir() {
956
1032
  return typeof this.profileDirOption === "function" ? this.profileDirOption() : this.profileDirOption;
957
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
+ }
958
1041
  /** Latest snapshot refs — used by the click/type path. */
959
1042
  refOf(ref) {
960
1043
  return this.lastRefs.get(ref);
@@ -972,9 +1055,8 @@ var PlaywrightDriver = class {
972
1055
  }
973
1056
  async ensureReady(startUrl) {
974
1057
  const preference = this.currentPreference();
975
- const profileDir = this.currentProfileDir();
976
- const wantChannel = playwrightChannelOrder(preference, process.platform)[0];
977
- 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);
978
1060
  if (runningOk) {
979
1061
  if (typeof startUrl === "string" && /^https?:\/\//i.test(startUrl)) {
980
1062
  const current = this.page.url();
@@ -987,34 +1069,18 @@ var PlaywrightDriver = class {
987
1069
  if (this.context !== null) {
988
1070
  await this.dispose().catch(() => void 0);
989
1071
  }
990
- this.stopPreferenceProfiles(profileDir);
991
- mkdirSync(profileDir, { recursive: true });
992
- const order = [...playwrightChannelOrder(preference, process.platform)];
1072
+ this.stopPreferenceProfiles(this.profileDirFor(preference));
993
1073
  let lastDetail = "";
994
1074
  for (const channel of order) {
995
- const kind = channel === "msedge" ? "edge" : "chrome";
996
- const resolved = resolveBrowserExecutable(kind);
997
- if (preference === "chrome" || preference === "edge") {
998
- if (resolved === null || resolved.kind !== preference) {
999
- lastDetail = `${preference} is not installed or not found on PATH`;
1000
- 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`;
1001
1082
  continue;
1002
1083
  }
1003
- } else if (resolved === null) {
1004
- lastDetail = `${kind} is not installed or not found on PATH`;
1005
- this.lastError = lastDetail;
1006
- continue;
1007
- }
1008
- try {
1009
- const context = await chromium.launchPersistentContext(profileDir, {
1010
- executablePath: resolved.executable,
1011
- headless: this.headless,
1012
- // Avoid Edge/Chrome infobar: "unsupported command-line flag: --no-sandbox".
1013
- chromiumSandbox: true,
1014
- ignoreDefaultArgs: ["--no-sandbox"],
1015
- viewport: this.headless ? { width: 1280, height: 800 } : null,
1016
- args: ["--no-first-run", "--no-default-browser-check", "--disable-default-apps"]
1017
- });
1018
1084
  this.context = context;
1019
1085
  this.channel = channel;
1020
1086
  this.launchedProfileDir = profileDir;
@@ -1035,19 +1101,72 @@ var PlaywrightDriver = class {
1035
1101
  this.lastError = lastDetail;
1036
1102
  }
1037
1103
  }
1038
- 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).` : "";
1039
1105
  throw new Error(
1040
1106
  `Playwright could not launch a persistent browser (tried ${order.join(", ")}): ${lastDetail}.${hint}`
1041
1107
  );
1042
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 = "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
+ }
1043
1162
  stopPreferenceProfiles(activeProfileDir) {
1044
1163
  stopAgentBrowserProcesses(activeProfileDir);
1045
1164
  if (this.launchedProfileDir !== null && this.launchedProfileDir !== activeProfileDir) {
1046
1165
  stopAgentBrowserProcesses(this.launchedProfileDir);
1047
1166
  }
1048
1167
  if (this.profileRoot !== void 0) {
1049
- for (const slot of ["auto", "chrome", "edge"]) {
1050
- const dir = browserAgentProfileDirFor(this.profileRoot, slot);
1168
+ for (const slot of BROWSER_AGENT_PROFILE_SLOTS) {
1169
+ const dir = browserAgentProfileSlotDir(this.profileRoot, slot);
1051
1170
  if (dir !== activeProfileDir) stopAgentBrowserProcesses(dir);
1052
1171
  }
1053
1172
  }
@@ -1321,8 +1440,8 @@ var PlaywrightDriver = class {
1321
1440
  }
1322
1441
  };
1323
1442
  function sleep(ms) {
1324
- return new Promise((resolve16) => {
1325
- setTimeout(resolve16, ms);
1443
+ return new Promise((resolve17) => {
1444
+ setTimeout(resolve17, ms);
1326
1445
  });
1327
1446
  }
1328
1447
  async function settlePage(page, quietMs = 800) {
@@ -1380,7 +1499,7 @@ async function listHttpAnchors(page) {
1380
1499
  // src/host/browser-agent/prompt.ts
1381
1500
  var SECTION_NAME = "agent-enhancer:browser-agent";
1382
1501
  var GUIDANCE = [
1383
- "## Browser agent (Desktop dedicated Chrome/Edge)",
1502
+ "## Browser agent (Desktop dedicated browser: Safari/Chrome on Mac, Chrome/Edge on Windows)",
1384
1503
  "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.",
1385
1504
  "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.",
1386
1505
  "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.",
@@ -1836,7 +1955,7 @@ function registerBrowserTools(ctx, options) {
1836
1955
  };
1837
1956
  disposers.push(ctx.tools.register(textTool(
1838
1957
  "browser_status",
1839
- "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.",
1958
+ "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.",
1840
1959
  {},
1841
1960
  async (_args, exec) => {
1842
1961
  guardEnabled();
@@ -2491,8 +2610,8 @@ function installBrowserAgent(ctx, options) {
2491
2610
  options.browserPreference()
2492
2611
  );
2493
2612
  const stopAllProfileSlots = () => {
2494
- for (const slot of ["auto", "chrome", "edge"]) {
2495
- stopAgentBrowserProcesses(browserAgentProfileDirFor(options.profileRoot, slot));
2613
+ for (const slot of BROWSER_AGENT_PROFILE_SLOTS) {
2614
+ stopAgentBrowserProcesses(browserAgentProfileSlotDir(options.profileRoot, slot));
2496
2615
  }
2497
2616
  };
2498
2617
  const enqueueSwitch = (work) => {
@@ -2535,8 +2654,10 @@ function installBrowserAgent(ctx, options) {
2535
2654
  if (activeDriver === null || mountedPreference !== preference) return false;
2536
2655
  const status = activeDriver.status();
2537
2656
  if (!status.ready) return true;
2538
- const want = playwrightChannelOrder(preference, process.platform)[0];
2539
- return status.endpoint === `playwright:${want}`;
2657
+ const endpoint = status.endpoint ?? "";
2658
+ if (!endpoint.startsWith("playwright:")) return false;
2659
+ const channel = endpoint.slice("playwright:".length);
2660
+ return playwrightChannelSatisfiesPreference(channel, preference, process.platform);
2540
2661
  };
2541
2662
  const createDriver = (_preference) => {
2542
2663
  mountedPreference = options.browserPreference();
@@ -2795,7 +2916,7 @@ var AuxiliaryError = class extends Error {
2795
2916
  // src/identity.ts
2796
2917
  var PACKAGE_NAME = "dsh-agent-enhancer";
2797
2918
  var PLUGIN_ID = "agent-enhancer";
2798
- var PACKAGE_VERSION = "0.3.9";
2919
+ var PACKAGE_VERSION = "0.3.11";
2799
2920
  var LEGACY_PACKAGE_NAME = "dsh-composer-enhancer";
2800
2921
  var ROLLBACK_PREFIX = `${PACKAGE_NAME}:rollback:`;
2801
2922
  var UNDO_PREFIX = `${PACKAGE_NAME}:undo:`;
@@ -5939,7 +6060,7 @@ var SessionCleanupRegistry = class {
5939
6060
 
5940
6061
  // src/host/session-delete/plugin-purge.ts
5941
6062
  import { createHash as createHash4 } from "node:crypto";
5942
- import { existsSync as existsSync2 } from "node:fs";
6063
+ import { existsSync as existsSync3 } from "node:fs";
5943
6064
  import { readdir as readdir3, readFile as readFile4, rm, unlink as unlink4 } from "node:fs/promises";
5944
6065
  import { join as join7 } from "node:path";
5945
6066
  function digest4(value) {
@@ -5949,7 +6070,7 @@ function shortDigest(value, length = 16) {
5949
6070
  return digest4(value).slice(0, length);
5950
6071
  }
5951
6072
  async function removeIfPresent4(path) {
5952
- if (!existsSync2(path)) return false;
6073
+ if (!existsSync3(path)) return false;
5953
6074
  await rm(path, { recursive: true, force: true });
5954
6075
  return true;
5955
6076
  }
@@ -6014,7 +6135,7 @@ function createContextExcludeCleaner(pluginDataRoot) {
6014
6135
 
6015
6136
  // src/host/session-delete/delete.ts
6016
6137
  import { createHash as createHash5 } from "node:crypto";
6017
- import { existsSync as existsSync3 } from "node:fs";
6138
+ import { existsSync as existsSync4 } from "node:fs";
6018
6139
  import { appendFile, mkdir as mkdir4, readdir as readdir4, rm as rm2 } from "node:fs/promises";
6019
6140
  import { homedir as homedir2, tmpdir } from "node:os";
6020
6141
  import { join as join8 } from "node:path";
@@ -6239,14 +6360,14 @@ async function forgetInRegistry(ctx, sessionId, options) {
6239
6360
  return removed;
6240
6361
  }
6241
6362
  async function removePathBestEffort(path) {
6242
- if (!existsSync3(path)) return false;
6363
+ if (!existsSync4(path)) return false;
6243
6364
  for (let attempt = 0; attempt < 3; attempt += 1) {
6244
6365
  try {
6245
6366
  await rm2(path, { recursive: true, force: true });
6246
6367
  return true;
6247
6368
  } catch {
6248
6369
  if (attempt === 2) return false;
6249
- await new Promise((resolve16) => setTimeout(resolve16, 120 * (attempt + 1)));
6370
+ await new Promise((resolve17) => setTimeout(resolve17, 120 * (attempt + 1)));
6250
6371
  }
6251
6372
  }
6252
6373
  return false;
@@ -6254,10 +6375,10 @@ async function removePathBestEffort(path) {
6254
6375
  async function eraseSessionLog(sessionId) {
6255
6376
  const removed = [];
6256
6377
  const root = sessionsRoot();
6257
- if (!existsSync3(root)) return removed;
6378
+ if (!existsSync4(root)) return removed;
6258
6379
  for (const workspaceDir of await readdir4(root)) {
6259
6380
  const target = join8(root, workspaceDir, sessionId);
6260
- if (!existsSync3(target)) continue;
6381
+ if (!existsSync4(target)) continue;
6261
6382
  const normalizedRoot = root.toLowerCase();
6262
6383
  if (!target.toLowerCase().startsWith(normalizedRoot)) continue;
6263
6384
  if (await removePathBestEffort(target)) removed.push(target);
@@ -6276,7 +6397,7 @@ async function eraseSpill(sessionId) {
6276
6397
  for (const entry of entries) {
6277
6398
  if (!SPILL_ROOT_RE.test(entry)) continue;
6278
6399
  const target = join8(spillBase(), entry, name2);
6279
- if (!existsSync3(target)) continue;
6400
+ if (!existsSync4(target)) continue;
6280
6401
  if (await removePathBestEffort(target)) removed.push(target);
6281
6402
  }
6282
6403
  return removed;
@@ -6304,7 +6425,7 @@ async function eraseProjcache(ctx, sessionId) {
6304
6425
  join8(projcacheSessionsDir(), `${sessionId}.json`),
6305
6426
  join8(projcacheSessionsDir(), `${uuid}.json`)
6306
6427
  ]) {
6307
- if (!existsSync3(cacheFile)) continue;
6428
+ if (!existsSync4(cacheFile)) continue;
6308
6429
  if (await removePathBestEffort(cacheFile)) removed.push(cacheFile);
6309
6430
  }
6310
6431
  return removed;
@@ -6374,35 +6495,20 @@ async function deleteSessionNow(options) {
6374
6495
  };
6375
6496
  }
6376
6497
 
6377
- // src/host/extra-folders/io.ts
6378
- import { promises as fsp } from "node:fs";
6379
- import { basename as basename4, join as join9, resolve as resolve3, sep as sep4 } from "node:path";
6380
-
6381
- // src/host/extra-folders/paths.ts
6382
- import { createHash as createHash6 } from "node:crypto";
6383
- import { isAbsolute as isAbsolute3, relative as relative2, resolve as resolve2, sep as sep3 } from "node:path";
6384
- function cwdStorageKey(primaryCwd) {
6385
- const normalized = resolve2(primaryCwd);
6386
- return createHash6("sha256").update(normalized).digest("hex").slice(0, 32);
6387
- }
6388
- function isInsideRoot(root, absolutePath2) {
6389
- const base = resolve2(root);
6390
- const target = resolve2(absolutePath2);
6391
- const rel = relative2(base, target);
6392
- return rel === "" || !rel.startsWith(`..${sep3}`) && rel !== ".." && !isAbsolute3(rel);
6393
- }
6394
- function assertInsideAllowedRoots(primaryCwd, extraRoots, absolutePath2) {
6395
- if (isInsideRoot(primaryCwd, absolutePath2)) return;
6396
- for (const root of extraRoots) {
6397
- if (isInsideRoot(root, absolutePath2)) return;
6398
- }
6399
- throw new Error("Path is outside the session workspace and attached folders");
6400
- }
6401
- function normalizeRootPath(path) {
6402
- const trimmed = path.trim();
6403
- if (trimmed === "") throw new Error("Path is empty");
6404
- return resolve2(trimmed);
6405
- }
6498
+ // src/host/web-chat-bridge/import-session.ts
6499
+ import { randomUUID as randomUUID6 } from "node:crypto";
6500
+ import { existsSync as existsSync5, statSync } from "node:fs";
6501
+ import { resolve as resolve2 } from "node:path";
6502
+ import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
6503
+ import {
6504
+ createAssistantMessage,
6505
+ createSystemMessage,
6506
+ createUserMessage
6507
+ } from "@deepseek-ai/dsh-llm";
6508
+ import {
6509
+ SessionId,
6510
+ SessionSeq as SessionSeq2
6511
+ } from "@deepseek-ai/dsh-session";
6406
6512
 
6407
6513
  // src/host/extra-folders/pick.ts
6408
6514
  import { execFile } from "node:child_process";
@@ -6424,6 +6530,16 @@ var ExtraFoldersError = class extends Error {
6424
6530
  // src/host/extra-folders/pick.ts
6425
6531
  var execFileAsync = promisify(execFile);
6426
6532
  var nodeRequire = createRequire(import.meta.url);
6533
+ function decodeWindowsPickerPathBase64(stdout) {
6534
+ const encoded = stdout.trim().replace(/\r?\n/g, "");
6535
+ if (encoded === "") return null;
6536
+ try {
6537
+ const path = Buffer.from(encoded, "base64").toString("utf8").trim();
6538
+ return path === "" ? null : path;
6539
+ } catch {
6540
+ return null;
6541
+ }
6542
+ }
6427
6543
  async function pickViaElectron() {
6428
6544
  try {
6429
6545
  const electron = nodeRequire("electron");
@@ -6450,7 +6566,8 @@ async function pickViaWindowsForms() {
6450
6566
  "$dialog.ShowNewFolderButton = $true",
6451
6567
  "$result = $dialog.ShowDialog()",
6452
6568
  "if ($result -eq [System.Windows.Forms.DialogResult]::OK) {",
6453
- " [Console]::Out.Write($dialog.SelectedPath)",
6569
+ " $bytes = [System.Text.Encoding]::UTF8.GetBytes($dialog.SelectedPath)",
6570
+ " [Console]::Out.Write([Convert]::ToBase64String($bytes))",
6454
6571
  "}"
6455
6572
  ].join("; ");
6456
6573
  try {
@@ -6459,8 +6576,7 @@ async function pickViaWindowsForms() {
6459
6576
  ["-NoProfile", "-STA", "-Command", script],
6460
6577
  { windowsHide: true, encoding: "utf8", timeout: 12e4 }
6461
6578
  );
6462
- const path = stdout.trim();
6463
- return path === "" ? null : path;
6579
+ return decodeWindowsPickerPathBase64(stdout);
6464
6580
  } catch {
6465
6581
  return void 0;
6466
6582
  }
@@ -6550,7 +6666,8 @@ async function pickFileViaWindowsForms(options) {
6550
6666
  "$dialog.Multiselect = $false",
6551
6667
  "$result = $dialog.ShowDialog()",
6552
6668
  "if ($result -eq [System.Windows.Forms.DialogResult]::OK) {",
6553
- " [Console]::Out.Write($dialog.FileName)",
6669
+ " $bytes = [System.Text.Encoding]::UTF8.GetBytes($dialog.FileName)",
6670
+ " [Console]::Out.Write([Convert]::ToBase64String($bytes))",
6554
6671
  "}"
6555
6672
  ].join("; ");
6556
6673
  try {
@@ -6559,8 +6676,7 @@ async function pickFileViaWindowsForms(options) {
6559
6676
  ["-NoProfile", "-STA", "-Command", script],
6560
6677
  { windowsHide: true, encoding: "utf8", timeout: 12e4 }
6561
6678
  );
6562
- const path = stdout.trim();
6563
- return path === "" ? null : path;
6679
+ return decodeWindowsPickerPathBase64(stdout);
6564
6680
  } catch {
6565
6681
  return void 0;
6566
6682
  }
@@ -6583,53 +6699,1147 @@ async function pickFileViaOsascript(options) {
6583
6699
  return void 0;
6584
6700
  }
6585
6701
  }
6586
- async function pickFileViaZenity(options) {
6587
- if (process.platform === "win32" || process.platform === "darwin") return void 0;
6588
- const args = ["--file-selection", `--title=${options.title ?? "Select file"}`];
6589
- for (const filter of options.filters ?? []) {
6590
- const patterns = filter.extensions.map((ext) => ext === "*" ? "*" : `*.${ext}`).join(" ");
6591
- args.push(`--file-filter=${filter.name} | ${patterns}`);
6702
+ async function pickFileViaZenity(options) {
6703
+ if (process.platform === "win32" || process.platform === "darwin") return void 0;
6704
+ const args = ["--file-selection", `--title=${options.title ?? "Select file"}`];
6705
+ for (const filter of options.filters ?? []) {
6706
+ const patterns = filter.extensions.map((ext) => ext === "*" ? "*" : `*.${ext}`).join(" ");
6707
+ args.push(`--file-filter=${filter.name} | ${patterns}`);
6708
+ }
6709
+ try {
6710
+ const { stdout } = await execFileAsync("zenity", args, {
6711
+ encoding: "utf8",
6712
+ timeout: 12e4
6713
+ });
6714
+ const path = stdout.trim();
6715
+ return path === "" ? null : path;
6716
+ } catch (error) {
6717
+ const code = error !== null && typeof error === "object" ? Reflect.get(error, "code") : void 0;
6718
+ if (code === 1) return null;
6719
+ return void 0;
6720
+ }
6721
+ }
6722
+ async function pickFileNow(signal, options = {}) {
6723
+ signal.throwIfAborted();
6724
+ const attempts = [
6725
+ () => pickFileViaElectron(options),
6726
+ () => pickFileViaWindowsForms(options),
6727
+ () => pickFileViaOsascript(options),
6728
+ () => pickFileViaZenity(options)
6729
+ ];
6730
+ for (const attempt of attempts) {
6731
+ signal.throwIfAborted();
6732
+ const path = await attempt();
6733
+ if (path !== void 0) return { path };
6734
+ }
6735
+ throw new ExtraFoldersError(
6736
+ "FILE_EDIT_FAILED",
6737
+ "No file picker is available in this environment"
6738
+ );
6739
+ }
6740
+
6741
+ // src/host/web-chat-bridge/limits.ts
6742
+ var WEB_CHAT_MAX_TEXT_BYTES = 5 * 1024 * 1024;
6743
+ var WEB_CHAT_MAX_MESSAGES = 5e3;
6744
+ var WEB_CHAT_MAX_EXPORT_CONVERSATIONS = 200;
6745
+
6746
+ // src/host/web-chat-bridge/import-session.ts
6747
+ var WebChatImportError = class extends Error {
6748
+ constructor(code, message, sessionId) {
6749
+ super(message);
6750
+ this.code = code;
6751
+ this.sessionId = sessionId;
6752
+ this.name = "WebChatImportError";
6753
+ }
6754
+ code;
6755
+ sessionId;
6756
+ };
6757
+ function webChatImportToRemoteError(error) {
6758
+ if (error instanceof WebChatImportError) {
6759
+ const details = {
6760
+ code: "FILE_EDIT_FAILED",
6761
+ webChatCode: error.code,
6762
+ ...error.sessionId === void 0 ? {} : { sessionId: error.sessionId }
6763
+ };
6764
+ return new RemoteError("agent-enhancer/failed", `${error.code}: ${error.message}`, details);
6765
+ }
6766
+ const detail = error instanceof Error ? error.message : String(error);
6767
+ return new RemoteError("agent-enhancer/failed", detail || "Web chat import failed", {
6768
+ code: "FILE_EDIT_FAILED",
6769
+ webChatCode: "import-failed"
6770
+ });
6771
+ }
6772
+ function serviceOf2(ctx, key) {
6773
+ try {
6774
+ return ctx.get(key);
6775
+ } catch {
6776
+ return void 0;
6777
+ }
6778
+ }
6779
+ function assertTranscript(transcript) {
6780
+ if (transcript.turns.length === 0) {
6781
+ throw new WebChatImportError("invalid-transcript", "Transcript has no turns");
6782
+ }
6783
+ if (transcript.turns.length > WEB_CHAT_MAX_MESSAGES) {
6784
+ throw new WebChatImportError(
6785
+ "invalid-transcript",
6786
+ `Exceeds message limit (${WEB_CHAT_MAX_MESSAGES})`
6787
+ );
6788
+ }
6789
+ let bytes = 0;
6790
+ for (const turn of transcript.turns) {
6791
+ bytes += Buffer.byteLength(turn.text, "utf8");
6792
+ if (bytes > WEB_CHAT_MAX_TEXT_BYTES) {
6793
+ throw new WebChatImportError(
6794
+ "invalid-transcript",
6795
+ `Exceeds text byte limit (${WEB_CHAT_MAX_TEXT_BYTES})`
6796
+ );
6797
+ }
6798
+ }
6799
+ }
6800
+ function importProvenancePrefix(transcript) {
6801
+ const partial = transcript.partial ? "yes" : "no";
6802
+ return `[Imported web chat \xB7 ${transcript.source.kind} \xB7 partial=${partial} \xB7 ${transcript.source.capturedAt}]
6803
+
6804
+ `;
6805
+ }
6806
+ var GENERIC_IMPORT_TITLE = /^(deepseek|shared conversation|imported chat|chat|untitled|未命名)$/i;
6807
+ function resolveWebChatImportTitle(transcript) {
6808
+ const raw = transcript.title.trim();
6809
+ if (raw !== "" && !GENERIC_IMPORT_TITLE.test(raw)) {
6810
+ return raw.length <= 80 ? raw : `${raw.slice(0, 79)}\u2026`;
6811
+ }
6812
+ const firstUser = transcript.turns.find((turn) => turn.role === "user");
6813
+ if (firstUser !== void 0) {
6814
+ const text3 = firstUser.text.trim().replace(/\s+/g, " ");
6815
+ if (text3 !== "") {
6816
+ return text3.length <= 40 ? text3 : `${text3.slice(0, 39)}\u2026`;
6817
+ }
6818
+ }
6819
+ if (raw !== "") return raw;
6820
+ return "Imported chat";
6821
+ }
6822
+ function closeOpenTurn(session, turn) {
6823
+ session.append("turn/end", { turn, reason: { kind: "completed" } });
6824
+ }
6825
+ function appendUserMessage(session, text3) {
6826
+ const message = createUserMessage({
6827
+ content: [{ type: "text", text: text3 }],
6828
+ source: { kind: "user" }
6829
+ });
6830
+ return session.append("user/message", message, { surfaceOp: "append" });
6831
+ }
6832
+ function appendSessionTitle(session, title, firstUserMessageSeq) {
6833
+ const trimmed = title.trim();
6834
+ if (trimmed === "") return;
6835
+ session.append("session/title", {
6836
+ title: trimmed,
6837
+ messageSeqs: firstUserMessageSeq === void 0 ? [] : [SessionSeq2(firstUserMessageSeq)],
6838
+ source: { kind: "fallback" }
6839
+ });
6840
+ }
6841
+ function appendAssistantMessage(session, turn, step, text3) {
6842
+ session.append("step/start", { turn, step });
6843
+ const message = createAssistantMessage({
6844
+ content: [{ type: "text", text: text3 }],
6845
+ source: { provider: "web-chat-bridge", model: "imported-history" }
6846
+ });
6847
+ session.append("assistant/message", {
6848
+ turn,
6849
+ step,
6850
+ message,
6851
+ stream: []
6852
+ }, { surfaceOp: "append" });
6853
+ session.append("step/end", { turn, step });
6854
+ }
6855
+ function appendProtectedSystemHead(session, turn, step) {
6856
+ session.append("step/start", { turn, step });
6857
+ session.append("system/message", {
6858
+ turn,
6859
+ step,
6860
+ message: createSystemMessage("")
6861
+ }, { surfaceOp: "append" });
6862
+ session.append("step/end", { turn, step });
6863
+ }
6864
+ function appendTranscript(session, transcript) {
6865
+ const provenance = importProvenancePrefix(transcript);
6866
+ const turns = transcript.turns;
6867
+ let turn = 1;
6868
+ let step = 1;
6869
+ let openTurn = true;
6870
+ let awaitingAssistant = false;
6871
+ let firstUser = true;
6872
+ let firstUserMessageSeq;
6873
+ session.append("turn/start", { turn });
6874
+ appendProtectedSystemHead(session, turn, step);
6875
+ for (let index = 0; index < turns.length; index += 1) {
6876
+ const chatTurn = turns[index];
6877
+ const nextRole = turns[index + 1]?.role;
6878
+ if (chatTurn.role === "user") {
6879
+ if (awaitingAssistant) {
6880
+ closeOpenTurn(session, turn);
6881
+ awaitingAssistant = false;
6882
+ openTurn = false;
6883
+ step = 0;
6884
+ }
6885
+ if (!openTurn) {
6886
+ turn += 1;
6887
+ step = 0;
6888
+ session.append("turn/start", { turn });
6889
+ openTurn = true;
6890
+ }
6891
+ const body = firstUser ? `${provenance}${chatTurn.text}` : chatTurn.text;
6892
+ const userEvent = appendUserMessage(session, body);
6893
+ if (firstUser && userEvent !== null && typeof userEvent === "object") {
6894
+ const seq = Number(Reflect.get(userEvent, "seq"));
6895
+ if (Number.isFinite(seq)) firstUserMessageSeq = seq;
6896
+ }
6897
+ awaitingAssistant = true;
6898
+ firstUser = false;
6899
+ continue;
6900
+ }
6901
+ if (chatTurn.role === "assistant") {
6902
+ if (!openTurn) {
6903
+ turn += 1;
6904
+ step = 0;
6905
+ session.append("turn/start", { turn });
6906
+ openTurn = true;
6907
+ awaitingAssistant = false;
6908
+ }
6909
+ step += 1;
6910
+ appendAssistantMessage(session, turn, step, chatTurn.text);
6911
+ awaitingAssistant = false;
6912
+ if (nextRole !== "assistant") {
6913
+ closeOpenTurn(session, turn);
6914
+ openTurn = false;
6915
+ step = 0;
6916
+ }
6917
+ }
6918
+ }
6919
+ if (openTurn) closeOpenTurn(session, turn);
6920
+ appendSessionTitle(session, resolveWebChatImportTitle(transcript), firstUserMessageSeq);
6921
+ }
6922
+ function buildWebChatImportSeed(transcript) {
6923
+ const events = [];
6924
+ const recorder = {
6925
+ append(type, data, intent) {
6926
+ const event = {
6927
+ type,
6928
+ seq: SessionSeq2(events.length),
6929
+ time: Date.now(),
6930
+ data,
6931
+ ...intent?.surfaceOp === void 0 ? {} : { surfaceOp: intent.surfaceOp }
6932
+ };
6933
+ events.push(event);
6934
+ return event;
6935
+ }
6936
+ };
6937
+ appendTranscript(recorder, transcript);
6938
+ return events;
6939
+ }
6940
+ function onceDispose(dispose) {
6941
+ let settled = false;
6942
+ return async () => {
6943
+ if (settled) return true;
6944
+ if (dispose === void 0) return false;
6945
+ settled = true;
6946
+ try {
6947
+ await dispose();
6948
+ return true;
6949
+ } catch {
6950
+ return false;
6951
+ }
6952
+ };
6953
+ }
6954
+ function errorDetail(error) {
6955
+ return error instanceof Error ? error.message : String(error);
6956
+ }
6957
+ async function openAgentWorkSession(input, cwd) {
6958
+ const agents = input.agents;
6959
+ if (typeof agents.createSession === "function") {
6960
+ let created;
6961
+ try {
6962
+ created = await agents.createSession({
6963
+ cwd,
6964
+ reusable: () => false
6965
+ });
6966
+ } catch (error) {
6967
+ throw new WebChatImportError("import-failed", `Agent create failed: ${errorDetail(error)}`);
6968
+ }
6969
+ const session2 = created.agent?.session;
6970
+ if (session2 === void 0) {
6971
+ throw new WebChatImportError("import-failed", "Agent create did not return a session");
6972
+ }
6973
+ const dispose = onceDispose(created.dispose?.bind(created));
6974
+ try {
6975
+ appendTranscript(session2, input.transcript);
6976
+ } catch (error) {
6977
+ const disposed = await dispose();
6978
+ throw new WebChatImportError(
6979
+ "import-failed",
6980
+ errorDetail(error),
6981
+ disposed ? void 0 : session2.id
6982
+ );
6983
+ }
6984
+ return { session: session2, dispose };
6985
+ }
6986
+ if (typeof agents.create !== "function") {
6987
+ throw new WebChatImportError("import-failed", "Agent registry is unavailable");
6988
+ }
6989
+ const sessionId = SessionId(`session-${randomUUID6()}`);
6990
+ const seed = buildWebChatImportSeed(input.transcript);
6991
+ let handle;
6992
+ try {
6993
+ handle = await agents.create({
6994
+ sessionId,
6995
+ seed,
6996
+ meta: { cwd },
6997
+ ...input.agentOptions === void 0 ? {} : { agentOptions: input.agentOptions }
6998
+ });
6999
+ } catch (error) {
7000
+ throw new WebChatImportError("import-failed", `Agent create failed: ${errorDetail(error)}`);
7001
+ }
7002
+ const session = handle.agent?.session;
7003
+ if (session === void 0) {
7004
+ throw new WebChatImportError("import-failed", "Agent create did not return a session", sessionId);
7005
+ }
7006
+ return { session, dispose: onceDispose(() => handle.dispose()) };
7007
+ }
7008
+ async function importWebChatHistoryNow(input) {
7009
+ assertTranscript(input.transcript);
7010
+ const cwd = resolve2(input.cwd);
7011
+ const opened = await openAgentWorkSession(input, cwd);
7012
+ try {
7013
+ const flushed = await input.sessions.flush(opened.session);
7014
+ if (flushed !== true) {
7015
+ const disposed = await opened.dispose();
7016
+ throw new WebChatImportError(
7017
+ "import-failed",
7018
+ "Session flush did not persist",
7019
+ disposed ? void 0 : opened.session.id
7020
+ );
7021
+ }
7022
+ if (input.attachToWorkspace !== void 0) {
7023
+ try {
7024
+ await input.attachToWorkspace(opened.session.id);
7025
+ } catch (error) {
7026
+ const disposed = await opened.dispose();
7027
+ const detail = errorDetail(error);
7028
+ throw new WebChatImportError(
7029
+ "import-failed",
7030
+ disposed ? `Workspace attach failed: ${detail}` : `Workspace attach failed: ${detail}; dispose session ${opened.session.id} manually`,
7031
+ disposed ? void 0 : opened.session.id
7032
+ );
7033
+ }
7034
+ }
7035
+ } catch (error) {
7036
+ if (error instanceof WebChatImportError) throw error;
7037
+ const disposed = await opened.dispose();
7038
+ throw new WebChatImportError(
7039
+ "import-failed",
7040
+ errorDetail(error),
7041
+ disposed ? void 0 : opened.session.id
7042
+ );
7043
+ }
7044
+ return { sessionId: opened.session.id };
7045
+ }
7046
+ function workspaceRegistryOf2(ctx) {
7047
+ const registry = serviceOf2(ctx, "workspaceRegistry");
7048
+ if (registry === void 0 || typeof registry.list !== "function") return void 0;
7049
+ return registry;
7050
+ }
7051
+ function workspacesFromStorage(ctx) {
7052
+ const facility = serviceOf2(ctx, "storageDomain");
7053
+ const domain = facility?.get?.("workspace");
7054
+ const table = domain?.table?.("workspaces");
7055
+ if (table === void 0) return [];
7056
+ const rows = [];
7057
+ for (const [id, record2] of table.entries()) {
7058
+ const cwd = record2?.path ?? record2?.cwd;
7059
+ if (typeof cwd !== "string" || cwd.trim() === "") continue;
7060
+ rows.push({
7061
+ id,
7062
+ title: record2.title?.trim() || id,
7063
+ cwd: resolve2(cwd)
7064
+ });
7065
+ }
7066
+ return rows;
7067
+ }
7068
+ function listWebChatWorkspacesNow(ctx) {
7069
+ const registry = workspaceRegistryOf2(ctx);
7070
+ if (registry !== void 0) {
7071
+ const rows = [];
7072
+ for (const workspace of registry.list()) {
7073
+ const cwd = workspace.path;
7074
+ if (typeof cwd !== "string" || cwd.trim() === "") continue;
7075
+ rows.push({
7076
+ id: workspace.id,
7077
+ title: workspace.title?.trim() || workspace.id,
7078
+ cwd: resolve2(cwd)
7079
+ });
7080
+ }
7081
+ if (rows.length > 0) return rows;
7082
+ }
7083
+ return workspacesFromStorage(ctx);
7084
+ }
7085
+ async function createWebChatWorkspaceNow(ctx, signal) {
7086
+ signal.throwIfAborted();
7087
+ const picked = await pickDirectoryNow(signal);
7088
+ if (picked.path === null) {
7089
+ return { cancelled: true, workspace: null };
7090
+ }
7091
+ signal.throwIfAborted();
7092
+ const absolute = resolve2(picked.path);
7093
+ try {
7094
+ if (!existsSync5(absolute) || !statSync(absolute).isDirectory()) {
7095
+ throw new WebChatImportError(
7096
+ "import-failed",
7097
+ `Selected folder does not exist: ${absolute}`
7098
+ );
7099
+ }
7100
+ } catch (error) {
7101
+ if (error instanceof WebChatImportError) throw error;
7102
+ throw new WebChatImportError(
7103
+ "import-failed",
7104
+ `Selected folder is not readable: ${absolute}`
7105
+ );
7106
+ }
7107
+ const registry = workspaceRegistryOf2(ctx);
7108
+ if (registry?.create === void 0) {
7109
+ throw new WebChatImportError("import-failed", "Workspace registry cannot create workspaces");
7110
+ }
7111
+ let created;
7112
+ try {
7113
+ created = await registry.create(absolute);
7114
+ } catch (error) {
7115
+ const detail = error instanceof Error ? error.message : String(error);
7116
+ const existing = listWebChatWorkspacesNow(ctx).find((row) => {
7117
+ try {
7118
+ return resolve2(row.cwd) === absolute;
7119
+ } catch {
7120
+ return false;
7121
+ }
7122
+ });
7123
+ if (existing !== void 0) {
7124
+ return { cancelled: false, workspace: existing };
7125
+ }
7126
+ throw new WebChatImportError("import-failed", detail || "Failed to create workspace");
7127
+ }
7128
+ const cwd = typeof created.path === "string" && created.path.trim() !== "" ? resolve2(created.path) : absolute;
7129
+ return {
7130
+ cancelled: false,
7131
+ workspace: {
7132
+ id: created.id,
7133
+ title: created.title?.trim() || created.id,
7134
+ cwd
7135
+ }
7136
+ };
7137
+ }
7138
+ function resolveWorkspace(ctx, workspaceId) {
7139
+ const registry = workspaceRegistryOf2(ctx);
7140
+ if (registry?.get !== void 0) {
7141
+ const workspace = registry.get(workspaceId);
7142
+ if (workspace !== void 0) {
7143
+ const cwd = workspace.path;
7144
+ if (typeof cwd === "string" && cwd.trim() !== "") {
7145
+ return {
7146
+ id: workspace.id,
7147
+ title: workspace.title?.trim() || workspace.id,
7148
+ cwd: resolve2(cwd)
7149
+ };
7150
+ }
7151
+ }
7152
+ }
7153
+ const fromList = listWebChatWorkspacesNow(ctx).find((row) => row.id === workspaceId);
7154
+ if (fromList !== void 0) return fromList;
7155
+ throw new WebChatImportError("no-workspace", `Workspace "${workspaceId}" was not found`);
7156
+ }
7157
+ async function attachToWorkspaceRegistry(ctx, workspaceId, sessionId) {
7158
+ const registry = workspaceRegistryOf2(ctx);
7159
+ const workspace = registry?.get?.(workspaceId);
7160
+ if (workspace?.attachSession !== void 0) {
7161
+ await workspace.attachSession(sessionId);
7162
+ return;
7163
+ }
7164
+ const facility = serviceOf2(ctx, "storageDomain");
7165
+ const domain = facility?.get?.("workspace");
7166
+ const table = domain?.table?.("workspaces");
7167
+ if (table === void 0) {
7168
+ throw new WebChatImportError("import-failed", "Workspace registry is unavailable for attach");
7169
+ }
7170
+ await table.update(workspaceId, (current) => {
7171
+ const row = current;
7172
+ const sessionIds = Array.isArray(row.sessionIds) ? row.sessionIds : [];
7173
+ if (sessionIds.includes(sessionId)) return row;
7174
+ return {
7175
+ ...row,
7176
+ sessionIds: [...sessionIds, sessionId],
7177
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7178
+ };
7179
+ });
7180
+ }
7181
+ function agentOptionsOf(ctx) {
7182
+ const defaults = serviceOf2(ctx, "agentDefaultModel");
7183
+ if (typeof defaults?.currentSelection !== "function") return void 0;
7184
+ const current = defaults.currentSelection.bind(defaults);
7185
+ return {
7186
+ get provider() {
7187
+ return current().provider;
7188
+ },
7189
+ get model() {
7190
+ return current().model;
7191
+ },
7192
+ get reasoningEffort() {
7193
+ return current().reasoningEffort;
7194
+ }
7195
+ };
7196
+ }
7197
+ async function importWebChatHistoryWithContext(ctx, request) {
7198
+ const workspace = resolveWorkspace(ctx, request.workspaceId);
7199
+ const sessions = serviceOf2(ctx, "sessions");
7200
+ const agents = serviceOf2(ctx, "agents");
7201
+ if (sessions === void 0 || typeof sessions.flush !== "function") {
7202
+ throw new WebChatImportError("import-failed", "Session store is unavailable");
7203
+ }
7204
+ if (agents === void 0 || typeof agents.createSession !== "function" && typeof agents.create !== "function") {
7205
+ throw new WebChatImportError("import-failed", "Agent registry is unavailable");
7206
+ }
7207
+ const agentOptions = agentOptionsOf(ctx);
7208
+ return importWebChatHistoryNow({
7209
+ sessions: { flush: (session) => sessions.flush(session) },
7210
+ agents,
7211
+ ...agentOptions === void 0 ? {} : { agentOptions },
7212
+ workspaceId: workspace.id,
7213
+ cwd: workspace.cwd,
7214
+ transcript: request.transcript,
7215
+ attachToWorkspace: (sessionId) => attachToWorkspaceRegistry(ctx, workspace.id, sessionId)
7216
+ });
7217
+ }
7218
+
7219
+ // src/host/web-chat-bridge/parse-export.ts
7220
+ import { inflateRawSync } from "node:zlib";
7221
+ var SECTION_HEADER = /^##\s*(User|Assistant|用户|助手)\s*$/gim;
7222
+ var MARKDOWN_CHAT_SPLIT = /^#\s+(.+)$/gm;
7223
+ function assertPayloadSize(bytes) {
7224
+ if (bytes.length > WEB_CHAT_MAX_TEXT_BYTES) {
7225
+ throw new Error(`Export too large: exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
7226
+ }
7227
+ }
7228
+ function assertTurnCount(turns) {
7229
+ if (turns.length === 0) {
7230
+ throw new Error("No messages found in export");
7231
+ }
7232
+ if (turns.length > WEB_CHAT_MAX_MESSAGES) {
7233
+ throw new Error(`Exceeds message limit (${WEB_CHAT_MAX_MESSAGES})`);
7234
+ }
7235
+ }
7236
+ function normalizeRole(raw) {
7237
+ const key = raw.trim().toLowerCase();
7238
+ if (key === "user" || key === "\u7528\u6237") return "user";
7239
+ if (key === "assistant" || key === "\u52A9\u624B") return "assistant";
7240
+ return null;
7241
+ }
7242
+ function extractTitleFromMarkdown(text3) {
7243
+ const match = text3.match(/^#\s+(.+)$/m);
7244
+ if (match?.[1]) return match[1].trim();
7245
+ const firstLine = text3.split(/\r?\n/).find((line) => line.trim() !== "");
7246
+ return firstLine?.trim() ?? "Imported chat";
7247
+ }
7248
+ function parseMarkdownTurns(text3) {
7249
+ const turns = [];
7250
+ const matches = [...text3.matchAll(SECTION_HEADER)];
7251
+ if (matches.length === 0) return turns;
7252
+ for (let i = 0; i < matches.length; i++) {
7253
+ const match = matches[i];
7254
+ const role = normalizeRole(match[1]);
7255
+ if (!role) continue;
7256
+ const start = match.index + match[0].length;
7257
+ const end = i + 1 < matches.length ? matches[i + 1].index : text3.length;
7258
+ const body = text3.slice(start, end).trim();
7259
+ if (body) turns.push({ role, text: body });
7260
+ }
7261
+ return turns;
7262
+ }
7263
+ function messageText(content) {
7264
+ if (typeof content === "string") return content.trim();
7265
+ if (Array.isArray(content)) {
7266
+ return content.map((part) => {
7267
+ if (typeof part === "string") return part;
7268
+ if (part && typeof part === "object" && "text" in part && typeof part.text === "string") {
7269
+ return part.text;
7270
+ }
7271
+ return "";
7272
+ }).filter(Boolean).join("\n").trim();
7273
+ }
7274
+ return "";
7275
+ }
7276
+ function normalizeJsonRole(raw) {
7277
+ if (typeof raw !== "string") return null;
7278
+ const key = raw.trim().toLowerCase();
7279
+ if (key === "user" || key === "human") return "user";
7280
+ if (key === "assistant" || key === "model" || key === "ai") return "assistant";
7281
+ return null;
7282
+ }
7283
+ function turnsFromMessageRows(rows) {
7284
+ const turns = [];
7285
+ for (const row of rows) {
7286
+ if (!row || typeof row !== "object") continue;
7287
+ const item = row;
7288
+ const role = normalizeJsonRole(item.role ?? item.author ?? item.speaker);
7289
+ if (!role) continue;
7290
+ const text3 = messageText(item.content ?? item.text ?? item.message);
7291
+ if (text3) turns.push({ role, text: text3 });
7292
+ }
7293
+ return turns;
7294
+ }
7295
+ function titleOfObject(obj, fallback) {
7296
+ if (typeof obj.title === "string" && obj.title.trim()) return obj.title.trim();
7297
+ if (typeof obj.name === "string" && obj.name.trim()) return obj.name.trim();
7298
+ if (typeof obj.chat_title === "string" && obj.chat_title.trim()) return obj.chat_title.trim();
7299
+ return fallback;
7300
+ }
7301
+ function conversationFromObject(value, fallbackTitle) {
7302
+ if (Array.isArray(value)) {
7303
+ const turns2 = turnsFromMessageRows(value);
7304
+ return turns2.length > 0 ? { title: fallbackTitle, turns: turns2 } : null;
7305
+ }
7306
+ if (!value || typeof value !== "object") return null;
7307
+ const obj = value;
7308
+ const title = titleOfObject(obj, fallbackTitle);
7309
+ let rows = [];
7310
+ if (Array.isArray(obj.messages)) rows = obj.messages;
7311
+ else if (Array.isArray(obj.conversation)) rows = obj.conversation;
7312
+ else if (Array.isArray(obj.turns)) rows = obj.turns;
7313
+ else if (Array.isArray(obj.chat_messages)) rows = obj.chat_messages;
7314
+ const turns = turnsFromMessageRows(rows);
7315
+ return turns.length > 0 ? { title, turns } : null;
7316
+ }
7317
+ function conversationsFromJsonValue(value, fallbackTitle) {
7318
+ if (Array.isArray(value)) {
7319
+ const asMessages = turnsFromMessageRows(value);
7320
+ if (asMessages.length > 0 && value.every((row) => {
7321
+ if (!row || typeof row !== "object") return false;
7322
+ const item = row;
7323
+ return normalizeJsonRole(item.role ?? item.author ?? item.speaker) !== null;
7324
+ })) {
7325
+ return [{ title: fallbackTitle, turns: asMessages }];
7326
+ }
7327
+ const out = [];
7328
+ for (let i = 0; i < value.length; i++) {
7329
+ const parsed = conversationFromObject(value[i], `${fallbackTitle} ${i + 1}`);
7330
+ if (parsed) out.push(parsed);
7331
+ }
7332
+ return out;
7333
+ }
7334
+ if (!value || typeof value !== "object") return [];
7335
+ const obj = value;
7336
+ const listKeys = ["chats", "conversations", "chat_sessions", "sessions", "history"];
7337
+ for (const key of listKeys) {
7338
+ const list = obj[key];
7339
+ if (!Array.isArray(list) || list.length === 0) continue;
7340
+ const out = [];
7341
+ for (let i = 0; i < list.length; i++) {
7342
+ const parsed = conversationFromObject(list[i], `${fallbackTitle} ${i + 1}`);
7343
+ if (parsed) out.push(parsed);
7344
+ }
7345
+ if (out.length > 0) return out;
7346
+ }
7347
+ const single = conversationFromObject(obj, fallbackTitle);
7348
+ return single ? [single] : [];
7349
+ }
7350
+ function splitMarkdownConversations(text3) {
7351
+ const matches = [...text3.matchAll(MARKDOWN_CHAT_SPLIT)];
7352
+ if (matches.length <= 1) {
7353
+ return [{ title: extractTitleFromMarkdown(text3), body: text3 }];
7354
+ }
7355
+ const out = [];
7356
+ for (let i = 0; i < matches.length; i++) {
7357
+ const match = matches[i];
7358
+ const title = match[1].trim() || `Chat ${i + 1}`;
7359
+ const start = match.index;
7360
+ const end = i + 1 < matches.length ? matches[i + 1].index : text3.length;
7361
+ const body = text3.slice(start, end).trim();
7362
+ if (body) out.push({ title, body });
7363
+ }
7364
+ return out;
7365
+ }
7366
+ function parseTextConversations(text3, filename) {
7367
+ const chunks = splitMarkdownConversations(text3);
7368
+ const out = [];
7369
+ for (const chunk of chunks) {
7370
+ const turns = parseMarkdownTurns(chunk.body);
7371
+ if (turns.length > 0) {
7372
+ out.push({ title: chunk.title, turns });
7373
+ continue;
7374
+ }
7375
+ }
7376
+ if (out.length > 0) return out;
7377
+ const trimmed = text3.trim();
7378
+ if (trimmed && filename.toLowerCase().endsWith(".txt")) {
7379
+ return [{ title: extractTitleFromMarkdown(text3), turns: [{ role: "user", text: trimmed }] }];
7380
+ }
7381
+ return [];
7382
+ }
7383
+ function isZipArchive(bytes) {
7384
+ return bytes.length >= 4 && bytes[0] === 80 && bytes[1] === 75;
7385
+ }
7386
+ function zipEntryPriority(name2) {
7387
+ const lower = name2.toLowerCase();
7388
+ if (lower.endsWith(".md")) return 0;
7389
+ if (lower.endsWith(".json")) return 1;
7390
+ if (lower.endsWith(".txt")) return 2;
7391
+ return 9;
7392
+ }
7393
+ function decompressZipEntry(method, compressed, uncompressedSize) {
7394
+ if (uncompressedSize > WEB_CHAT_MAX_TEXT_BYTES) {
7395
+ throw new Error(`Export too large: exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
7396
+ }
7397
+ if (method === 0) {
7398
+ if (compressed.length > WEB_CHAT_MAX_TEXT_BYTES) {
7399
+ throw new Error(`Export too large: exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
7400
+ }
7401
+ return compressed;
7402
+ }
7403
+ if (method === 8) {
7404
+ return inflateRawSync(compressed, { maxOutputLength: WEB_CHAT_MAX_TEXT_BYTES + 1 });
7405
+ }
7406
+ throw new Error("unrecognized-export: unsupported zip compression");
7407
+ }
7408
+ function listZipEntryDescriptors(bytes) {
7409
+ const entries = [];
7410
+ let offset = 0;
7411
+ while (offset + 30 <= bytes.length) {
7412
+ if (bytes.readUInt32LE(offset) !== 67324752) break;
7413
+ const method = bytes.readUInt16LE(offset + 8);
7414
+ const compressedSize = bytes.readUInt32LE(offset + 18);
7415
+ const uncompressedSize = bytes.readUInt32LE(offset + 22);
7416
+ const nameLength = bytes.readUInt16LE(offset + 26);
7417
+ const extraLength = bytes.readUInt16LE(offset + 28);
7418
+ const headerSize = 30 + nameLength + extraLength;
7419
+ const nameStart = offset + 30;
7420
+ const nameEnd = nameStart + nameLength;
7421
+ if (nameEnd > bytes.length) break;
7422
+ const name2 = bytes.toString("utf8", nameStart, nameEnd);
7423
+ const dataStart = offset + headerSize;
7424
+ const dataEnd = dataStart + compressedSize;
7425
+ if (dataEnd > bytes.length) break;
7426
+ if (method === 0 || method === 8) {
7427
+ entries.push({
7428
+ name: name2,
7429
+ method,
7430
+ compressedSize,
7431
+ uncompressedSize,
7432
+ dataOffset: dataStart
7433
+ });
7434
+ }
7435
+ offset = dataEnd;
7436
+ }
7437
+ return entries;
7438
+ }
7439
+ function readZipEntryPayload(bytes, descriptor) {
7440
+ const compressed = bytes.subarray(
7441
+ descriptor.dataOffset,
7442
+ descriptor.dataOffset + descriptor.compressedSize
7443
+ );
7444
+ return decompressZipEntry(descriptor.method, compressed, descriptor.uncompressedSize);
7445
+ }
7446
+ function buildTranscript(filename, title, turns) {
7447
+ assertTurnCount(turns);
7448
+ return {
7449
+ title: title || "Imported chat",
7450
+ turns,
7451
+ partial: false,
7452
+ source: {
7453
+ kind: "official-export",
7454
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
7455
+ filename
7456
+ }
7457
+ };
7458
+ }
7459
+ function previewOfTurns(turns) {
7460
+ const firstUser = turns.find((turn) => turn.role === "user") ?? turns[0];
7461
+ if (firstUser === void 0) return "";
7462
+ const text3 = firstUser.text.trim();
7463
+ return text3.length <= 160 ? text3 : `${text3.slice(0, 159)}\u2026`;
7464
+ }
7465
+ function toCatalogItems(filename, conversations) {
7466
+ const items = [];
7467
+ for (let i = 0; i < conversations.length && items.length < WEB_CHAT_MAX_EXPORT_CONVERSATIONS; i++) {
7468
+ const conversation = conversations[i];
7469
+ try {
7470
+ const transcript = buildTranscript(filename, conversation.title, conversation.turns);
7471
+ items.push({
7472
+ id: `chat-${i + 1}`,
7473
+ title: transcript.title,
7474
+ turnCount: transcript.turns.length,
7475
+ preview: previewOfTurns(transcript.turns),
7476
+ transcript
7477
+ });
7478
+ } catch {
7479
+ }
7480
+ }
7481
+ return items;
7482
+ }
7483
+ function conversationsFromBytes(filename, bytes) {
7484
+ const lowerName = filename.toLowerCase();
7485
+ if (isZipArchive(bytes) || lowerName.endsWith(".zip")) {
7486
+ const descriptors = listZipEntryDescriptors(bytes).filter((entry) => !entry.name.endsWith("/") && zipEntryPriority(entry.name) < 9).sort((a, b) => zipEntryPriority(a.name) - zipEntryPriority(b.name) || a.name.localeCompare(b.name));
7487
+ if (descriptors.length === 0) {
7488
+ throw new Error("unrecognized-export: no parseable file in zip");
7489
+ }
7490
+ const jsonEntries = descriptors.filter((entry) => entry.name.toLowerCase().endsWith(".json"));
7491
+ for (const entry of jsonEntries) {
7492
+ const payload = readZipEntryPayload(bytes, entry);
7493
+ assertPayloadSize(payload);
7494
+ const nestedName = entry.name.split(/[/\\]/).pop() ?? entry.name;
7495
+ let parsed;
7496
+ try {
7497
+ parsed = JSON.parse(payload.toString("utf8"));
7498
+ } catch {
7499
+ continue;
7500
+ }
7501
+ const conversations = conversationsFromJsonValue(parsed, extractTitleFromMarkdown(nestedName));
7502
+ if (conversations.length > 1) return conversations;
7503
+ }
7504
+ const out = [];
7505
+ for (const entry of descriptors) {
7506
+ if (out.length >= WEB_CHAT_MAX_EXPORT_CONVERSATIONS) break;
7507
+ try {
7508
+ const payload = readZipEntryPayload(bytes, entry);
7509
+ assertPayloadSize(payload);
7510
+ const nestedName = entry.name.split(/[/\\]/).pop() ?? entry.name;
7511
+ out.push(...conversationsFromBytes(nestedName, payload));
7512
+ } catch {
7513
+ }
7514
+ }
7515
+ return out;
7516
+ }
7517
+ if (lowerName.endsWith(".json") || bytes[0] === 123 || bytes[0] === 91) {
7518
+ const text3 = bytes.toString("utf8");
7519
+ let parsed;
7520
+ try {
7521
+ parsed = JSON.parse(text3);
7522
+ } catch {
7523
+ throw new Error("unrecognized-export: invalid json");
7524
+ }
7525
+ return conversationsFromJsonValue(parsed, extractTitleFromMarkdown(filename));
7526
+ }
7527
+ if (lowerName.endsWith(".md") || lowerName.endsWith(".txt")) {
7528
+ return parseTextConversations(bytes.toString("utf8"), filename);
7529
+ }
7530
+ throw new Error("unrecognized-export: unsupported file type");
7531
+ }
7532
+ function analyzeWebChatExport(input) {
7533
+ assertPayloadSize(input.bytes);
7534
+ const conversations = conversationsFromBytes(input.filename, input.bytes);
7535
+ const items = toCatalogItems(input.filename, conversations);
7536
+ if (items.length === 0) {
7537
+ throw new Error("No messages found in export");
7538
+ }
7539
+ return {
7540
+ items,
7541
+ truncated: conversations.length > items.length
7542
+ };
7543
+ }
7544
+
7545
+ // src/host/web-chat-bridge/share-link.ts
7546
+ var SHARE_URL_RE = /(?:https?:\/\/chat\.deepseek\.com)?\/share\/([A-Za-z0-9_-]+)/i;
7547
+ var SHARE_ID_RE = /^[A-Za-z0-9_-]{6,}$/;
7548
+ function extractWebChatShareId(raw) {
7549
+ const trimmed = raw.trim();
7550
+ if (trimmed === "") return null;
7551
+ const fromUrl = trimmed.match(SHARE_URL_RE);
7552
+ if (fromUrl?.[1]) return fromUrl[1];
7553
+ if (SHARE_ID_RE.test(trimmed)) return trimmed;
7554
+ return null;
7555
+ }
7556
+ function webChatSharePageUrl(shareId) {
7557
+ return `https://chat.deepseek.com/share/${shareId}`;
7558
+ }
7559
+ function webChatShareContentApiUrl(shareId) {
7560
+ return `https://chat.deepseek.com/api/v0/share/content?share_id=${encodeURIComponent(shareId)}`;
7561
+ }
7562
+ function normalizeRole2(raw) {
7563
+ if (typeof raw !== "string") return null;
7564
+ const key = raw.trim().toLowerCase();
7565
+ if (key === "user" || key === "human") return "user";
7566
+ if (key === "assistant" || key === "ai" || key === "model") return "assistant";
7567
+ return null;
7568
+ }
7569
+ function messageText2(raw) {
7570
+ if (typeof raw === "string") return raw.trim();
7571
+ if (Array.isArray(raw)) {
7572
+ return raw.map((part) => {
7573
+ if (typeof part === "string") return part;
7574
+ if (part && typeof part === "object" && "text" in part) {
7575
+ const text3 = Reflect.get(part, "text");
7576
+ return typeof text3 === "string" ? text3 : "";
7577
+ }
7578
+ return "";
7579
+ }).filter(Boolean).join("\n").trim();
7580
+ }
7581
+ return "";
7582
+ }
7583
+ function fragmentsText(fragments, preferTypes) {
7584
+ if (!Array.isArray(fragments)) return "";
7585
+ const preferred = new Set(preferTypes.map((type) => type.toUpperCase()));
7586
+ const preferredParts = [];
7587
+ const fallbackParts = [];
7588
+ for (const frag of fragments) {
7589
+ if (frag === null || typeof frag !== "object") continue;
7590
+ const type = String(Reflect.get(frag, "type") ?? "").toUpperCase();
7591
+ const content = Reflect.get(frag, "content");
7592
+ if (typeof content !== "string" || content.trim() === "") continue;
7593
+ const text3 = content.trim();
7594
+ if (type === "THINK" || type === "TIP" || type.startsWith("TOOL_")) {
7595
+ if (preferred.size === 0) fallbackParts.push(text3);
7596
+ continue;
7597
+ }
7598
+ if (preferred.size === 0 || preferred.has(type)) preferredParts.push(text3);
7599
+ else fallbackParts.push(text3);
7600
+ }
7601
+ if (preferredParts.length > 0) return preferredParts.join("\n\n");
7602
+ return fallbackParts.join("\n\n");
7603
+ }
7604
+ function rowText(item, role) {
7605
+ const direct = messageText2(item.content ?? item.text ?? item.message);
7606
+ if (direct) return direct;
7607
+ if (role === "user") return fragmentsText(item.fragments, ["REQUEST"]);
7608
+ return fragmentsText(item.fragments, ["RESPONSE"]);
7609
+ }
7610
+ function assertTurns(turns) {
7611
+ if (turns.length === 0) {
7612
+ throw new Error("Share link has no messages");
7613
+ }
7614
+ if (turns.length > WEB_CHAT_MAX_MESSAGES) {
7615
+ throw new Error(`Exceeds message limit (${WEB_CHAT_MAX_MESSAGES})`);
7616
+ }
7617
+ let bytes = 0;
7618
+ for (const turn of turns) {
7619
+ bytes += Buffer.byteLength(turn.text, "utf8");
7620
+ if (bytes > WEB_CHAT_MAX_TEXT_BYTES) {
7621
+ throw new Error(`Share content exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
7622
+ }
7623
+ }
7624
+ }
7625
+ function bizRecord(data) {
7626
+ if (data === null || typeof data !== "object") return null;
7627
+ const root = data;
7628
+ if (Reflect.get(root, "code") !== 0 && Reflect.get(root, "code") !== void 0) {
7629
+ const msg = Reflect.get(root, "msg");
7630
+ throw new Error(
7631
+ typeof msg === "string" && msg.trim() !== "" ? `share-api: ${msg}` : "share-api: request failed"
7632
+ );
7633
+ }
7634
+ const payload = Reflect.get(root, "data");
7635
+ const biz = payload !== null && typeof payload === "object" ? Reflect.get(payload, "biz_data") : void 0;
7636
+ if (biz !== null && typeof biz === "object") return biz;
7637
+ return root;
7638
+ }
7639
+ function turnsFromBizRecord(record2) {
7640
+ const rowsRaw = record2.messages ?? record2.chat_messages;
7641
+ const rows = Array.isArray(rowsRaw) ? rowsRaw : [];
7642
+ const turns = [];
7643
+ for (const row of rows) {
7644
+ if (row === null || typeof row !== "object") continue;
7645
+ const item = row;
7646
+ const role = normalizeRole2(item.role ?? item.author ?? item.speaker);
7647
+ if (!role) continue;
7648
+ const text3 = rowText(item, role);
7649
+ if (!text3) continue;
7650
+ turns.push({ role, text: text3 });
7651
+ }
7652
+ return turns;
7653
+ }
7654
+ function parseWebChatShareContent(data, options) {
7655
+ const record2 = bizRecord(data);
7656
+ if (record2 === null) {
7657
+ throw new Error("unrecognized-share: empty response");
7658
+ }
7659
+ const titleRaw = record2.title;
7660
+ const title = typeof titleRaw === "string" && titleRaw.trim() !== "" ? titleRaw.trim() : `Shared chat ${options.shareId}`;
7661
+ const turns = turnsFromBizRecord(record2);
7662
+ assertTurns(turns);
7663
+ return {
7664
+ title,
7665
+ turns,
7666
+ partial: false,
7667
+ source: {
7668
+ kind: "share-link",
7669
+ url: options.shareUrl,
7670
+ chatSessionId: options.shareId,
7671
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString()
7672
+ }
7673
+ };
7674
+ }
7675
+ async function fetchWebChatShareContent(shareId, signal) {
7676
+ signal.throwIfAborted();
7677
+ const response = await fetch(webChatShareContentApiUrl(shareId), {
7678
+ method: "GET",
7679
+ signal,
7680
+ headers: {
7681
+ accept: "application/json, text/plain, */*",
7682
+ referer: "https://chat.deepseek.com/",
7683
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
7684
+ }
7685
+ });
7686
+ if (!response.ok) {
7687
+ throw new Error(`share-api: HTTP ${response.status}`);
7688
+ }
7689
+ return await response.json();
7690
+ }
7691
+
7692
+ // src/host/web-chat-bridge/login-snapshot.ts
7693
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7694
+ import { dirname, join as join9 } from "node:path";
7695
+
7696
+ // src/host/web-chat-bridge/login-snapshot-types.ts
7697
+ var WEB_CHAT_OFFICIAL_ORIGIN = "https://chat.deepseek.com";
7698
+ var WEB_CHAT_LOGIN_SNAPSHOT_VERSION = 1;
7699
+
7700
+ // src/host/web-chat-bridge/login-snapshot-policy.ts
7701
+ function localStorageKeyCount(slice) {
7702
+ return Object.keys(slice.localStorage).length;
7703
+ }
7704
+ function hasCookie(slice) {
7705
+ return slice.cookie.trim().length > 0;
7706
+ }
7707
+ function shouldPersistWebChatLoginCapture(baseline, candidate) {
7708
+ if (candidate === null) return false;
7709
+ const candidateKeys = localStorageKeyCount(candidate);
7710
+ const candidateCookie = hasCookie(candidate);
7711
+ if (candidateKeys === 0 && !candidateCookie) return false;
7712
+ if (baseline === null) return true;
7713
+ const baselineKeys = localStorageKeyCount(baseline);
7714
+ const baselineCookie = hasCookie(baseline);
7715
+ if (baselineKeys > 0 && candidateKeys === 0) return false;
7716
+ if (baselineCookie && !candidateCookie && candidateKeys === 0) return false;
7717
+ return true;
7718
+ }
7719
+
7720
+ // src/host/web-chat-bridge/login-snapshot.ts
7721
+ var SENSITIVE_STORAGE_KEY = /password|passwd|pwd/i;
7722
+ function webChatBridgeDataDir(pluginDataPackageRoot) {
7723
+ return join9(pluginDataPackageRoot, "web-chat-bridge");
7724
+ }
7725
+ function webChatLoginSnapshotPath(pluginDataPackageRoot) {
7726
+ return join9(webChatBridgeDataDir(pluginDataPackageRoot), "session.json");
7727
+ }
7728
+ function sanitizeLocalStorage(entries) {
7729
+ const out = {};
7730
+ for (const [key, value] of Object.entries(entries)) {
7731
+ if (typeof key !== "string" || typeof value !== "string") continue;
7732
+ if (SENSITIVE_STORAGE_KEY.test(key)) continue;
7733
+ out[key] = value;
7734
+ }
7735
+ return out;
7736
+ }
7737
+ function parseSnapshot(raw) {
7738
+ try {
7739
+ const parsed = JSON.parse(raw);
7740
+ if (parsed.version !== WEB_CHAT_LOGIN_SNAPSHOT_VERSION) return null;
7741
+ if (parsed.origin !== WEB_CHAT_OFFICIAL_ORIGIN) return null;
7742
+ const localStorage = sanitizeLocalStorage(
7743
+ typeof parsed.localStorage === "object" && parsed.localStorage !== null ? parsed.localStorage : {}
7744
+ );
7745
+ const cookie = typeof parsed.cookie === "string" ? parsed.cookie : "";
7746
+ const savedAt = typeof parsed.savedAt === "string" && parsed.savedAt.trim() !== "" ? parsed.savedAt : (/* @__PURE__ */ new Date()).toISOString();
7747
+ return {
7748
+ version: WEB_CHAT_LOGIN_SNAPSHOT_VERSION,
7749
+ origin: WEB_CHAT_OFFICIAL_ORIGIN,
7750
+ localStorage,
7751
+ cookie,
7752
+ savedAt
7753
+ };
7754
+ } catch {
7755
+ return null;
7756
+ }
7757
+ }
7758
+ function loadWebChatLoginSnapshot(pluginDataPackageRoot) {
7759
+ const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7760
+ if (!existsSync6(path)) return null;
7761
+ try {
7762
+ return parseSnapshot(readFileSync(path, "utf8"));
7763
+ } catch {
7764
+ return null;
6592
7765
  }
7766
+ }
7767
+ function saveWebChatLoginSnapshot(pluginDataPackageRoot, input, options) {
7768
+ const baseline = options?.baseline !== void 0 ? options.baseline : loadWebChatLoginSnapshot(pluginDataPackageRoot);
7769
+ const candidate = {
7770
+ localStorage: input.localStorage,
7771
+ cookie: input.cookie
7772
+ };
7773
+ if (!shouldPersistWebChatLoginCapture(baseline, candidate)) {
7774
+ return baseline;
7775
+ }
7776
+ if (input.origin !== void 0 && input.origin !== WEB_CHAT_OFFICIAL_ORIGIN) {
7777
+ throw new Error("Web chat login snapshot origin mismatch");
7778
+ }
7779
+ const snapshot = {
7780
+ version: WEB_CHAT_LOGIN_SNAPSHOT_VERSION,
7781
+ origin: WEB_CHAT_OFFICIAL_ORIGIN,
7782
+ localStorage: sanitizeLocalStorage(input.localStorage),
7783
+ cookie: typeof input.cookie === "string" ? input.cookie : "",
7784
+ savedAt: typeof input.savedAt === "string" && input.savedAt.trim() !== "" ? input.savedAt : (/* @__PURE__ */ new Date()).toISOString()
7785
+ };
7786
+ const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7787
+ mkdirSync2(dirname(path), { recursive: true });
7788
+ const tmp = `${path}.${process.pid}.tmp`;
7789
+ writeFileSync(tmp, `${JSON.stringify(snapshot, null, 2)}
7790
+ `, "utf8");
7791
+ renameSync(tmp, path);
7792
+ return snapshot;
7793
+ }
7794
+ function clearWebChatLoginSnapshot(pluginDataPackageRoot) {
7795
+ const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7796
+ if (!existsSync6(path)) return false;
6593
7797
  try {
6594
- const { stdout } = await execFileAsync("zenity", args, {
6595
- encoding: "utf8",
6596
- timeout: 12e4
6597
- });
6598
- const path = stdout.trim();
6599
- return path === "" ? null : path;
6600
- } catch (error) {
6601
- const code = error !== null && typeof error === "object" ? Reflect.get(error, "code") : void 0;
6602
- if (code === 1) return null;
6603
- return void 0;
7798
+ unlinkSync(path);
7799
+ return true;
7800
+ } catch {
7801
+ return false;
6604
7802
  }
6605
7803
  }
6606
- async function pickFileNow(signal, options = {}) {
6607
- signal.throwIfAborted();
6608
- const attempts = [
6609
- () => pickFileViaElectron(options),
6610
- () => pickFileViaWindowsForms(options),
6611
- () => pickFileViaOsascript(options),
6612
- () => pickFileViaZenity(options)
6613
- ];
6614
- for (const attempt of attempts) {
6615
- signal.throwIfAborted();
6616
- const path = await attempt();
6617
- if (path !== void 0) return { path };
7804
+
7805
+ // src/host/extra-folders/io.ts
7806
+ import { promises as fsp } from "node:fs";
7807
+ import { basename as basename4, join as join10, resolve as resolve4, sep as sep4 } from "node:path";
7808
+
7809
+ // src/host/extra-folders/paths.ts
7810
+ import { createHash as createHash6 } from "node:crypto";
7811
+ import { isAbsolute as isAbsolute3, relative as relative2, resolve as resolve3, sep as sep3 } from "node:path";
7812
+ function cwdStorageKey(primaryCwd) {
7813
+ const normalized = resolve3(primaryCwd);
7814
+ return createHash6("sha256").update(normalized).digest("hex").slice(0, 32);
7815
+ }
7816
+ function isInsideRoot(root, absolutePath2) {
7817
+ const base = resolve3(root);
7818
+ const target = resolve3(absolutePath2);
7819
+ const rel = relative2(base, target);
7820
+ return rel === "" || !rel.startsWith(`..${sep3}`) && rel !== ".." && !isAbsolute3(rel);
7821
+ }
7822
+ function assertInsideAllowedRoots(primaryCwd, extraRoots, absolutePath2) {
7823
+ if (isInsideRoot(primaryCwd, absolutePath2)) return;
7824
+ for (const root of extraRoots) {
7825
+ if (isInsideRoot(root, absolutePath2)) return;
6618
7826
  }
6619
- throw new ExtraFoldersError(
6620
- "FILE_EDIT_FAILED",
6621
- "No file picker is available in this environment"
6622
- );
7827
+ throw new Error("Path is outside the session workspace and attached folders");
7828
+ }
7829
+ function normalizeRootPath(path) {
7830
+ const trimmed = path.trim();
7831
+ if (trimmed === "") throw new Error("Path is empty");
7832
+ return resolve3(trimmed);
6623
7833
  }
6624
7834
 
6625
7835
  // src/host/extra-folders/io.ts
6626
7836
  function sessionCwd(session) {
6627
7837
  const header = session?.header;
6628
- if (typeof header?.cwd === "string" && header.cwd.trim() !== "") return resolve3(header.cwd);
7838
+ if (typeof header?.cwd === "string" && header.cwd.trim() !== "") return resolve4(header.cwd);
6629
7839
  try {
6630
7840
  const requested = session?.requestHeader?.();
6631
7841
  if (typeof requested?.cwd === "string" && requested.cwd.trim() !== "") {
6632
- return resolve3(requested.cwd);
7842
+ return resolve4(requested.cwd);
6633
7843
  }
6634
7844
  } catch {
6635
7845
  }
@@ -6648,7 +7858,7 @@ function titleOf(path, explicit) {
6648
7858
  return name2 === "" ? path : name2;
6649
7859
  }
6650
7860
  function samePath(a, b) {
6651
- return resolve3(a).toLowerCase() === resolve3(b).toLowerCase();
7861
+ return resolve4(a).toLowerCase() === resolve4(b).toLowerCase();
6652
7862
  }
6653
7863
  async function assertDirectory(absolutePath2) {
6654
7864
  try {
@@ -6812,7 +8022,7 @@ async function listExtraFolderEntriesNow(options) {
6812
8022
  throw new ExtraFoldersError("FILE_DENIED", "Root is not the workspace or an attached folder");
6813
8023
  }
6814
8024
  const relativePath = relativeUnderRoot(rootPath, options.request.relativePath);
6815
- const absoluteDir = relativePath === "" ? rootPath : join9(rootPath, relativePath);
8025
+ const absoluteDir = relativePath === "" ? rootPath : join10(rootPath, relativePath);
6816
8026
  assertInsideAllowedRoots(primaryCwd, extraPaths, absoluteDir);
6817
8027
  await assertDirectory(absoluteDir);
6818
8028
  let names;
@@ -6827,14 +8037,14 @@ async function listExtraFolderEntriesNow(options) {
6827
8037
  const entries = [];
6828
8038
  for (const name2 of names) {
6829
8039
  if (name2 === "." || name2 === "..") continue;
6830
- const absolutePath2 = join9(absoluteDir, name2);
8040
+ const absolutePath2 = join10(absoluteDir, name2);
6831
8041
  try {
6832
8042
  assertInsideAllowedRoots(primaryCwd, extraPaths, absolutePath2);
6833
8043
  const stat = await fsp.lstat(absolutePath2);
6834
8044
  if (stat.isSymbolicLink()) continue;
6835
8045
  const kind = stat.isDirectory() ? "directory" : stat.isFile() ? "file" : null;
6836
8046
  if (kind === null) continue;
6837
- const path = relativePath === "" ? name2 : join9(relativePath, name2);
8047
+ const path = relativePath === "" ? name2 : join10(relativePath, name2);
6838
8048
  entries.push({ name: name2, path: path.replace(/\\/g, "/"), absolutePath: absolutePath2, kind });
6839
8049
  } catch {
6840
8050
  }
@@ -6850,12 +8060,12 @@ async function listExtraFolderEntriesNow(options) {
6850
8060
  };
6851
8061
  }
6852
8062
  function loadExtraRootPaths(store, primaryCwd) {
6853
- return store.load(resolve3(primaryCwd)).roots.map((root) => root.path);
8063
+ return store.load(resolve4(primaryCwd)).roots.map((root) => root.path);
6854
8064
  }
6855
8065
 
6856
8066
  // src/host/extra-folders/store.ts
6857
- import { mkdirSync as mkdirSync2, readFileSync, renameSync, writeFileSync } from "node:fs";
6858
- import { dirname, join as join10 } from "node:path";
8067
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
8068
+ import { dirname as dirname2, join as join11 } from "node:path";
6859
8069
  function emptyDoc(primaryCwd) {
6860
8070
  return {
6861
8071
  version: EXTRA_FOLDERS_VERSION,
@@ -6887,14 +8097,14 @@ function parseDoc(raw, primaryCwd) {
6887
8097
  }
6888
8098
  }
6889
8099
  function createExtraFoldersStore(rootDir) {
6890
- mkdirSync2(rootDir, { recursive: true });
6891
- const fileOf = (primaryCwd) => join10(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
8100
+ mkdirSync3(rootDir, { recursive: true });
8101
+ const fileOf = (primaryCwd) => join11(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
6892
8102
  return {
6893
8103
  rootDir,
6894
8104
  load(primaryCwd) {
6895
8105
  const file = fileOf(primaryCwd);
6896
8106
  try {
6897
- return parseDoc(readFileSync(file, "utf8"), primaryCwd);
8107
+ return parseDoc(readFileSync2(file, "utf8"), primaryCwd);
6898
8108
  } catch (error) {
6899
8109
  const code = error !== null && typeof error === "object" ? String(Reflect.get(error, "code") ?? "") : "";
6900
8110
  if (code === "ENOENT") return emptyDoc(primaryCwd);
@@ -6908,18 +8118,18 @@ function createExtraFoldersStore(rootDir) {
6908
8118
  roots: [...roots]
6909
8119
  };
6910
8120
  const file = fileOf(primaryCwd);
6911
- mkdirSync2(dirname(file), { recursive: true });
8121
+ mkdirSync3(dirname2(file), { recursive: true });
6912
8122
  const tmp = `${file}.${process.pid}.tmp`;
6913
- writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}
8123
+ writeFileSync2(tmp, `${JSON.stringify(doc, null, 2)}
6914
8124
  `, "utf8");
6915
- renameSync(tmp, file);
8125
+ renameSync2(tmp, file);
6916
8126
  return doc;
6917
8127
  }
6918
8128
  };
6919
8129
  }
6920
8130
 
6921
8131
  // src/host/file-edit/io.ts
6922
- import { isAbsolute as isAbsolute4, resolve as resolve4 } from "node:path";
8132
+ import { isAbsolute as isAbsolute4, resolve as resolve5 } from "node:path";
6923
8133
 
6924
8134
  // src/host/file-edit/types.ts
6925
8135
  var FILE_EDIT_MAX_BYTES = 2 * 1024 * 1024;
@@ -7000,7 +8210,7 @@ async function resolveTarget(fs, workspaceRoot, extraRoots, path) {
7000
8210
  const trimmed = path.trim();
7001
8211
  if (trimmed === "") throw new FileEditError("FILE_NOT_FOUND", "Path is empty");
7002
8212
  const target = await fs.resolve(trimmed, { cwd: workspaceRoot });
7003
- const absolutePath2 = processPathOf(target, isAbsolute4(trimmed) ? trimmed : resolve4(workspaceRoot, trimmed));
8213
+ const absolutePath2 = processPathOf(target, isAbsolute4(trimmed) ? trimmed : resolve5(workspaceRoot, trimmed));
7004
8214
  try {
7005
8215
  assertInsideAllowedRoots(workspaceRoot, extraRoots, absolutePath2);
7006
8216
  } catch (error) {
@@ -7096,9 +8306,9 @@ async function writeWorkspaceFileNow(options) {
7096
8306
  }
7097
8307
 
7098
8308
  // src/host/file-edit/monaco.ts
7099
- import { existsSync as existsSync4 } from "node:fs";
8309
+ import { existsSync as existsSync7 } from "node:fs";
7100
8310
  import { promises as fsp2 } from "node:fs";
7101
- import { dirname as dirname2, extname, join as join11, resolve as resolve5, sep as sep5 } from "node:path";
8311
+ import { dirname as dirname3, extname, join as join12, resolve as resolve6, sep as sep5 } from "node:path";
7102
8312
  import { fileURLToPath } from "node:url";
7103
8313
 
7104
8314
  // src/shared/monaco-route.ts
@@ -7107,16 +8317,16 @@ var MONACO_ROUTE = "/api/agent-enhancer/monaco";
7107
8317
  // src/host/file-edit/monaco.ts
7108
8318
  var FILE_PATTERN = /^(?:vs\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/;
7109
8319
  function packageRootCandidates() {
7110
- const here = dirname2(fileURLToPath(import.meta.url));
8320
+ const here = dirname3(fileURLToPath(import.meta.url));
7111
8321
  return [
7112
- resolve5(here, "..", "vendor", "monaco", "vs"),
7113
- resolve5(here, "..", "..", "vendor", "monaco", "vs"),
7114
- resolve5(here, "..", "..", "..", "vendor", "monaco", "vs")
8322
+ resolve6(here, "..", "vendor", "monaco", "vs"),
8323
+ resolve6(here, "..", "..", "vendor", "monaco", "vs"),
8324
+ resolve6(here, "..", "..", "..", "vendor", "monaco", "vs")
7115
8325
  ];
7116
8326
  }
7117
8327
  function resolveMonacoVsDir() {
7118
8328
  for (const candidate of packageRootCandidates()) {
7119
- if (existsSync4(join11(candidate, "loader.js"))) return candidate;
8329
+ if (existsSync7(join12(candidate, "loader.js"))) return candidate;
7120
8330
  }
7121
8331
  return packageRootCandidates()[0];
7122
8332
  }
@@ -7162,8 +8372,8 @@ function plain(status, message) {
7162
8372
  });
7163
8373
  }
7164
8374
  function isInside(root, candidate) {
7165
- const normalizedRoot = resolve5(root);
7166
- const normalized = resolve5(candidate);
8375
+ const normalizedRoot = resolve6(root);
8376
+ const normalized = resolve6(candidate);
7167
8377
  if (normalized === normalizedRoot) return true;
7168
8378
  return normalized.startsWith(normalizedRoot + sep5);
7169
8379
  }
@@ -7172,7 +8382,7 @@ async function locateFile(vsDir, relativeUnderVs) {
7172
8382
  const parts = relativeUnderVs.split("/");
7173
8383
  let cursor = rootReal;
7174
8384
  for (const part of parts) {
7175
- cursor = join11(cursor, part);
8385
+ cursor = join12(cursor, part);
7176
8386
  if (!isInside(rootReal, cursor)) return null;
7177
8387
  }
7178
8388
  if (!isInside(rootReal, cursor)) return null;
@@ -7253,16 +8463,16 @@ function installMonacoRoute(ctx) {
7253
8463
  }
7254
8464
 
7255
8465
  // src/host/instructions-skills/io.ts
7256
- import { existsSync as existsSync14, readFileSync as readFileSync6, statSync as statSync4 } from "node:fs";
7257
- import { basename as basename13, join as join25, resolve as resolve15, sep as sep7 } from "node:path";
8466
+ import { existsSync as existsSync17, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
8467
+ import { basename as basename13, join as join26, resolve as resolve16, sep as sep7 } from "node:path";
7258
8468
 
7259
8469
  // src/host/instructions-skills/create.ts
7260
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
7261
- import { dirname as dirname4, join as join13, resolve as resolve7 } from "node:path";
8470
+ import { existsSync as existsSync9, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
8471
+ import { dirname as dirname5, join as join14, resolve as resolve8 } from "node:path";
7262
8472
 
7263
8473
  // src/host/instructions-skills/paths.ts
7264
- import { existsSync as existsSync5, statSync } from "node:fs";
7265
- import { basename as basename5, dirname as dirname3, join as join12, resolve as resolve6, sep as sep6 } from "node:path";
8474
+ import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
8475
+ import { basename as basename5, dirname as dirname4, join as join13, resolve as resolve7, sep as sep6 } from "node:path";
7266
8476
  import { homedir as homedir3 } from "node:os";
7267
8477
  var INSTRUCTION_CANDIDATES = [
7268
8478
  "AGENTS.md",
@@ -7273,76 +8483,76 @@ var INSTRUCTION_CANDIDATES = [
7273
8483
  var PROJECT_ROOT_MARKERS = [".git"];
7274
8484
  function dshHomeOf(env = process.env) {
7275
8485
  const fromEnv = env.DSH_HOME;
7276
- if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve6(fromEnv.trim());
7277
- return resolve6(homedir3(), ".dsh");
8486
+ if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve7(fromEnv.trim());
8487
+ return resolve7(homedir3(), ".dsh");
7278
8488
  }
7279
8489
  function agentsHomeOf(env = process.env) {
7280
8490
  const fromEnv = env.DSH_AGENTS_HOME;
7281
- if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve6(fromEnv.trim());
7282
- return resolve6(homedir3(), ".agents");
8491
+ if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve7(fromEnv.trim());
8492
+ return resolve7(homedir3(), ".agents");
7283
8493
  }
7284
8494
  function findProjectRoot(cwd, markers = PROJECT_ROOT_MARKERS) {
7285
- let current = resolve6(cwd);
8495
+ let current = resolve7(cwd);
7286
8496
  for (; ; ) {
7287
8497
  for (const marker of markers) {
7288
- if (existsSync5(join12(current, marker))) return current;
8498
+ if (existsSync8(join13(current, marker))) return current;
7289
8499
  }
7290
- const parent = dirname3(current);
7291
- if (parent === current) return resolve6(cwd);
8500
+ const parent = dirname4(current);
8501
+ if (parent === current) return resolve7(cwd);
7292
8502
  current = parent;
7293
8503
  }
7294
8504
  }
7295
8505
  function projectChainDirs(projectRoot, cwd) {
7296
- const root = resolve6(projectRoot);
7297
- const tip = resolve6(cwd);
8506
+ const root = resolve7(projectRoot);
8507
+ const tip = resolve7(cwd);
7298
8508
  if (!isInsideOrSame(root, tip)) return [root];
7299
8509
  const parts = [];
7300
8510
  let current = tip;
7301
8511
  for (; ; ) {
7302
8512
  parts.push(current);
7303
8513
  if (samePath2(current, root)) break;
7304
- const parent = dirname3(current);
8514
+ const parent = dirname4(current);
7305
8515
  if (parent === current) break;
7306
8516
  current = parent;
7307
8517
  }
7308
8518
  return parts.reverse();
7309
8519
  }
7310
8520
  function skillRootsFor(cwd, projectRoot, env = process.env) {
7311
- const root = resolve6(projectRoot);
7312
- const tip = resolve6(cwd);
8521
+ const root = resolve7(projectRoot);
8522
+ const tip = resolve7(cwd);
7313
8523
  return [
7314
- join12(root, ".agents", "skills"),
7315
- join12(root, ".dsh", "skills"),
7316
- join12(tip, ".agents", "skills"),
7317
- join12(tip, ".dsh", "skills"),
7318
- join12(agentsHomeOf(env), "skills"),
7319
- join12(dshHomeOf(env), "skills")
8524
+ join13(root, ".agents", "skills"),
8525
+ join13(root, ".dsh", "skills"),
8526
+ join13(tip, ".agents", "skills"),
8527
+ join13(tip, ".dsh", "skills"),
8528
+ join13(agentsHomeOf(env), "skills"),
8529
+ join13(dshHomeOf(env), "skills")
7320
8530
  ].filter((path, index, all) => all.findIndex((other) => samePath2(other, path)) === index);
7321
8531
  }
7322
8532
  function previewSkillSearchRoots(cwd, projectRoot, env = process.env) {
7323
- const home = resolve6(homedir3());
8533
+ const home = resolve7(homedir3());
7324
8534
  return [
7325
8535
  ...skillRootsFor(cwd, projectRoot, env),
7326
- join12(home, ".cursor", "skills"),
7327
- join12(home, ".cursor", "skills-cursor"),
7328
- join12(home, ".codex", "skills"),
7329
- join12(home, ".claude", "skills")
8536
+ join13(home, ".cursor", "skills"),
8537
+ join13(home, ".cursor", "skills-cursor"),
8538
+ join13(home, ".codex", "skills"),
8539
+ join13(home, ".claude", "skills")
7330
8540
  ].filter((path, index, all) => all.findIndex((other) => samePath2(other, path)) === index);
7331
8541
  }
7332
8542
  function fileBytes(path) {
7333
8543
  try {
7334
- const stat = statSync(path);
8544
+ const stat = statSync2(path);
7335
8545
  return stat.isFile() ? stat.size : null;
7336
8546
  } catch {
7337
8547
  return null;
7338
8548
  }
7339
8549
  }
7340
8550
  function samePath2(a, b) {
7341
- return resolve6(a).toLowerCase() === resolve6(b).toLowerCase();
8551
+ return resolve7(a).toLowerCase() === resolve7(b).toLowerCase();
7342
8552
  }
7343
8553
  function isInsideOrSame(root, candidate) {
7344
- const base = resolve6(root).toLowerCase();
7345
- const path = resolve6(candidate).toLowerCase();
8554
+ const base = resolve7(root).toLowerCase();
8555
+ const path = resolve7(candidate).toLowerCase();
7346
8556
  if (path === base) return true;
7347
8557
  const prefix = base.endsWith(sep6) ? base : `${base}${sep6}`;
7348
8558
  return path.startsWith(prefix);
@@ -7381,12 +8591,12 @@ Instructions for the agent go here.
7381
8591
  `;
7382
8592
  }
7383
8593
  function createWorkspaceAgentsFile(projectRoot) {
7384
- const path = resolve7(projectRoot, "AGENTS.md");
7385
- if (existsSync6(path)) {
8594
+ const path = resolve8(projectRoot, "AGENTS.md");
8595
+ if (existsSync9(path)) {
7386
8596
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
7387
8597
  }
7388
- mkdirSync3(dirname4(path), { recursive: true });
7389
- writeFileSync2(path, AGENTS_STUB, "utf8");
8598
+ mkdirSync4(dirname5(path), { recursive: true });
8599
+ writeFileSync3(path, AGENTS_STUB, "utf8");
7390
8600
  return { path, created: true };
7391
8601
  }
7392
8602
  function createWorkspaceSkill(projectRoot, rawName) {
@@ -7394,19 +8604,19 @@ function createWorkspaceSkill(projectRoot, rawName) {
7394
8604
  if (!isKebabCaseName(name2)) {
7395
8605
  throw new AuxiliaryError("FILE_DENIED", "Skill name must be kebab-case");
7396
8606
  }
7397
- const dir = join13(resolve7(projectRoot), ".agents", "skills", name2);
7398
- const path = join13(dir, "SKILL.md");
7399
- if (existsSync6(path) || existsSync6(dir)) {
8607
+ const dir = join14(resolve8(projectRoot), ".agents", "skills", name2);
8608
+ const path = join14(dir, "SKILL.md");
8609
+ if (existsSync9(path) || existsSync9(dir)) {
7400
8610
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
7401
8611
  }
7402
- mkdirSync3(dir, { recursive: true });
7403
- writeFileSync2(path, skillStubMarkdown(name2), "utf8");
8612
+ mkdirSync4(dir, { recursive: true });
8613
+ writeFileSync3(path, skillStubMarkdown(name2), "utf8");
7404
8614
  return { path, created: true, name: name2 };
7405
8615
  }
7406
8616
 
7407
8617
  // src/host/instructions-skills/discover.ts
7408
- import { existsSync as existsSync10, readdirSync as readdirSync3, readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
7409
- import { basename as basename9, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
8618
+ import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
8619
+ import { basename as basename9, dirname as dirname8, join as join19, resolve as resolve12 } from "node:path";
7410
8620
 
7411
8621
  // src/host/instructions-skills/types.ts
7412
8622
  function defaultSkillInstallMeta() {
@@ -7419,9 +8629,9 @@ function defaultSkillInstallMeta() {
7419
8629
  }
7420
8630
 
7421
8631
  // src/host/instructions-skills/transient-paths.ts
7422
- import { existsSync as existsSync7, lstatSync, readdirSync, renameSync as renameSync2, rmSync, unlinkSync } from "node:fs";
8632
+ import { existsSync as existsSync10, lstatSync, readdirSync, renameSync as renameSync3, rmSync, unlinkSync as unlinkSync2 } from "node:fs";
7423
8633
  import { tmpdir as tmpdir2 } from "node:os";
7424
- import { basename as basename6, join as join14, resolve as resolve8 } from "node:path";
8634
+ import { basename as basename6, join as join15, resolve as resolve9 } from "node:path";
7425
8635
  var TRANSIENT_MARK = /\.__ae_(?:removing|installing)_/;
7426
8636
  function isTransientSkillEntryName(name2) {
7427
8637
  const base = basename6(name2.trim());
@@ -7430,10 +8640,10 @@ function isTransientSkillEntryName(name2) {
7430
8640
  }
7431
8641
  function skillTransientWorkPath(kind, skillName) {
7432
8642
  const safe = skillName.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 80) || "skill";
7433
- return join14(tmpdir2(), `ae-skill-${kind}-${safe}-${process.pid}-${Date.now()}`);
8643
+ return join15(tmpdir2(), `ae-skill-${kind}-${safe}-${process.pid}-${Date.now()}`);
7434
8644
  }
7435
8645
  function sweepTransientSkillEntries(skillsRoot) {
7436
- const root = resolve8(skillsRoot);
8646
+ const root = resolve9(skillsRoot);
7437
8647
  let names;
7438
8648
  try {
7439
8649
  names = readdirSync(root);
@@ -7442,7 +8652,7 @@ function sweepTransientSkillEntries(skillsRoot) {
7442
8652
  }
7443
8653
  for (const name2 of names) {
7444
8654
  if (!isTransientSkillEntryName(name2)) continue;
7445
- const full = join14(root, name2);
8655
+ const full = join15(root, name2);
7446
8656
  try {
7447
8657
  rmSync(full, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 });
7448
8658
  } catch {
@@ -7450,14 +8660,14 @@ function sweepTransientSkillEntries(skillsRoot) {
7450
8660
  }
7451
8661
  }
7452
8662
  function renameAsideToTemp(from, kind) {
7453
- const absolute = resolve8(from);
8663
+ const absolute = resolve9(from);
7454
8664
  const preferred = skillTransientWorkPath(kind, basename6(absolute));
7455
8665
  try {
7456
- renameSync2(absolute, preferred);
8666
+ renameSync3(absolute, preferred);
7457
8667
  return preferred;
7458
8668
  } catch {
7459
8669
  const sibling = `${absolute}.__ae_${kind}_${process.pid}_${Date.now()}`;
7460
- renameSync2(absolute, sibling);
8670
+ renameSync3(absolute, sibling);
7461
8671
  return sibling;
7462
8672
  }
7463
8673
  }
@@ -7466,7 +8676,7 @@ function removeQuietly(path) {
7466
8676
  const stat = lstatSync(path);
7467
8677
  if (stat.isSymbolicLink()) {
7468
8678
  try {
7469
- unlinkSync(path);
8679
+ unlinkSync2(path);
7470
8680
  } catch {
7471
8681
  }
7472
8682
  return;
@@ -7474,7 +8684,7 @@ function removeQuietly(path) {
7474
8684
  } catch {
7475
8685
  return;
7476
8686
  }
7477
- if (!existsSync7(path)) return;
8687
+ if (!existsSync10(path)) return;
7478
8688
  try {
7479
8689
  rmSync(path, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 });
7480
8690
  } catch {
@@ -7483,27 +8693,27 @@ function removeQuietly(path) {
7483
8693
 
7484
8694
  // src/host/instructions-skills/uninstall.ts
7485
8695
  import { lstatSync as lstatSync3 } from "node:fs";
7486
- import { basename as basename8, dirname as dirname6, join as join17, resolve as resolve10 } from "node:path";
8696
+ import { basename as basename8, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
7487
8697
 
7488
8698
  // src/host/instructions-skills/install-ledger.ts
7489
- import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
7490
- import { dirname as dirname5, join as join15 } from "node:path";
8699
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
8700
+ import { dirname as dirname6, join as join16 } from "node:path";
7491
8701
  function ledgerPath(dataRoot) {
7492
- return join15(dataRoot, "skills-install", "registry.json");
8702
+ return join16(dataRoot, "skills-install", "registry.json");
7493
8703
  }
7494
8704
  function writeLedger(dataRoot, ledger) {
7495
8705
  const path = ledgerPath(dataRoot);
7496
- mkdirSync4(dirname5(path), { recursive: true });
8706
+ mkdirSync5(dirname6(path), { recursive: true });
7497
8707
  const tmp = `${path}.${process.pid}.tmp`;
7498
- writeFileSync3(tmp, `${JSON.stringify(ledger, null, 2)}
8708
+ writeFileSync4(tmp, `${JSON.stringify(ledger, null, 2)}
7499
8709
  `, "utf8");
7500
- renameSync3(tmp, path);
8710
+ renameSync4(tmp, path);
7501
8711
  }
7502
8712
  function readInstallLedger(dataRoot) {
7503
8713
  const path = ledgerPath(dataRoot);
7504
- if (!existsSync8(path)) return {};
8714
+ if (!existsSync11(path)) return {};
7505
8715
  try {
7506
- const raw = readFileSync2(path, "utf8").trim();
8716
+ const raw = readFileSync3(path, "utf8").trim();
7507
8717
  if (raw === "") return {};
7508
8718
  return JSON.parse(raw);
7509
8719
  } catch {
@@ -7525,15 +8735,15 @@ function removeInstallRecord(dataRoot, name2) {
7525
8735
  import { execFileSync as execFileSync2 } from "node:child_process";
7526
8736
  import {
7527
8737
  chmodSync,
7528
- existsSync as existsSync9,
8738
+ existsSync as existsSync12,
7529
8739
  lstatSync as lstatSync2,
7530
8740
  readdirSync as readdirSync2,
7531
8741
  readlinkSync,
7532
8742
  rmSync as rmSync2,
7533
- unlinkSync as unlinkSync2
8743
+ unlinkSync as unlinkSync3
7534
8744
  } from "node:fs";
7535
8745
  import { homedir as homedir4 } from "node:os";
7536
- import { basename as basename7, join as join16, resolve as resolve9 } from "node:path";
8746
+ import { basename as basename7, join as join17, resolve as resolve10 } from "node:path";
7537
8747
 
7538
8748
  // src/host/instructions-skills/fs-access.ts
7539
8749
  var ACCESS_DENIED_RE = /eperm|eacces|eio|ebusy|access is denied|operation not permitted|file in use|still present|拒绝访问|¾Ü¾ø·ÃÎÊ/i;
@@ -7562,10 +8772,10 @@ function pathPresent(path) {
7562
8772
  }
7563
8773
  }
7564
8774
  function isManagedSkillEntryPath(target, env = process.env) {
7565
- const absolute = resolve9(target);
8775
+ const absolute = resolve10(target);
7566
8776
  const managedRoots = [
7567
- join16(agentsHomeOf(env), "skills"),
7568
- join16(dshHomeOf(env), "skills")
8777
+ join17(agentsHomeOf(env), "skills"),
8778
+ join17(dshHomeOf(env), "skills")
7569
8779
  ];
7570
8780
  for (const root of managedRoots) {
7571
8781
  if (samePath2(absolute, root) || isInsideOrSame(root, absolute)) return true;
@@ -7573,17 +8783,17 @@ function isManagedSkillEntryPath(target, env = process.env) {
7573
8783
  return false;
7574
8784
  }
7575
8785
  function isProtectedExternalSkillPath(target, env = process.env) {
7576
- const absolute = resolve9(target);
8786
+ const absolute = resolve10(target);
7577
8787
  if (isManagedSkillEntryPath(absolute, env)) return false;
7578
- const home = resolve9(homedir4());
8788
+ const home = resolve10(homedir4());
7579
8789
  const protectedRoots = [
7580
- join16(home, ".skills-manager"),
7581
- join16(home, ".cursor", "skills"),
7582
- join16(home, ".cursor", "skills-cursor"),
7583
- join16(home, ".codex", "skills"),
7584
- join16(home, ".claude", "skills"),
7585
- join16(home, ".codebuddy", "skills"),
7586
- join16(home, ".workbuddy", "skills")
8790
+ join17(home, ".skills-manager"),
8791
+ join17(home, ".cursor", "skills"),
8792
+ join17(home, ".cursor", "skills-cursor"),
8793
+ join17(home, ".codex", "skills"),
8794
+ join17(home, ".claude", "skills"),
8795
+ join17(home, ".codebuddy", "skills"),
8796
+ join17(home, ".workbuddy", "skills")
7587
8797
  ];
7588
8798
  for (const root of protectedRoots) {
7589
8799
  if (samePath2(absolute, root) || isInsideOrSame(root, absolute)) return true;
@@ -7607,12 +8817,12 @@ function isReparseOrSymlink(path) {
7607
8817
  }
7608
8818
  }
7609
8819
  function effectivelyGone(target) {
7610
- if (!pathPresent(target) && !existsSync9(target)) return true;
8820
+ if (!pathPresent(target) && !existsSync12(target)) return true;
7611
8821
  try {
7612
8822
  const stat = lstatSync2(target);
7613
8823
  if (stat.isSymbolicLink()) return false;
7614
8824
  if (!stat.isDirectory()) return false;
7615
- if (existsSync9(join16(target, "SKILL.md"))) return false;
8825
+ if (existsSync12(join17(target, "SKILL.md"))) return false;
7616
8826
  let names;
7617
8827
  try {
7618
8828
  names = readdirSync2(target);
@@ -7626,7 +8836,7 @@ function effectivelyGone(target) {
7626
8836
  }
7627
8837
  function unlinkMountOnly(absolute) {
7628
8838
  try {
7629
- unlinkSync2(absolute);
8839
+ unlinkSync3(absolute);
7630
8840
  } catch {
7631
8841
  if (process.platform === "win32") {
7632
8842
  try {
@@ -7642,7 +8852,7 @@ function unlinkMountOnly(absolute) {
7642
8852
  return false;
7643
8853
  }
7644
8854
  }
7645
- return !pathPresent(absolute) && !existsSync9(absolute);
8855
+ return !pathPresent(absolute) && !existsSync12(absolute);
7646
8856
  }
7647
8857
  function tryUnlinkReparseOrFile(absolute) {
7648
8858
  let preferUnlink = false;
@@ -7658,11 +8868,11 @@ function tryUnlinkReparseOrFile(absolute) {
7658
8868
  return unlinkMountOnly(absolute);
7659
8869
  }
7660
8870
  function removePathRobust(target) {
7661
- const absolute = resolve9(target);
8871
+ const absolute = resolve10(target);
7662
8872
  if (isProtectedExternalSkillPath(absolute)) {
7663
8873
  return;
7664
8874
  }
7665
- if (!pathPresent(absolute) && !existsSync9(absolute)) return;
8875
+ if (!pathPresent(absolute) && !existsSync12(absolute)) return;
7666
8876
  if (isReparseOrSymlink(absolute)) {
7667
8877
  if (unlinkMountOnly(absolute)) return;
7668
8878
  if (effectivelyGone(absolute)) return;
@@ -7680,7 +8890,7 @@ function removePathRobust(target) {
7680
8890
  } catch (error) {
7681
8891
  if (!isWindowsPathBusyError(error) && effectivelyGone(absolute)) return;
7682
8892
  }
7683
- if (!pathPresent(absolute) && !existsSync9(absolute)) return;
8893
+ if (!pathPresent(absolute) && !existsSync12(absolute)) return;
7684
8894
  try {
7685
8895
  const aside = renameAsideToTemp(absolute, "removing");
7686
8896
  removeQuietly(aside);
@@ -7700,18 +8910,18 @@ function removePathRobust(target) {
7700
8910
  } catch {
7701
8911
  }
7702
8912
  }
7703
- if (!pathPresent(absolute) && !existsSync9(absolute)) return;
8913
+ if (!pathPresent(absolute) && !existsSync12(absolute)) return;
7704
8914
  if (effectivelyGone(absolute)) return;
7705
8915
  }
7706
- if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync9(absolute)) return;
8916
+ if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync12(absolute)) return;
7707
8917
  throw new AuxiliaryError("FILE_EDIT_FAILED", busyPathHint(basename7(absolute)));
7708
8918
  }
7709
8919
 
7710
8920
  // src/host/instructions-skills/uninstall.ts
7711
8921
  function skillEntryPath(skillMdOrBundlePath) {
7712
- const absolute = resolve10(skillMdOrBundlePath);
8922
+ const absolute = resolve11(skillMdOrBundlePath);
7713
8923
  const base = basename8(absolute);
7714
- if (base.toLowerCase() === "skill.md") return dirname6(absolute);
8924
+ if (base.toLowerCase() === "skill.md") return dirname7(absolute);
7715
8925
  if (base.toLowerCase().endsWith(".md")) return absolute;
7716
8926
  return absolute;
7717
8927
  }
@@ -7726,11 +8936,11 @@ function pathPresent2(path) {
7726
8936
  function managedSkillEntriesForName(root, name2) {
7727
8937
  if (!isKebabCaseName(name2)) return [];
7728
8938
  const out = [];
7729
- const asDir = join17(root, name2);
7730
- const asFile = join17(root, `${name2}.md`);
8939
+ const asDir = join18(root, name2);
8940
+ const asFile = join18(root, `${name2}.md`);
7731
8941
  for (const entry of [asDir, asFile]) {
7732
8942
  if (!pathPresent2(entry)) continue;
7733
- if (!samePath2(dirname6(entry), root)) continue;
8943
+ if (!samePath2(dirname7(entry), root)) continue;
7734
8944
  if (!isInsideOrSame(root, entry)) continue;
7735
8945
  out.push(entry);
7736
8946
  }
@@ -7740,11 +8950,11 @@ function resolveManagedSkillRemovalTarget(path, name2, managedRoots) {
7740
8950
  if (!isKebabCaseName(name2)) return null;
7741
8951
  const entry = skillEntryPath(path);
7742
8952
  for (const root of managedRoots) {
7743
- const asDir = join17(root, name2);
7744
- const asFile = join17(root, `${name2}.md`);
8953
+ const asDir = join18(root, name2);
8954
+ const asFile = join18(root, `${name2}.md`);
7745
8955
  if (samePath2(entry, asDir) || samePath2(entry, asFile)) {
7746
8956
  if (!pathPresent2(entry)) return null;
7747
- if (!samePath2(dirname6(entry), root)) return null;
8957
+ if (!samePath2(dirname7(entry), root)) return null;
7748
8958
  if (!isInsideOrSame(root, entry)) return null;
7749
8959
  return entry;
7750
8960
  }
@@ -7761,15 +8971,15 @@ function purgeManagedSkillName(options) {
7761
8971
  if (!isKebabCaseName(name2)) {
7762
8972
  throw new AuxiliaryError("FILE_DENIED", `Invalid skill name: ${name2}`);
7763
8973
  }
7764
- const except = (options.exceptPaths ?? []).map((entry) => resolve10(entry));
8974
+ const except = (options.exceptPaths ?? []).map((entry) => resolve11(entry));
7765
8975
  const roots = skillRootsFor(options.cwd, options.projectRoot, options.env);
7766
8976
  const purgeTargets = /* @__PURE__ */ new Set();
7767
8977
  for (const extra of options.also ?? []) {
7768
- purgeTargets.add(resolve10(extra));
8978
+ purgeTargets.add(resolve11(extra));
7769
8979
  }
7770
8980
  for (const root of roots) {
7771
8981
  for (const entry of managedSkillEntriesForName(root, name2)) {
7772
- purgeTargets.add(resolve10(entry));
8982
+ purgeTargets.add(resolve11(entry));
7773
8983
  }
7774
8984
  }
7775
8985
  const removed = [];
@@ -7809,54 +9019,54 @@ function uninstallManagedSkill(options) {
7809
9019
 
7810
9020
  // src/host/instructions-skills/discover.ts
7811
9021
  function entryId(scope, path) {
7812
- return `${scope}:${resolve11(path).toLowerCase()}`;
9022
+ return `${scope}:${resolve12(path).toLowerCase()}`;
7813
9023
  }
7814
9024
  function pushUnique(out, seen, entry) {
7815
- const key = resolve11(entry.path).toLowerCase();
9025
+ const key = resolve12(entry.path).toLowerCase();
7816
9026
  if (seen.has(key)) return;
7817
9027
  seen.add(key);
7818
9028
  out.push(entry);
7819
9029
  }
7820
9030
  function discoverInstructionFiles(options) {
7821
9031
  const env = options.env ?? process.env;
7822
- const cwd = resolve11(options.cwd);
9032
+ const cwd = resolve12(options.cwd);
7823
9033
  const projectRoot = findProjectRoot(cwd);
7824
9034
  const seen = /* @__PURE__ */ new Set();
7825
9035
  const instructions = [];
7826
- const globalPath = join18(dshHomeOf(env), "AGENTS.md");
9036
+ const globalPath = join19(dshHomeOf(env), "AGENTS.md");
7827
9037
  pushUnique(instructions, seen, {
7828
9038
  id: entryId("global", globalPath),
7829
9039
  scope: "global",
7830
9040
  name: "AGENTS.md",
7831
9041
  path: globalPath,
7832
- exists: existsSync10(globalPath),
9042
+ exists: existsSync13(globalPath),
7833
9043
  bytes: fileBytes(globalPath),
7834
9044
  createable: false
7835
9045
  });
7836
- const sharedPath = join18(agentsHomeOf(env), "AGENTS.md");
9046
+ const sharedPath = join19(agentsHomeOf(env), "AGENTS.md");
7837
9047
  pushUnique(instructions, seen, {
7838
9048
  id: entryId("shared", sharedPath),
7839
9049
  scope: "shared",
7840
9050
  name: "AGENTS.md",
7841
9051
  path: sharedPath,
7842
- exists: existsSync10(sharedPath),
9052
+ exists: existsSync13(sharedPath),
7843
9053
  bytes: fileBytes(sharedPath),
7844
9054
  createable: false
7845
9055
  });
7846
- const rootAgents = join18(projectRoot, "AGENTS.md");
9056
+ const rootAgents = join19(projectRoot, "AGENTS.md");
7847
9057
  pushUnique(instructions, seen, {
7848
9058
  id: entryId("project", rootAgents),
7849
9059
  scope: "project",
7850
9060
  name: "AGENTS.md",
7851
9061
  path: rootAgents,
7852
- exists: existsSync10(rootAgents),
9062
+ exists: existsSync13(rootAgents),
7853
9063
  bytes: fileBytes(rootAgents),
7854
- createable: !existsSync10(rootAgents)
9064
+ createable: !existsSync13(rootAgents)
7855
9065
  });
7856
9066
  for (const dir of projectChainDirs(projectRoot, cwd)) {
7857
9067
  for (const name2 of INSTRUCTION_CANDIDATES) {
7858
- const path = join18(dir, name2);
7859
- if (!existsSync10(path)) continue;
9068
+ const path = join19(dir, name2);
9069
+ if (!existsSync13(path)) continue;
7860
9070
  if (samePath2(path, rootAgents)) continue;
7861
9071
  pushUnique(instructions, seen, {
7862
9072
  id: entryId("project", path),
@@ -7873,7 +9083,7 @@ function discoverInstructionFiles(options) {
7873
9083
  }
7874
9084
  function descriptionFromSkillMd(path) {
7875
9085
  try {
7876
- const text3 = readFileSync3(path, "utf8");
9086
+ const text3 = readFileSync4(path, "utf8");
7877
9087
  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text3);
7878
9088
  if (match === null) return "";
7879
9089
  const block = match[1];
@@ -7900,14 +9110,14 @@ function discoverFilesystemSkills(options) {
7900
9110
  }
7901
9111
  for (const name2 of names) {
7902
9112
  if (isTransientSkillEntryName(name2)) continue;
7903
- const skillMd = join18(root, name2, "SKILL.md");
7904
- if (!existsSync10(skillMd)) continue;
9113
+ const skillMd = join19(root, name2, "SKILL.md");
9114
+ if (!existsSync13(skillMd)) continue;
7905
9115
  if (byName.has(name2)) continue;
7906
9116
  byName.set(name2, {
7907
- id: `fs:${resolve11(skillMd).toLowerCase()}`,
9117
+ id: `fs:${resolve12(skillMd).toLowerCase()}`,
7908
9118
  name: name2,
7909
9119
  description: descriptionFromSkillMd(skillMd),
7910
- path: resolve11(skillMd),
9120
+ path: resolve12(skillMd),
7911
9121
  provider: dirnameLabel(root, options.projectRoot, env),
7912
9122
  modelInvocable: null,
7913
9123
  userInvocable: null,
@@ -7920,11 +9130,11 @@ function discoverFilesystemSkills(options) {
7920
9130
  return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
7921
9131
  }
7922
9132
  function dirnameLabel(root, projectRoot, env) {
7923
- if (samePath2(root, join18(projectRoot, ".agents", "skills"))) return "project";
7924
- if (samePath2(root, join18(projectRoot, ".dsh", "skills"))) return "project-dsh";
7925
- if (samePath2(root, join18(agentsHomeOf(env), "skills"))) return "shared";
7926
- if (samePath2(root, join18(dshHomeOf(env), "skills"))) return "dsh-home";
7927
- const parent = basename9(dirname7(root)).toLowerCase();
9133
+ if (samePath2(root, join19(projectRoot, ".agents", "skills"))) return "project";
9134
+ if (samePath2(root, join19(projectRoot, ".dsh", "skills"))) return "project-dsh";
9135
+ if (samePath2(root, join19(agentsHomeOf(env), "skills"))) return "shared";
9136
+ if (samePath2(root, join19(dshHomeOf(env), "skills"))) return "dsh-home";
9137
+ const parent = basename9(dirname8(root)).toLowerCase();
7928
9138
  const leaf = basename9(root).toLowerCase();
7929
9139
  if (parent === ".cursor" && leaf === "skills") return "cursor";
7930
9140
  if (parent === ".cursor" && leaf === "skills-cursor") return "cursor-builtin";
@@ -7943,7 +9153,7 @@ function normalizeRegistrySkills(raw) {
7943
9153
  const name2 = typeof row.name === "string" ? row.name.trim() : "";
7944
9154
  if (name2 === "" || seen.has(name2)) continue;
7945
9155
  seen.add(name2);
7946
- const path = typeof row.path === "string" && row.path.trim() !== "" ? resolve11(row.path.trim()) : null;
9156
+ const path = typeof row.path === "string" && row.path.trim() !== "" ? resolve12(row.path.trim()) : null;
7947
9157
  out.push({
7948
9158
  id: path !== null ? `reg:${path.toLowerCase()}` : `reg:${name2}`,
7949
9159
  name: name2,
@@ -7960,24 +9170,24 @@ function normalizeRegistrySkills(raw) {
7960
9170
  }
7961
9171
  function coerceSkillDocumentPath(path, _name) {
7962
9172
  if (path === null || path.trim() === "") return null;
7963
- const absolute = resolve11(path.trim());
7964
- if (existsSync10(absolute)) {
9173
+ const absolute = resolve12(path.trim());
9174
+ if (existsSync13(absolute)) {
7965
9175
  try {
7966
- if (statSync2(absolute).isFile()) return absolute;
9176
+ if (statSync3(absolute).isFile()) return absolute;
7967
9177
  } catch {
7968
9178
  }
7969
- const asFile = join18(absolute, "SKILL.md");
7970
- if (existsSync10(asFile)) return asFile;
9179
+ const asFile = join19(absolute, "SKILL.md");
9180
+ if (existsSync13(asFile)) return asFile;
7971
9181
  }
7972
9182
  const lower = absolute.toLowerCase();
7973
9183
  if (lower.endsWith("skill.md") || lower.endsWith(".md")) return absolute;
7974
- const nested = join18(absolute, "SKILL.md");
7975
- return existsSync10(nested) ? nested : absolute;
9184
+ const nested = join19(absolute, "SKILL.md");
9185
+ return existsSync13(nested) ? nested : absolute;
7976
9186
  }
7977
9187
  function resolveSkillPathFromRoots(name2, cwd, projectRoot, env) {
7978
9188
  for (const root of previewSkillSearchRoots(cwd, projectRoot, env)) {
7979
- const skillMd = join18(root, name2, "SKILL.md");
7980
- if (existsSync10(skillMd)) return resolve11(skillMd);
9189
+ const skillMd = join19(root, name2, "SKILL.md");
9190
+ if (existsSync13(skillMd)) return resolve12(skillMd);
7981
9191
  }
7982
9192
  return null;
7983
9193
  }
@@ -8138,22 +9348,22 @@ function parseGitSkillSource(raw) {
8138
9348
 
8139
9349
  // src/host/instructions-skills/install.ts
8140
9350
  import { execFile as execFile3, spawn } from "node:child_process";
8141
- import { existsSync as existsSync12, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
9351
+ import { existsSync as existsSync15, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
8142
9352
  import { tmpdir as tmpdir3 } from "node:os";
8143
- import { basename as basename11, dirname as dirname9, join as join22, resolve as resolve13 } from "node:path";
9353
+ import { basename as basename11, dirname as dirname10, join as join23, resolve as resolve14 } from "node:path";
8144
9354
  import { promisify as promisify3 } from "node:util";
8145
9355
 
8146
9356
  // src/host/instructions-skills/github-archive.ts
8147
9357
  import { execFile as execFile2 } from "node:child_process";
8148
9358
  import {
8149
9359
  createWriteStream,
8150
- mkdirSync as mkdirSync5,
9360
+ mkdirSync as mkdirSync6,
8151
9361
  readdirSync as readdirSync4,
8152
- renameSync as renameSync4,
9362
+ renameSync as renameSync5,
8153
9363
  rmSync as rmSync3,
8154
- statSync as statSync3
9364
+ statSync as statSync4
8155
9365
  } from "node:fs";
8156
- import { join as join19 } from "node:path";
9366
+ import { join as join20 } from "node:path";
8157
9367
  import { Readable } from "node:stream";
8158
9368
  import { pipeline } from "node:stream/promises";
8159
9369
  import { promisify as promisify2 } from "node:util";
@@ -8198,7 +9408,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
8198
9408
  }
8199
9409
  async function extractZip(zipPath, destDir, signal) {
8200
9410
  signal.throwIfAborted();
8201
- mkdirSync5(destDir, { recursive: true });
9411
+ mkdirSync6(destDir, { recursive: true });
8202
9412
  try {
8203
9413
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
8204
9414
  windowsHide: true,
@@ -8217,9 +9427,9 @@ function unwrapArchiveRoot(extractDir) {
8217
9427
  return extractDir;
8218
9428
  }
8219
9429
  if (entries.length !== 1) return extractDir;
8220
- const only = join19(extractDir, entries[0]);
9430
+ const only = join20(extractDir, entries[0]);
8221
9431
  try {
8222
- if (statSync3(only).isDirectory()) return only;
9432
+ if (statSync4(only).isDirectory()) return only;
8223
9433
  } catch {
8224
9434
  return extractDir;
8225
9435
  }
@@ -8256,10 +9466,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
8256
9466
  }
8257
9467
  async function fetchGithubRepoArchive(options) {
8258
9468
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
8259
- mkdirSync5(workDir, { recursive: true });
8260
- const zipPath = join19(workDir, "repo.zip");
8261
- const extractDir = join19(workDir, "extract");
8262
- mkdirSync5(extractDir, { recursive: true });
9469
+ mkdirSync6(workDir, { recursive: true });
9470
+ const zipPath = join20(workDir, "repo.zip");
9471
+ const extractDir = join20(workDir, "extract");
9472
+ mkdirSync6(extractDir, { recursive: true });
8263
9473
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
8264
9474
  const candidates = archiveCandidates(owner, repo, defaultBranch);
8265
9475
  const errors = [];
@@ -8270,7 +9480,7 @@ async function fetchGithubRepoArchive(options) {
8270
9480
  try {
8271
9481
  rmSync3(zipPath, { force: true });
8272
9482
  rmSync3(extractDir, { recursive: true, force: true });
8273
- mkdirSync5(extractDir, { recursive: true });
9483
+ mkdirSync6(extractDir, { recursive: true });
8274
9484
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
8275
9485
  if (!downloadStarted) {
8276
9486
  onStage?.("downloading", detail);
@@ -8282,9 +9492,9 @@ async function fetchGithubRepoArchive(options) {
8282
9492
  onStage?.("extracting", `${owner}/${repo}`);
8283
9493
  await extractZip(zipPath, extractDir, signal);
8284
9494
  const root = unwrapArchiveRoot(extractDir);
8285
- const repoDir = join19(workDir, "repo");
9495
+ const repoDir = join20(workDir, "repo");
8286
9496
  rmSync3(repoDir, { recursive: true, force: true });
8287
- renameSync4(root, repoDir);
9497
+ renameSync5(root, repoDir);
8288
9498
  try {
8289
9499
  rmSync3(zipPath, { force: true });
8290
9500
  rmSync3(extractDir, { recursive: true, force: true });
@@ -8312,18 +9522,18 @@ async function fetchGithubRepoArchive(options) {
8312
9522
  // src/host/instructions-skills/install-fs.ts
8313
9523
  import {
8314
9524
  cpSync,
8315
- existsSync as existsSync11,
9525
+ existsSync as existsSync14,
8316
9526
  lstatSync as lstatSync4,
8317
- mkdirSync as mkdirSync6,
9527
+ mkdirSync as mkdirSync7,
8318
9528
  readdirSync as readdirSync5,
8319
- readFileSync as readFileSync4,
8320
- renameSync as renameSync5,
9529
+ readFileSync as readFileSync5,
9530
+ renameSync as renameSync6,
8321
9531
  symlinkSync
8322
9532
  } from "node:fs";
8323
- import { basename as basename10, dirname as dirname8, join as join20, resolve as resolve12 } from "node:path";
9533
+ import { basename as basename10, dirname as dirname9, join as join21, resolve as resolve13 } from "node:path";
8324
9534
  function frontmatterBlock(path) {
8325
9535
  try {
8326
- const text3 = readFileSync4(path, "utf8");
9536
+ const text3 = readFileSync5(path, "utf8");
8327
9537
  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text3);
8328
9538
  return match?.[1] ?? null;
8329
9539
  } catch {
@@ -8340,13 +9550,13 @@ function nameFromSkillPath(path, fallback) {
8340
9550
  return fallback;
8341
9551
  }
8342
9552
  function directoryBundleName(dir, folderName) {
8343
- return nameFromSkillPath(join20(dir, "SKILL.md"), folderName);
9553
+ return nameFromSkillPath(join21(dir, "SKILL.md"), folderName);
8344
9554
  }
8345
9555
  function findSkillBundles(root) {
8346
- const absolute = resolve12(root);
8347
- if (!existsSync11(absolute)) return [];
8348
- const rootSkill = join20(absolute, "SKILL.md");
8349
- if (existsSync11(rootSkill)) {
9556
+ const absolute = resolve13(root);
9557
+ if (!existsSync14(absolute)) return [];
9558
+ const rootSkill = join21(absolute, "SKILL.md");
9559
+ if (existsSync14(rootSkill)) {
8350
9560
  const folderName = basename10(absolute);
8351
9561
  const name2 = directoryBundleName(absolute, folderName);
8352
9562
  if (isKebabCaseName(name2)) {
@@ -8362,8 +9572,8 @@ function findSkillBundles(root) {
8362
9572
  }
8363
9573
  for (const entry of entries) {
8364
9574
  if (isTransientSkillEntryName(entry)) continue;
8365
- const full = join20(absolute, entry);
8366
- if (existsSync11(join20(full, "SKILL.md"))) {
9575
+ const full = join21(absolute, entry);
9576
+ if (existsSync14(join21(full, "SKILL.md"))) {
8367
9577
  const name2 = directoryBundleName(full, entry);
8368
9578
  if (!isKebabCaseName(name2)) continue;
8369
9579
  out.push({ name: name2, sourcePath: full, kind: "directory" });
@@ -8384,12 +9594,12 @@ function findSkillBundles(root) {
8384
9594
  return out.sort((a, b) => a.name.localeCompare(b.name));
8385
9595
  }
8386
9596
  function resolveBundlesFromClone(cloneRoot, subpath) {
8387
- const base = subpath === null || subpath === "" ? resolve12(cloneRoot) : resolve12(cloneRoot, subpath);
8388
- if (!existsSync11(base)) {
9597
+ const base = subpath === null || subpath === "" ? resolve13(cloneRoot) : resolve13(cloneRoot, subpath);
9598
+ if (!existsSync14(base)) {
8389
9599
  throw new AuxiliaryError("FILE_NOT_FOUND", `Path not found in repository: ${subpath ?? "."}`);
8390
9600
  }
8391
- if (base.toLowerCase().endsWith("skill.md") && existsSync11(base)) {
8392
- const dir = dirname8(base);
9601
+ if (base.toLowerCase().endsWith("skill.md") && existsSync14(base)) {
9602
+ const dir = dirname9(base);
8393
9603
  const name2 = directoryBundleName(dir, basename10(dir));
8394
9604
  if (!isKebabCaseName(name2)) {
8395
9605
  throw new AuxiliaryError("FILE_DENIED", `Skill directory name must be kebab-case: ${name2}`);
@@ -8398,8 +9608,8 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
8398
9608
  }
8399
9609
  const direct = findSkillBundles(base);
8400
9610
  if (direct.length > 0) return direct;
8401
- for (const rel of ["skills", join20(".agents", "skills"), join20(".dsh", "skills")]) {
8402
- const nested = join20(base, rel);
9611
+ for (const rel of ["skills", join21(".agents", "skills"), join21(".dsh", "skills")]) {
9612
+ const nested = join21(base, rel);
8403
9613
  const found = findSkillBundles(nested);
8404
9614
  if (found.length > 0) return found;
8405
9615
  }
@@ -8408,13 +9618,13 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
8408
9618
  function installTargetDir(target, projectRoot, agentsHome, dshHome2) {
8409
9619
  switch (target) {
8410
9620
  case "user":
8411
- return join20(resolve12(agentsHome), "skills");
9621
+ return join21(resolve13(agentsHome), "skills");
8412
9622
  case "user-dsh":
8413
- return join20(resolve12(dshHome2), "skills");
9623
+ return join21(resolve13(dshHome2), "skills");
8414
9624
  case "project":
8415
- return join20(resolve12(projectRoot), ".agents", "skills");
9625
+ return join21(resolve13(projectRoot), ".agents", "skills");
8416
9626
  case "project-dsh":
8417
- return join20(resolve12(projectRoot), ".dsh", "skills");
9627
+ return join21(resolve13(projectRoot), ".dsh", "skills");
8418
9628
  default: {
8419
9629
  const _exhaustive = target;
8420
9630
  return _exhaustive;
@@ -8422,7 +9632,7 @@ function installTargetDir(target, projectRoot, agentsHome, dshHome2) {
8422
9632
  }
8423
9633
  }
8424
9634
  function destinationForBundle(targetDir, bundle) {
8425
- return bundle.kind === "directory" ? join20(targetDir, bundle.name) : join20(targetDir, `${bundle.name}.md`);
9635
+ return bundle.kind === "directory" ? join21(targetDir, bundle.name) : join21(targetDir, `${bundle.name}.md`);
8426
9636
  }
8427
9637
  function removeDestination(dest) {
8428
9638
  removePathRobust(dest);
@@ -8440,13 +9650,13 @@ function isStaleSkillDestination(dest, kind) {
8440
9650
  if (kind === "file") {
8441
9651
  try {
8442
9652
  const stat = lstatSync4(dest);
8443
- if (stat.isSymbolicLink()) return !existsSync11(dest);
9653
+ if (stat.isSymbolicLink()) return !existsSync14(dest);
8444
9654
  return !stat.isFile();
8445
9655
  } catch {
8446
9656
  return true;
8447
9657
  }
8448
9658
  }
8449
- return !existsSync11(join20(dest, "SKILL.md"));
9659
+ return !existsSync14(join21(dest, "SKILL.md"));
8450
9660
  }
8451
9661
  function copySkillTree(source, dest) {
8452
9662
  try {
@@ -8463,7 +9673,7 @@ function copySkillTree(source, dest) {
8463
9673
  }
8464
9674
  }
8465
9675
  function copySkillTreeAtomic(source, dest, kind) {
8466
- mkdirSync6(dirname8(dest), { recursive: true });
9676
+ mkdirSync7(dirname9(dest), { recursive: true });
8467
9677
  if (kind === "file") {
8468
9678
  if (destinationPresent(dest)) removeDestination(dest);
8469
9679
  copySkillTree(source, dest);
@@ -8477,7 +9687,7 @@ function copySkillTreeAtomic(source, dest, kind) {
8477
9687
  throw new AuxiliaryError("FILE_EDIT_FAILED", busyPathHint(basename10(dest)));
8478
9688
  }
8479
9689
  try {
8480
- renameSync5(staging, dest);
9690
+ renameSync6(staging, dest);
8481
9691
  } catch (error) {
8482
9692
  if (isWindowsPathBusyError(error)) {
8483
9693
  throw new AuxiliaryError("FILE_EDIT_FAILED", busyPathHint(basename10(dest)));
@@ -8491,7 +9701,7 @@ function copySkillTreeAtomic(source, dest, kind) {
8491
9701
  }
8492
9702
  }
8493
9703
  function linkOrCopy(source, dest, mode, kind) {
8494
- mkdirSync6(dirname8(dest), { recursive: true });
9704
+ mkdirSync7(dirname9(dest), { recursive: true });
8495
9705
  if (mode === "copy") {
8496
9706
  copySkillTreeAtomic(source, dest, kind);
8497
9707
  return "copy";
@@ -8499,7 +9709,7 @@ function linkOrCopy(source, dest, mode, kind) {
8499
9709
  try {
8500
9710
  if (process.platform === "win32") {
8501
9711
  const stat = lstatSync4(source);
8502
- if (stat.isDirectory() || stat.isSymbolicLink() && existsSync11(join20(source, "SKILL.md"))) {
9712
+ if (stat.isDirectory() || stat.isSymbolicLink() && existsSync14(join21(source, "SKILL.md"))) {
8503
9713
  symlinkSync(source, dest, "junction");
8504
9714
  return "link";
8505
9715
  }
@@ -8529,13 +9739,13 @@ function installBundle(options) {
8529
9739
 
8530
9740
  // src/host/instructions-skills/content-revision.ts
8531
9741
  import { createHash as createHash7 } from "node:crypto";
8532
- import { readdirSync as readdirSync6, readFileSync as readFileSync5 } from "node:fs";
8533
- import { join as join21, relative as relative3 } from "node:path";
9742
+ import { readdirSync as readdirSync6, readFileSync as readFileSync6 } from "node:fs";
9743
+ import { join as join22, relative as relative3 } from "node:path";
8534
9744
  function listRelativeFiles(dir, root) {
8535
9745
  const entries = [];
8536
9746
  for (const entry of readdirSync6(dir, { withFileTypes: true })) {
8537
9747
  if (entry.name.startsWith(".")) continue;
8538
- const abs = join21(dir, entry.name);
9748
+ const abs = join22(dir, entry.name);
8539
9749
  if (entry.isDirectory()) {
8540
9750
  entries.push(...listRelativeFiles(abs, root));
8541
9751
  } else if (entry.isFile()) {
@@ -8548,7 +9758,7 @@ function contentRevisionOfDir(dir) {
8548
9758
  const paths = listRelativeFiles(dir, dir).sort();
8549
9759
  const aggregate = createHash7("sha256");
8550
9760
  for (const relPath of paths) {
8551
- const contents = readFileSync5(join21(dir, relPath));
9761
+ const contents = readFileSync6(join22(dir, relPath));
8552
9762
  const fileDigest = createHash7("sha256").update(`${relPath}\0`).update(contents).digest();
8553
9763
  aggregate.update(fileDigest);
8554
9764
  }
@@ -8657,7 +9867,7 @@ function tempWorkDir(prefix) {
8657
9867
  base = realpathSync(base);
8658
9868
  } catch {
8659
9869
  }
8660
- return mkdtempSync(join22(base, prefix));
9870
+ return mkdtempSync(join23(base, prefix));
8661
9871
  }
8662
9872
  function execDetail(error) {
8663
9873
  if (!(error instanceof Error)) return String(error);
@@ -8759,7 +9969,7 @@ async function materializeSkillGitTreeFromSource(source, workDir, signal, progre
8759
9969
  return { rootDir, parsed };
8760
9970
  }
8761
9971
  async function materializeRepo(parsed, workDir, signal, progressSessionId) {
8762
- const cloneDir = join22(workDir, "repo");
9972
+ const cloneDir = join23(workDir, "repo");
8763
9973
  const archiveErrors = [];
8764
9974
  const sessionId = progressSessionId?.trim() ?? "";
8765
9975
  if (parsed.github !== null) {
@@ -8900,14 +10110,14 @@ async function installSkillsFromGit(options) {
8900
10110
  // src/host/instructions-skills/update-check.ts
8901
10111
  import { mkdtempSync as mkdtempSync2, realpathSync as realpathSync2, rmSync as rmSync5 } from "node:fs";
8902
10112
  import { tmpdir as tmpdir4 } from "node:os";
8903
- import { join as join23 } from "node:path";
10113
+ import { join as join24 } from "node:path";
8904
10114
  function tempWorkDir2(prefix) {
8905
10115
  let base = tmpdir4();
8906
10116
  try {
8907
10117
  base = realpathSync2(base);
8908
10118
  } catch {
8909
10119
  }
8910
- return mkdtempSync2(join23(base, prefix));
10120
+ return mkdtempSync2(join24(base, prefix));
8911
10121
  }
8912
10122
  function revisionPathForBundle(bundle) {
8913
10123
  return bundle.kind === "directory" ? bundle.sourcePath : bundle.sourcePath;
@@ -8966,9 +10176,9 @@ async function checkGithubSkillUpdate(record2, options) {
8966
10176
 
8967
10177
  // src/host/instructions-skills/zip-install.ts
8968
10178
  import { execFile as execFile4 } from "node:child_process";
8969
- import { existsSync as existsSync13, mkdirSync as mkdirSync7, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
10179
+ import { existsSync as existsSync16, mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
8970
10180
  import { tmpdir as tmpdir5 } from "node:os";
8971
- import { basename as basename12, join as join24, resolve as resolve14 } from "node:path";
10181
+ import { basename as basename12, join as join25, resolve as resolve15 } from "node:path";
8972
10182
  import { promisify as promisify4 } from "node:util";
8973
10183
  var execFileAsync4 = promisify4(execFile4);
8974
10184
  function tempWorkDir3(prefix) {
@@ -8977,11 +10187,11 @@ function tempWorkDir3(prefix) {
8977
10187
  base = realpathSync3(base);
8978
10188
  } catch {
8979
10189
  }
8980
- return mkdtempSync3(join24(base, prefix));
10190
+ return mkdtempSync3(join25(base, prefix));
8981
10191
  }
8982
10192
  async function extractZipArchive(zipPath, destDir, signal) {
8983
10193
  signal.throwIfAborted();
8984
- mkdirSync7(destDir, { recursive: true });
10194
+ mkdirSync8(destDir, { recursive: true });
8985
10195
  try {
8986
10196
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
8987
10197
  windowsHide: true,
@@ -8994,15 +10204,15 @@ async function extractZipArchive(zipPath, destDir, signal) {
8994
10204
  signal.throwIfAborted();
8995
10205
  }
8996
10206
  async function installSkillsFromZipFile(options) {
8997
- const zipPath = resolve14(options.zipPath);
8998
- if (!existsSync13(zipPath)) {
10207
+ const zipPath = resolve15(options.zipPath);
10208
+ if (!existsSync16(zipPath)) {
8999
10209
  throw new AuxiliaryError("FILE_NOT_FOUND", `Zip not found: ${zipPath}`);
9000
10210
  }
9001
10211
  if (!zipPath.toLowerCase().endsWith(".zip")) {
9002
10212
  throw new AuxiliaryError("FILE_DENIED", `Expected a .zip archive: ${basename12(zipPath)}`);
9003
10213
  }
9004
10214
  const workDir = tempWorkDir3("ae-skill-zip-");
9005
- const extractDir = join24(workDir, "extract");
10215
+ const extractDir = join25(workDir, "extract");
9006
10216
  try {
9007
10217
  await extractZipArchive(zipPath, extractDir, options.signal);
9008
10218
  const root = unwrapArchiveRoot(extractDir);
@@ -9067,11 +10277,11 @@ async function installSkillsFromZipFile(options) {
9067
10277
  // src/host/instructions-skills/io.ts
9068
10278
  function sessionCwd3(session) {
9069
10279
  const header = session?.header;
9070
- if (typeof header?.cwd === "string" && header.cwd.trim() !== "") return resolve15(header.cwd);
10280
+ if (typeof header?.cwd === "string" && header.cwd.trim() !== "") return resolve16(header.cwd);
9071
10281
  try {
9072
10282
  const requested = session?.requestHeader?.();
9073
10283
  if (typeof requested?.cwd === "string" && requested.cwd.trim() !== "") {
9074
- return resolve15(requested.cwd);
10284
+ return resolve16(requested.cwd);
9075
10285
  }
9076
10286
  } catch {
9077
10287
  }
@@ -9165,12 +10375,12 @@ async function enrichSkillsFromLedger(skills, options) {
9165
10375
  }
9166
10376
  function inferSkillInstallTarget(name2, cwd, projectRoot, env = process.env) {
9167
10377
  const roots = skillRootsFor(cwd, projectRoot, env);
9168
- const projectAgents = join25(resolve15(projectRoot), ".agents", "skills");
9169
- const projectDsh = join25(resolve15(projectRoot), ".dsh", "skills");
9170
- const userAgents = join25(agentsHomeOf(env), "skills");
9171
- const userDsh = join25(dshHomeOf(env), "skills");
10378
+ const projectAgents = join26(resolve16(projectRoot), ".agents", "skills");
10379
+ const projectDsh = join26(resolve16(projectRoot), ".dsh", "skills");
10380
+ const userAgents = join26(agentsHomeOf(env), "skills");
10381
+ const userDsh = join26(dshHomeOf(env), "skills");
9172
10382
  for (const root of roots) {
9173
- const present = existsSync14(join25(root, name2, "SKILL.md")) || existsSync14(join25(root, `${name2}.md`));
10383
+ const present = existsSync17(join26(root, name2, "SKILL.md")) || existsSync17(join26(root, `${name2}.md`));
9174
10384
  if (!present) continue;
9175
10385
  if (samePath2(root, projectAgents)) return "project";
9176
10386
  if (samePath2(root, projectDsh)) return "project-dsh";
@@ -9178,7 +10388,7 @@ function inferSkillInstallTarget(name2, cwd, projectRoot, env = process.env) {
9178
10388
  if (samePath2(root, userDsh)) return "user-dsh";
9179
10389
  const normalized = root.toLowerCase().split(/[/\\]/).join(sep7);
9180
10390
  const dshMarker = `${sep7}.dsh${sep7}skills`;
9181
- const underProject = isInsideOrSame(resolve15(projectRoot), root);
10391
+ const underProject = isInsideOrSame(resolve16(projectRoot), root);
9182
10392
  if (normalized.includes(dshMarker) || normalized.endsWith(`${sep7}.dsh${sep7}skills`)) {
9183
10393
  return underProject ? "project-dsh" : "user-dsh";
9184
10394
  }
@@ -9391,8 +10601,8 @@ async function updateSkillFromGitNow(options) {
9391
10601
  }
9392
10602
  function skillDocumentAbsolutePath(path) {
9393
10603
  const trimmed = path.replace(/[/\\]+$/, "");
9394
- if (/\.md$/i.test(trimmed)) return resolve15(trimmed);
9395
- return resolve15(trimmed, "SKILL.md");
10604
+ if (/\.md$/i.test(trimmed)) return resolve16(trimmed);
10605
+ return resolve16(trimmed, "SKILL.md");
9396
10606
  }
9397
10607
  async function readSkillDocumentNow(options) {
9398
10608
  options.signal.throwIfAborted();
@@ -9408,11 +10618,11 @@ async function readSkillDocumentNow(options) {
9408
10618
  throw new AuxiliaryError("FILE_DENIED", "Only SKILL.md may be previewed");
9409
10619
  }
9410
10620
  options.signal.throwIfAborted();
9411
- if (!existsSync14(absolutePath2)) {
10621
+ if (!existsSync17(absolutePath2)) {
9412
10622
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
9413
10623
  }
9414
10624
  try {
9415
- const stat = statSync4(absolutePath2);
10625
+ const stat = statSync5(absolutePath2);
9416
10626
  if (!stat.isFile()) {
9417
10627
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
9418
10628
  }
@@ -9426,7 +10636,7 @@ async function readSkillDocumentNow(options) {
9426
10636
  options.signal.throwIfAborted();
9427
10637
  let text3;
9428
10638
  try {
9429
- text3 = readFileSync6(absolutePath2, "utf8");
10639
+ text3 = readFileSync7(absolutePath2, "utf8");
9430
10640
  } catch {
9431
10641
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
9432
10642
  }
@@ -9443,7 +10653,7 @@ async function readSkillDocumentNow(options) {
9443
10653
  }
9444
10654
 
9445
10655
  // src/host/mcp-connectors/io.ts
9446
- import { existsSync as existsSync16 } from "node:fs";
10656
+ import { existsSync as existsSync19 } from "node:fs";
9447
10657
 
9448
10658
  // src/host/mcp-connectors/validate.ts
9449
10659
  var MCP_SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
@@ -9565,22 +10775,22 @@ function parseMcpJsonText(jsonText) {
9565
10775
  }
9566
10776
 
9567
10777
  // src/host/mcp-connectors/install-git.ts
9568
- import { existsSync as existsSync15, mkdirSync as mkdirSync8, readFileSync as readFileSync7, renameSync as renameSync6, rmSync as rmSync7 } from "node:fs";
9569
- import { join as join27 } from "node:path";
10778
+ import { existsSync as existsSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
10779
+ import { join as join28 } from "node:path";
9570
10780
 
9571
10781
  // src/host/mcp-connectors/paths.ts
9572
- import { join as join26 } from "node:path";
10782
+ import { join as join27 } from "node:path";
9573
10783
  function mcpConnectorsRoot(pluginDataPackageRoot) {
9574
- return join26(pluginDataPackageRoot, "mcp-connectors");
10784
+ return join27(pluginDataPackageRoot, "mcp-connectors");
9575
10785
  }
9576
10786
  function mcpConnectorsLedgerPath(root) {
9577
- return join26(root, "mcp-connectors.json");
10787
+ return join27(root, "mcp-connectors.json");
9578
10788
  }
9579
10789
  function mcpServersRoot(root) {
9580
- return join26(root, "mcp-servers");
10790
+ return join27(root, "mcp-servers");
9581
10791
  }
9582
10792
  function mcpServerInstallDir(root, id) {
9583
- return join26(mcpServersRoot(root), id);
10793
+ return join27(mcpServersRoot(root), id);
9584
10794
  }
9585
10795
 
9586
10796
  // src/host/mcp-connectors/install-git.ts
@@ -9597,8 +10807,8 @@ function inferStdioFromPackageJson(installDir, override) {
9597
10807
  cwd: installDir
9598
10808
  };
9599
10809
  }
9600
- const pkgPath = join27(installDir, "package.json");
9601
- if (!existsSync15(pkgPath)) {
10810
+ const pkgPath = join28(installDir, "package.json");
10811
+ if (!existsSync18(pkgPath)) {
9602
10812
  return {
9603
10813
  transport: "stdio",
9604
10814
  command: "npx",
@@ -9608,14 +10818,14 @@ function inferStdioFromPackageJson(installDir, override) {
9608
10818
  };
9609
10819
  }
9610
10820
  try {
9611
- const pkg = JSON.parse(readFileSync7(pkgPath, "utf8"));
10821
+ const pkg = JSON.parse(readFileSync8(pkgPath, "utf8"));
9612
10822
  if (isRecord4(pkg)) {
9613
10823
  const bin = pkg.bin;
9614
10824
  if (typeof bin === "string" && bin.trim() !== "") {
9615
10825
  return {
9616
10826
  transport: "stdio",
9617
10827
  command: process.execPath,
9618
- args: [join27(installDir, bin)],
10828
+ args: [join28(installDir, bin)],
9619
10829
  env: {},
9620
10830
  cwd: installDir
9621
10831
  };
@@ -9628,7 +10838,7 @@ function inferStdioFromPackageJson(installDir, override) {
9628
10838
  return {
9629
10839
  transport: "stdio",
9630
10840
  command: process.execPath,
9631
- args: [join27(installDir, first)],
10841
+ args: [join28(installDir, first)],
9632
10842
  env: {},
9633
10843
  cwd: installDir
9634
10844
  };
@@ -9638,7 +10848,7 @@ function inferStdioFromPackageJson(installDir, override) {
9638
10848
  return {
9639
10849
  transport: "stdio",
9640
10850
  command: process.execPath,
9641
- args: [join27(installDir, pkg.main)],
10851
+ args: [join28(installDir, pkg.main)],
9642
10852
  env: {},
9643
10853
  cwd: installDir
9644
10854
  };
@@ -9657,17 +10867,17 @@ function inferStdioFromPackageJson(installDir, override) {
9657
10867
  async function installMcpServerFromGit(options) {
9658
10868
  const parsed = parseGitSkillSource(options.source);
9659
10869
  const installDir = mcpServerInstallDir(options.rootDir, options.id);
9660
- if (existsSync15(installDir)) {
10870
+ if (existsSync18(installDir)) {
9661
10871
  if (!options.force) {
9662
10872
  throw new AuxiliaryError("FILE_EDIT_FAILED", `MCP install dir already exists: ${installDir}`);
9663
10873
  }
9664
10874
  removePathRobust(installDir);
9665
10875
  }
9666
- mkdirSync8(join27(options.rootDir, "mcp-servers"), { recursive: true });
10876
+ mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
9667
10877
  const staging = `${installDir}.staging.${process.pid}`;
9668
10878
  try {
9669
- if (existsSync15(staging)) removePathRobust(staging);
9670
- mkdirSync8(staging, { recursive: true });
10879
+ if (existsSync18(staging)) removePathRobust(staging);
10880
+ mkdirSync9(staging, { recursive: true });
9671
10881
  if (parsed.github === null) {
9672
10882
  throw new AuxiliaryError(
9673
10883
  "FILE_EDIT_FAILED",
@@ -9683,20 +10893,20 @@ async function installMcpServerFromGit(options) {
9683
10893
  options.signal.throwIfAborted();
9684
10894
  let contentRoot = repoDir;
9685
10895
  if (parsed.subpath !== null) {
9686
- const nested = join27(repoDir, parsed.subpath);
9687
- if (!existsSync15(nested)) {
10896
+ const nested = join28(repoDir, parsed.subpath);
10897
+ if (!existsSync18(nested)) {
9688
10898
  throw new AuxiliaryError("FILE_EDIT_FAILED", `Subpath not found in repo: ${parsed.subpath}`);
9689
10899
  }
9690
10900
  contentRoot = nested;
9691
10901
  }
9692
- mkdirSync8(join27(options.rootDir, "mcp-servers"), { recursive: true });
10902
+ mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
9693
10903
  if (contentRoot !== repoDir) {
9694
10904
  const nestedStaging = `${installDir}.nested.${process.pid}`;
9695
- renameSync6(contentRoot, nestedStaging);
10905
+ renameSync7(contentRoot, nestedStaging);
9696
10906
  removePathRobust(staging);
9697
- renameSync6(nestedStaging, installDir);
10907
+ renameSync7(nestedStaging, installDir);
9698
10908
  } else {
9699
- renameSync6(repoDir, installDir);
10909
+ renameSync7(repoDir, installDir);
9700
10910
  try {
9701
10911
  removePathRobust(staging);
9702
10912
  } catch {
@@ -9704,11 +10914,11 @@ async function installMcpServerFromGit(options) {
9704
10914
  }
9705
10915
  } catch (error) {
9706
10916
  try {
9707
- if (existsSync15(staging)) rmSync7(staging, { recursive: true, force: true });
10917
+ if (existsSync18(staging)) rmSync7(staging, { recursive: true, force: true });
9708
10918
  } catch {
9709
10919
  }
9710
10920
  try {
9711
- if (existsSync15(installDir)) removePathRobust(installDir);
10921
+ if (existsSync18(installDir)) removePathRobust(installDir);
9712
10922
  } catch {
9713
10923
  }
9714
10924
  if (error instanceof AuxiliaryError) throw error;
@@ -9806,7 +11016,7 @@ async function uninstallMcpConnectorNow(host, request) {
9806
11016
  }
9807
11017
  const next = doc.connectors.filter((entry) => entry.id !== request.id);
9808
11018
  const installDir = mcpServerInstallDir(host.store.rootDir, request.id);
9809
- if (existsSync16(installDir)) {
11019
+ if (existsSync19(installDir)) {
9810
11020
  try {
9811
11021
  removePathRobust(installDir);
9812
11022
  } catch (error) {
@@ -9938,8 +11148,8 @@ function listMcpConnectorToolsNow(host, request) {
9938
11148
  }
9939
11149
 
9940
11150
  // src/host/mcp-connectors/store.ts
9941
- import { mkdirSync as mkdirSync9, readFileSync as readFileSync8, renameSync as renameSync7, writeFileSync as writeFileSync4 } from "node:fs";
9942
- import { dirname as dirname10 } from "node:path";
11151
+ import { mkdirSync as mkdirSync10, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
11152
+ import { dirname as dirname11 } from "node:path";
9943
11153
 
9944
11154
  // src/host/mcp-connectors/types.ts
9945
11155
  var MCP_CONNECTORS_VERSION = 1;
@@ -10021,13 +11231,13 @@ function parseDoc2(raw) {
10021
11231
  }
10022
11232
  }
10023
11233
  function createMcpConnectorsStore(rootDir) {
10024
- mkdirSync9(rootDir, { recursive: true });
11234
+ mkdirSync10(rootDir, { recursive: true });
10025
11235
  const file = mcpConnectorsLedgerPath(rootDir);
10026
11236
  return {
10027
11237
  rootDir,
10028
11238
  load() {
10029
11239
  try {
10030
- return parseDoc2(readFileSync8(file, "utf8"));
11240
+ return parseDoc2(readFileSync9(file, "utf8"));
10031
11241
  } catch (error) {
10032
11242
  const code = error !== null && typeof error === "object" ? String(Reflect.get(error, "code") ?? "") : "";
10033
11243
  if (code !== "ENOENT") {
@@ -10040,11 +11250,11 @@ function createMcpConnectorsStore(rootDir) {
10040
11250
  version: MCP_CONNECTORS_VERSION,
10041
11251
  connectors: [...connectors]
10042
11252
  };
10043
- mkdirSync9(dirname10(file), { recursive: true });
11253
+ mkdirSync10(dirname11(file), { recursive: true });
10044
11254
  const tmp = `${file}.${process.pid}.tmp`;
10045
- writeFileSync4(tmp, `${JSON.stringify(doc, null, 2)}
11255
+ writeFileSync5(tmp, `${JSON.stringify(doc, null, 2)}
10046
11256
  `, "utf8");
10047
- renameSync7(tmp, file);
11257
+ renameSync8(tmp, file);
10048
11258
  return doc;
10049
11259
  }
10050
11260
  };
@@ -10726,7 +11936,7 @@ var SoftPauseGate = class {
10726
11936
  this.clear(sessionId);
10727
11937
  return;
10728
11938
  }
10729
- await new Promise((resolve16) => {
11939
+ await new Promise((resolve17) => {
10730
11940
  let settled = false;
10731
11941
  const settle = () => {
10732
11942
  if (settled) return;
@@ -10737,7 +11947,7 @@ var SoftPauseGate = class {
10737
11947
  bucket2.delete(waiter);
10738
11948
  if (bucket2.size === 0) this.waiters.delete(sessionId);
10739
11949
  }
10740
- resolve16();
11950
+ resolve17();
10741
11951
  };
10742
11952
  const onAbort = () => {
10743
11953
  this.engaged.delete(sessionId);
@@ -11949,9 +13159,9 @@ function mergeUsageCalls(stored, history) {
11949
13159
  }
11950
13160
 
11951
13161
  // src/host/usage/ledger.ts
11952
- import { randomUUID as randomUUID6 } from "node:crypto";
13162
+ import { randomUUID as randomUUID7 } from "node:crypto";
11953
13163
  import { chmod as chmod4, mkdir as mkdir5, readFile as readFile5, rename as rename4, unlink as unlink5, writeFile as writeFile4 } from "node:fs/promises";
11954
- import { basename as basename14, join as join28 } from "node:path";
13164
+ import { basename as basename14, join as join29 } from "node:path";
11955
13165
  import { z as z3 } from "zod";
11956
13166
  var callSchema = z3.object({
11957
13167
  at: z3.number().int().nonnegative(),
@@ -11981,7 +13191,7 @@ async function removeIfPresent5(path) {
11981
13191
  }
11982
13192
  }
11983
13193
  async function writeAtomic4(path, value) {
11984
- const temporary = join28(join28(path, ".."), `.${basename14(path)}.${randomUUID6()}.tmp`);
13194
+ const temporary = join29(join29(path, ".."), `.${basename14(path)}.${randomUUID7()}.tmp`);
11985
13195
  try {
11986
13196
  await writeFile4(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
11987
13197
  await rename4(temporary, path);
@@ -11995,7 +13205,7 @@ var UsageLedger = class {
11995
13205
  }) {
11996
13206
  this.root = root;
11997
13207
  this.warn = warn;
11998
- this.file = join28(root, "ledger.json");
13208
+ this.file = join29(root, "ledger.json");
11999
13209
  }
12000
13210
  root;
12001
13211
  warn;
@@ -12280,6 +13490,156 @@ var deleteSessionResultSchema = z4.strictObject({
12280
13490
  });
12281
13491
  var deleteSessionRequestCodec = codec("dsh-agent-enhancer#DeleteSessionRequest", deleteSessionRequestSchema);
12282
13492
  var deleteSessionResultCodec = codec("dsh-agent-enhancer#DeleteSessionResult", deleteSessionResultSchema);
13493
+ var webChatTurnSchema = z4.strictObject({
13494
+ role: z4.enum(["user", "assistant"]),
13495
+ text: z4.string()
13496
+ });
13497
+ var webChatTranscriptSchema = z4.strictObject({
13498
+ title: z4.string(),
13499
+ partial: z4.boolean(),
13500
+ turns: z4.array(webChatTurnSchema).min(1),
13501
+ source: z4.strictObject({
13502
+ kind: z4.enum(["rendered-capture", "official-export", "share-link", "account-history"]),
13503
+ url: z4.string().optional(),
13504
+ chatSessionId: z4.string().optional(),
13505
+ capturedAt: z4.string(),
13506
+ filename: z4.string().optional()
13507
+ })
13508
+ });
13509
+ var listWebChatWorkspacesRequestSchema = z4.strictObject({});
13510
+ var listWebChatWorkspacesResultSchema = z4.strictObject({
13511
+ items: z4.array(z4.strictObject({
13512
+ id: z4.string(),
13513
+ title: z4.string(),
13514
+ cwd: z4.string()
13515
+ }))
13516
+ });
13517
+ var createWebChatWorkspaceRequestSchema = z4.strictObject({});
13518
+ var createWebChatWorkspaceResultSchema = z4.strictObject({
13519
+ cancelled: z4.boolean(),
13520
+ workspace: z4.strictObject({
13521
+ id: z4.string(),
13522
+ title: z4.string(),
13523
+ cwd: z4.string()
13524
+ }).nullable()
13525
+ });
13526
+ var importWebChatHistoryRequestSchema = z4.strictObject({
13527
+ workspaceId: z4.string().min(1),
13528
+ transcript: webChatTranscriptSchema
13529
+ });
13530
+ var importWebChatHistoryResultSchema = z4.strictObject({
13531
+ sessionId: sessionIdSchema3
13532
+ });
13533
+ var parseWebChatExportRequestSchema = z4.strictObject({
13534
+ filename: z4.string().min(1),
13535
+ bytesBase64: z4.string().min(1)
13536
+ });
13537
+ var webChatExportCatalogItemSchema = z4.strictObject({
13538
+ id: z4.string().min(1),
13539
+ title: z4.string(),
13540
+ turnCount: z4.number().int().nonnegative(),
13541
+ preview: z4.string(),
13542
+ transcript: webChatTranscriptSchema.optional()
13543
+ });
13544
+ var parseWebChatExportResultSchema = z4.strictObject({
13545
+ items: z4.array(webChatExportCatalogItemSchema).min(1),
13546
+ truncated: z4.boolean()
13547
+ });
13548
+ var resolveWebChatShareLinkRequestSchema = z4.strictObject({
13549
+ shareUrl: z4.string().min(1),
13550
+ /** Optional guest-fetched JSON string; when set, Host skips network fetch. */
13551
+ payloadJson: z4.string().optional()
13552
+ });
13553
+ var resolveWebChatShareLinkResultSchema = z4.strictObject({
13554
+ transcript: webChatTranscriptSchema
13555
+ });
13556
+ var listWebChatWorkspacesRequestCodec = codec(
13557
+ "dsh-agent-enhancer#ListWebChatWorkspacesRequest",
13558
+ listWebChatWorkspacesRequestSchema
13559
+ );
13560
+ var listWebChatWorkspacesResultCodec = codec(
13561
+ "dsh-agent-enhancer#ListWebChatWorkspacesResult",
13562
+ listWebChatWorkspacesResultSchema
13563
+ );
13564
+ var createWebChatWorkspaceRequestCodec = codec(
13565
+ "dsh-agent-enhancer#CreateWebChatWorkspaceRequest",
13566
+ createWebChatWorkspaceRequestSchema
13567
+ );
13568
+ var createWebChatWorkspaceResultCodec = codec(
13569
+ "dsh-agent-enhancer#CreateWebChatWorkspaceResult",
13570
+ createWebChatWorkspaceResultSchema
13571
+ );
13572
+ var importWebChatHistoryRequestCodec = codec(
13573
+ "dsh-agent-enhancer#ImportWebChatHistoryRequest",
13574
+ importWebChatHistoryRequestSchema
13575
+ );
13576
+ var importWebChatHistoryResultCodec = codec(
13577
+ "dsh-agent-enhancer#ImportWebChatHistoryResult",
13578
+ importWebChatHistoryResultSchema
13579
+ );
13580
+ var parseWebChatExportRequestCodec = codec(
13581
+ "dsh-agent-enhancer#ParseWebChatExportRequest",
13582
+ parseWebChatExportRequestSchema
13583
+ );
13584
+ var parseWebChatExportResultCodec = codec(
13585
+ "dsh-agent-enhancer#ParseWebChatExportResult",
13586
+ parseWebChatExportResultSchema
13587
+ );
13588
+ var resolveWebChatShareLinkRequestCodec = codec(
13589
+ "dsh-agent-enhancer#ResolveWebChatShareLinkRequest",
13590
+ resolveWebChatShareLinkRequestSchema
13591
+ );
13592
+ var resolveWebChatShareLinkResultCodec = codec(
13593
+ "dsh-agent-enhancer#ResolveWebChatShareLinkResult",
13594
+ resolveWebChatShareLinkResultSchema
13595
+ );
13596
+ var webChatLoginSnapshotSchema = z4.strictObject({
13597
+ version: z4.literal(1),
13598
+ origin: z4.string(),
13599
+ localStorage: z4.record(z4.string(), z4.string()),
13600
+ cookie: z4.string(),
13601
+ savedAt: z4.string()
13602
+ });
13603
+ var loadWebChatLoginSnapshotRequestSchema = z4.strictObject({});
13604
+ var loadWebChatLoginSnapshotResultSchema = z4.strictObject({
13605
+ snapshot: webChatLoginSnapshotSchema.nullable()
13606
+ });
13607
+ var saveWebChatLoginSnapshotRequestSchema = z4.strictObject({
13608
+ localStorage: z4.record(z4.string(), z4.string()),
13609
+ cookie: z4.string(),
13610
+ savedAt: z4.string()
13611
+ });
13612
+ var saveWebChatLoginSnapshotResultSchema = z4.strictObject({
13613
+ ok: z4.literal(true)
13614
+ });
13615
+ var clearWebChatLoginSnapshotRequestSchema = z4.strictObject({});
13616
+ var clearWebChatLoginSnapshotResultSchema = z4.strictObject({
13617
+ cleared: z4.boolean()
13618
+ });
13619
+ var loadWebChatLoginSnapshotRequestCodec = codec(
13620
+ "dsh-agent-enhancer#LoadWebChatLoginSnapshotRequest",
13621
+ loadWebChatLoginSnapshotRequestSchema
13622
+ );
13623
+ var loadWebChatLoginSnapshotResultCodec = codec(
13624
+ "dsh-agent-enhancer#LoadWebChatLoginSnapshotResult",
13625
+ loadWebChatLoginSnapshotResultSchema
13626
+ );
13627
+ var saveWebChatLoginSnapshotRequestCodec = codec(
13628
+ "dsh-agent-enhancer#SaveWebChatLoginSnapshotRequest",
13629
+ saveWebChatLoginSnapshotRequestSchema
13630
+ );
13631
+ var saveWebChatLoginSnapshotResultCodec = codec(
13632
+ "dsh-agent-enhancer#SaveWebChatLoginSnapshotResult",
13633
+ saveWebChatLoginSnapshotResultSchema
13634
+ );
13635
+ var clearWebChatLoginSnapshotRequestCodec = codec(
13636
+ "dsh-agent-enhancer#ClearWebChatLoginSnapshotRequest",
13637
+ clearWebChatLoginSnapshotRequestSchema
13638
+ );
13639
+ var clearWebChatLoginSnapshotResultCodec = codec(
13640
+ "dsh-agent-enhancer#ClearWebChatLoginSnapshotResult",
13641
+ clearWebChatLoginSnapshotResultSchema
13642
+ );
12283
13643
  var readWorkspaceFileRequestSchema = z4.strictObject({
12284
13644
  sessionId: sessionIdSchema3,
12285
13645
  path: z4.string().min(1)
@@ -12563,10 +13923,10 @@ var browserAgentAuditEntrySchema = z4.strictObject({
12563
13923
  });
12564
13924
  var browserAgentSnapshotSchema = z4.strictObject({
12565
13925
  enabled: z4.boolean(),
12566
- /** Settings preference (auto / chrome / edge). */
12567
- browser: z4.enum(["auto", "chrome", "edge"]),
13926
+ /** Settings preference (auto / chrome / edge / safari). */
13927
+ browser: z4.enum(["auto", "chrome", "edge", "safari"]),
12568
13928
  /** Actually launched channel once ready; null when not running. */
12569
- launchedBrowser: z4.enum(["chrome", "edge"]).nullable(),
13929
+ launchedBrowser: z4.enum(["chrome", "edge", "safari"]).nullable(),
12570
13930
  /** Shipping driver (Playwright only after MV3 retirement). */
12571
13931
  driver: z4.literal("playwright"),
12572
13932
  allowedOrigins: z4.array(z4.string()),
@@ -12674,7 +14034,7 @@ var browserAgentQuotePageResultCodec = codec(
12674
14034
  browserAgentQuotePageResultSchema
12675
14035
  );
12676
14036
  var browserAgentLaunchBrowserRequestSchema = z4.strictObject({
12677
- browser: z4.enum(["auto", "chrome", "edge"]).optional()
14037
+ browser: z4.enum(["auto", "chrome", "edge", "safari"]).optional()
12678
14038
  });
12679
14039
  var browserAgentLaunchBrowserRequestCodec = codec(
12680
14040
  "dsh-agent-enhancer#BrowserAgentLaunchBrowserRequest",
@@ -12682,7 +14042,7 @@ var browserAgentLaunchBrowserRequestCodec = codec(
12682
14042
  );
12683
14043
  var browserAgentLaunchBrowserResultSchema = z4.strictObject({
12684
14044
  ok: z4.boolean(),
12685
- browser: z4.enum(["chrome", "edge"]).optional(),
14045
+ browser: z4.enum(["chrome", "edge", "safari"]).optional(),
12686
14046
  executable: z4.string().optional(),
12687
14047
  profileDir: z4.string().min(1),
12688
14048
  error: z4.string().optional(),
@@ -12693,7 +14053,7 @@ var browserAgentLaunchBrowserResultCodec = codec(
12693
14053
  browserAgentLaunchBrowserResultSchema
12694
14054
  );
12695
14055
  var browserAgentSetBrowserRequestSchema = z4.strictObject({
12696
- browser: z4.enum(["auto", "chrome", "edge"])
14056
+ browser: z4.enum(["auto", "chrome", "edge", "safari"])
12697
14057
  });
12698
14058
  var browserAgentSetBrowserRequestCodec = codec(
12699
14059
  "dsh-agent-enhancer#BrowserAgentSetBrowserRequest",
@@ -12701,7 +14061,7 @@ var browserAgentSetBrowserRequestCodec = codec(
12701
14061
  );
12702
14062
  var browserAgentSetBrowserResultSchema = z4.strictObject({
12703
14063
  ok: z4.boolean(),
12704
- browser: z4.enum(["auto", "chrome", "edge"]),
14064
+ browser: z4.enum(["auto", "chrome", "edge", "safari"]),
12705
14065
  snapshot: browserAgentSnapshotSchema
12706
14066
  });
12707
14067
  var browserAgentSetBrowserResultCodec = codec(
@@ -13611,6 +14971,110 @@ var remoteInfo = createTypertRemoteInfo({
13611
14971
  }],
13612
14972
  cancellation: { parameter: "signal" },
13613
14973
  result: listMcpConnectorToolsResultCodec
14974
+ },
14975
+ "agentEnhancer/listWebChatWorkspaces": {
14976
+ service: "agentEnhancer",
14977
+ implementation: "listWebChatWorkspaces",
14978
+ invocation: { kind: "direct" },
14979
+ parameters: [{
14980
+ name: "request",
14981
+ source: "json",
14982
+ codec: listWebChatWorkspacesRequestCodec,
14983
+ strictCodec: listWebChatWorkspacesRequestCodec
14984
+ }],
14985
+ cancellation: { parameter: "signal" },
14986
+ result: listWebChatWorkspacesResultCodec
14987
+ },
14988
+ "agentEnhancer/createWebChatWorkspace": {
14989
+ service: "agentEnhancer",
14990
+ implementation: "createWebChatWorkspace",
14991
+ invocation: { kind: "direct" },
14992
+ parameters: [{
14993
+ name: "request",
14994
+ source: "json",
14995
+ codec: createWebChatWorkspaceRequestCodec,
14996
+ strictCodec: createWebChatWorkspaceRequestCodec
14997
+ }],
14998
+ cancellation: { parameter: "signal" },
14999
+ result: createWebChatWorkspaceResultCodec
15000
+ },
15001
+ "agentEnhancer/importWebChatHistory": {
15002
+ service: "agentEnhancer",
15003
+ implementation: "importWebChatHistory",
15004
+ invocation: { kind: "direct" },
15005
+ parameters: [{
15006
+ name: "request",
15007
+ source: "json",
15008
+ codec: importWebChatHistoryRequestCodec,
15009
+ strictCodec: importWebChatHistoryRequestCodec
15010
+ }],
15011
+ cancellation: { parameter: "signal" },
15012
+ result: importWebChatHistoryResultCodec
15013
+ },
15014
+ "agentEnhancer/parseWebChatExport": {
15015
+ service: "agentEnhancer",
15016
+ implementation: "parseWebChatExport",
15017
+ invocation: { kind: "direct" },
15018
+ parameters: [{
15019
+ name: "request",
15020
+ source: "json",
15021
+ codec: parseWebChatExportRequestCodec,
15022
+ strictCodec: parseWebChatExportRequestCodec
15023
+ }],
15024
+ cancellation: { parameter: "signal" },
15025
+ result: parseWebChatExportResultCodec
15026
+ },
15027
+ "agentEnhancer/resolveWebChatShareLink": {
15028
+ service: "agentEnhancer",
15029
+ implementation: "resolveWebChatShareLink",
15030
+ invocation: { kind: "direct" },
15031
+ parameters: [{
15032
+ name: "request",
15033
+ source: "json",
15034
+ codec: resolveWebChatShareLinkRequestCodec,
15035
+ strictCodec: resolveWebChatShareLinkRequestCodec
15036
+ }],
15037
+ cancellation: { parameter: "signal" },
15038
+ result: resolveWebChatShareLinkResultCodec
15039
+ },
15040
+ "agentEnhancer/loadWebChatLoginSnapshot": {
15041
+ service: "agentEnhancer",
15042
+ implementation: "loadWebChatLoginSnapshot",
15043
+ invocation: { kind: "direct" },
15044
+ parameters: [{
15045
+ name: "request",
15046
+ source: "json",
15047
+ codec: loadWebChatLoginSnapshotRequestCodec,
15048
+ strictCodec: loadWebChatLoginSnapshotRequestCodec
15049
+ }],
15050
+ cancellation: { parameter: "signal" },
15051
+ result: loadWebChatLoginSnapshotResultCodec
15052
+ },
15053
+ "agentEnhancer/saveWebChatLoginSnapshot": {
15054
+ service: "agentEnhancer",
15055
+ implementation: "saveWebChatLoginSnapshot",
15056
+ invocation: { kind: "direct" },
15057
+ parameters: [{
15058
+ name: "request",
15059
+ source: "json",
15060
+ codec: saveWebChatLoginSnapshotRequestCodec,
15061
+ strictCodec: saveWebChatLoginSnapshotRequestCodec
15062
+ }],
15063
+ cancellation: { parameter: "signal" },
15064
+ result: saveWebChatLoginSnapshotResultCodec
15065
+ },
15066
+ "agentEnhancer/clearWebChatLoginSnapshot": {
15067
+ service: "agentEnhancer",
15068
+ implementation: "clearWebChatLoginSnapshot",
15069
+ invocation: { kind: "direct" },
15070
+ parameters: [{
15071
+ name: "request",
15072
+ source: "json",
15073
+ codec: clearWebChatLoginSnapshotRequestCodec,
15074
+ strictCodec: clearWebChatLoginSnapshotRequestCodec
15075
+ }],
15076
+ cancellation: { parameter: "signal" },
15077
+ result: clearWebChatLoginSnapshotResultCodec
13614
15078
  }
13615
15079
  }
13616
15080
  }, z4);
@@ -13895,11 +15359,14 @@ async function showOsNotificationNow(input) {
13895
15359
  }
13896
15360
 
13897
15361
  // src/host/update/check.ts
13898
- import { homedir as homedir5 } from "node:os";
13899
- import { join as join30 } from "node:path";
15362
+ import { homedir as homedir6 } from "node:os";
15363
+ import { join as join32 } from "node:path";
13900
15364
 
13901
15365
  // src/host/update/cli.ts
13902
15366
  import { spawn as nodeSpawn } from "node:child_process";
15367
+ import { existsSync as existsSync20 } from "node:fs";
15368
+ import { homedir as homedir5 } from "node:os";
15369
+ import { posix as pathPosix2 } from "node:path";
13903
15370
  function defaultSpawn(command, args, options) {
13904
15371
  return nodeSpawn(command, [...args], options ?? {});
13905
15372
  }
@@ -13909,6 +15376,40 @@ var STRICT_SEMVER = /^\d+\.\d+\.\d+$/;
13909
15376
  function isStrictVersion(value) {
13910
15377
  return STRICT_SEMVER.test(value);
13911
15378
  }
15379
+ function dshFromElectronExecPath(execPath) {
15380
+ const normalized = execPath.replace(/\\/g, "/");
15381
+ const marker = "/Contents/MacOS/";
15382
+ const idx = normalized.lastIndexOf(marker);
15383
+ if (idx < 0) return null;
15384
+ const contentsRoot = normalized.slice(0, idx + "/Contents".length);
15385
+ return pathPosix2.join(contentsRoot, "Resources", "runtime", "cli", "bin", "dsh");
15386
+ }
15387
+ function dshExecutableCandidates(options = {}) {
15388
+ const platform = options.platform ?? process.platform;
15389
+ const env = options.env ?? process.env;
15390
+ const home = options.home ?? env.HOME?.trim() ?? homedir5();
15391
+ const execPath = options.execPath ?? process.execPath;
15392
+ const out = [];
15393
+ const push = (value) => {
15394
+ const trimmed = typeof value === "string" ? value.trim() : "";
15395
+ if (trimmed === "" || out.includes(trimmed)) return;
15396
+ out.push(trimmed);
15397
+ };
15398
+ push(env.DSH_CLI);
15399
+ if (platform === "darwin") {
15400
+ push(dshFromElectronExecPath(execPath));
15401
+ push("/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
15402
+ push(pathPosix2.join(
15403
+ home,
15404
+ "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh"
15405
+ ));
15406
+ }
15407
+ push("dsh");
15408
+ return out;
15409
+ }
15410
+ function isCommandMissingDetail(detail) {
15411
+ return /ENOENT|not found|spawn .*(ENOENT|not found)/i.test(detail);
15412
+ }
13912
15413
  function dshSpawnOptions() {
13913
15414
  const base = { stdio: ["ignore", "pipe", "pipe"] };
13914
15415
  return process.platform === "win32" ? { ...base, shell: true, windowsHide: true } : base;
@@ -13923,14 +15424,14 @@ function resolveCanAutoApply(input) {
13923
15424
  return input.installKind === "npm" && input.dshAvailable;
13924
15425
  }
13925
15426
  function waitForExit(child, timeoutMs) {
13926
- return new Promise((resolve16) => {
15427
+ return new Promise((resolve17) => {
13927
15428
  let settled = false;
13928
15429
  const chunks = [];
13929
15430
  const finish = (ok, detail) => {
13930
15431
  if (settled) return;
13931
15432
  settled = true;
13932
15433
  clearTimeout(timer);
13933
- resolve16({ ok, detail });
15434
+ resolve17({ ok, detail });
13934
15435
  };
13935
15436
  const timer = setTimeout(() => {
13936
15437
  child.kill();
@@ -13947,29 +15448,42 @@ function waitForExit(child, timeoutMs) {
13947
15448
  });
13948
15449
  });
13949
15450
  }
13950
- async function runDsh(args, spawnFn, timeoutMs) {
15451
+ async function runDshOnce(command, args, spawnFn, timeoutMs) {
13951
15452
  let child;
13952
15453
  try {
13953
- child = spawnFn("dsh", args, dshSpawnOptions());
15454
+ child = spawnFn(command, args, dshSpawnOptions());
13954
15455
  } catch (err) {
13955
15456
  return { ok: false, detail: err instanceof Error ? err.message : String(err) };
13956
15457
  }
13957
15458
  return waitForExit(child, timeoutMs);
13958
15459
  }
13959
- async function probeDsh(spawnFn = defaultSpawn) {
13960
- const result = await runDsh(["--version"], spawnFn, PROBE_TIMEOUT_MS);
15460
+ async function runDsh(args, spawnFn, timeoutMs, options = {}) {
15461
+ const candidates = options.candidates ?? dshExecutableCandidates();
15462
+ const exists = options.exists ?? existsSync20;
15463
+ let last = { ok: false, detail: "dsh not found" };
15464
+ for (const command of candidates) {
15465
+ if (command !== "dsh" && !exists(command)) continue;
15466
+ const result = await runDshOnce(command, args, spawnFn, timeoutMs);
15467
+ if (result.ok) return result;
15468
+ last = result;
15469
+ if (!isCommandMissingDetail(result.detail)) return result;
15470
+ }
15471
+ return last;
15472
+ }
15473
+ async function probeDsh(spawnFn = defaultSpawn, options = {}) {
15474
+ const result = await runDsh(["--version"], spawnFn, PROBE_TIMEOUT_MS, options);
13961
15475
  return result.ok;
13962
15476
  }
13963
- async function runPluginAdd(latest, spawnFn = defaultSpawn) {
15477
+ async function runPluginAdd(latest, spawnFn = defaultSpawn, options = {}) {
13964
15478
  if (!isStrictVersion(latest)) return { ok: false, detail: "invalid version" };
13965
- return runDsh(pluginAddArgs(latest), spawnFn, RUN_ADD_TIMEOUT_MS);
15479
+ return runDsh(pluginAddArgs(latest), spawnFn, RUN_ADD_TIMEOUT_MS, options);
13966
15480
  }
13967
15481
 
13968
15482
  // src/host/update/install-kind.ts
13969
15483
  import { lstatSync as lstatSync5 } from "node:fs";
13970
- import { join as join29 } from "node:path";
15484
+ import { join as join31 } from "node:path";
13971
15485
  function detectInstallKind(profileDir) {
13972
- const pkgPath = join29(profileDir, "node_modules", PACKAGE_NAME);
15486
+ const pkgPath = join31(profileDir, "node_modules", PACKAGE_NAME);
13973
15487
  try {
13974
15488
  const stat = lstatSync5(pkgPath);
13975
15489
  if (stat.isSymbolicLink()) return "link";
@@ -14099,9 +15613,9 @@ function isNewerVersion(latest, current) {
14099
15613
  }
14100
15614
 
14101
15615
  // src/host/update/check.ts
14102
- function resolveDesktopProfileDir(env = process.env, home = homedir5()) {
14103
- const dshHome2 = env.DSH_HOME ?? join30(home, ".dsh");
14104
- return join30(dshHome2, "profiles", "desktop");
15616
+ function resolveDesktopProfileDir(env = process.env, home = homedir6()) {
15617
+ const dshHome2 = env.DSH_HOME ?? join32(home, ".dsh");
15618
+ return join32(dshHome2, "profiles", "desktop");
14105
15619
  }
14106
15620
  async function checkPluginUpdate(deps) {
14107
15621
  const latest = await deps.fetchLatest();
@@ -14158,6 +15672,12 @@ async function applyPluginUpdateForHost(messages, overrides) {
14158
15672
  }
14159
15673
 
14160
15674
  // src/host/index.ts
15675
+ function hostBrowserPreference(value) {
15676
+ return coerceBrowserAgentBrowserForPlatform(
15677
+ resolveBrowserAgentBrowser(value),
15678
+ process.platform
15679
+ );
15680
+ }
14161
15681
  var name = PLUGIN_ID;
14162
15682
  var inject = [
14163
15683
  "llm",
@@ -14193,6 +15713,8 @@ var Config = z5.object({
14193
15713
  /** High-risk; default off. */
14194
15714
  browserAgentEnabled: z5.boolean().default(false).volatile(),
14195
15715
  browserAgentBrowser: z5.string().default("auto").volatile(),
15716
+ /** Default off; embeds official web chat + import to work. */
15717
+ webChatBridgeEnabled: z5.boolean().default(true).volatile(),
14196
15718
  instructionsSkillsEnabled: z5.boolean().default(true).volatile(),
14197
15719
  mcpConnectorsEnabled: z5.boolean().default(true).volatile(),
14198
15720
  // Empty provider/model = follow the current Desktop session model.
@@ -14239,12 +15761,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
14239
15761
  };
14240
15762
  }
14241
15763
  }, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
14242
- join31(homedir6(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
15764
+ join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
14243
15765
  ), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null, browserAgent = null, browserAgentSettings = () => ({
14244
15766
  enabled: false,
14245
15767
  browser: "auto"
14246
15768
  }), setBrowserAgentBrowser = () => void 0, browserAgentProfileDir = defaultBrowserAgentProfileDir(
14247
- join31(homedir6(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
15769
+ join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
14248
15770
  )) {
14249
15771
  super(ctx, "agentEnhancer");
14250
15772
  this.models = models;
@@ -14287,7 +15809,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14287
15809
  const boundTabId = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
14288
15810
  const connected = driverStatus?.ready === true;
14289
15811
  const endpoint = driverStatus?.endpoint ?? "playwright:unlaunched";
14290
- const launched = endpoint === "playwright:msedge" ? "edge" : endpoint === "playwright:chrome" ? "chrome" : null;
15812
+ const launched = endpoint === "playwright:msedge" ? "edge" : endpoint === "playwright:chrome" ? "chrome" : endpoint === "playwright:webkit" ? "safari" : null;
14291
15813
  return {
14292
15814
  enabled: settings.enabled,
14293
15815
  browser: settings.browser,
@@ -14318,7 +15840,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14318
15840
  }
14319
15841
  requireMcpHost() {
14320
15842
  if (this.mcpHost === null) {
14321
- throw new RemoteError("agent-enhancer/failed", "MCP connectors host is unavailable", {
15843
+ throw new RemoteError2("agent-enhancer/failed", "MCP connectors host is unavailable", {
14322
15844
  code: "FILE_EDIT_FAILED"
14323
15845
  });
14324
15846
  }
@@ -14336,7 +15858,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14336
15858
  }
14337
15859
  assertOwner() {
14338
15860
  if (this.ctx.invocation?.peer.principal.kind !== "owner") {
14339
- throw new RemoteError("agent-enhancer/forbidden", "Only the desktop owner may use Agent Enhance", {});
15861
+ throw new RemoteError2("agent-enhancer/forbidden", "Only the desktop owner may use Agent Enhance", {});
14340
15862
  }
14341
15863
  }
14342
15864
  async call(payload, signal) {
@@ -14346,7 +15868,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14346
15868
  } catch (error) {
14347
15869
  if (signal.aborted) throw error;
14348
15870
  const code = error instanceof AuxiliaryError ? error.code : "MODEL_FAILED";
14349
- throw new RemoteError("agent-enhancer/failed", "Agent Enhance request failed", { code });
15871
+ throw new RemoteError2("agent-enhancer/failed", "Agent Enhance request failed", { code });
14350
15872
  }
14351
15873
  }
14352
15874
  /** Same Desktop catalog the official model selector uses (`llm` registry). */
@@ -14354,7 +15876,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14354
15876
  try {
14355
15877
  return await buildAuxiliaryModelCatalog(this.ctx);
14356
15878
  } catch {
14357
- throw new RemoteError("agent-enhancer/failed", "Agent Enhance catalog failed", {
15879
+ throw new RemoteError2("agent-enhancer/failed", "Agent Enhance catalog failed", {
14358
15880
  code: "MODEL_UNAVAILABLE"
14359
15881
  });
14360
15882
  }
@@ -14364,7 +15886,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14364
15886
  signal.throwIfAborted();
14365
15887
  const agent = this.ctx.agents.get(request.sessionId);
14366
15888
  if (agent === void 0) {
14367
- throw new RemoteError("agent-enhancer/failed", "Session not available for context inspect", {
15889
+ throw new RemoteError2("agent-enhancer/failed", "Session not available for context inspect", {
14368
15890
  code: "SESSION_CHANGED"
14369
15891
  });
14370
15892
  }
@@ -14378,7 +15900,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14378
15900
  };
14379
15901
  } catch (error) {
14380
15902
  if (signal.aborted) throw error;
14381
- throw new RemoteError("agent-enhancer/failed", "Context inspect failed", { code: "MODEL_FAILED" });
15903
+ throw new RemoteError2("agent-enhancer/failed", "Context inspect failed", { code: "MODEL_FAILED" });
14382
15904
  }
14383
15905
  }
14384
15906
  /** Permanently delete one sidebar session (official logs + plugin persistence). */
@@ -14396,17 +15918,118 @@ var AgentEnhancerService = class extends TypertRemoteService {
14396
15918
  if (signal.aborted) throw error;
14397
15919
  if (error instanceof SessionDeleteError) {
14398
15920
  this.ctx.logger.warn(`agent-enhancer deleteSession failed: ${error.code} ${error.message}`);
14399
- throw new RemoteError("agent-enhancer/failed", error.message, {
15921
+ throw new RemoteError2("agent-enhancer/failed", error.message, {
14400
15922
  code: error.code === "BUSY" ? "SESSION_BUSY" : "SESSION_DELETE_FAILED"
14401
15923
  });
14402
15924
  }
14403
15925
  const detail = error instanceof Error ? error.message : String(error);
14404
15926
  this.ctx.logger.warn(`agent-enhancer deleteSession failed: ${detail}`);
14405
- throw new RemoteError("agent-enhancer/failed", detail || "Session delete failed", {
15927
+ throw new RemoteError2("agent-enhancer/failed", detail || "Session delete failed", {
14406
15928
  code: "SESSION_DELETE_FAILED"
14407
15929
  });
14408
15930
  }
14409
15931
  }
15932
+ /** Workspaces eligible for imported web-chat sessions. */
15933
+ async listWebChatWorkspaces(_request, signal) {
15934
+ this.assertOwner();
15935
+ signal.throwIfAborted();
15936
+ try {
15937
+ return { items: listWebChatWorkspacesNow(this.ctx) };
15938
+ } catch (error) {
15939
+ if (signal.aborted) throw error;
15940
+ throw webChatImportToRemoteError(error);
15941
+ }
15942
+ }
15943
+ /** Pick a folder and register it as a workspace for web-chat import. */
15944
+ async createWebChatWorkspace(_request, signal) {
15945
+ this.assertOwner();
15946
+ signal.throwIfAborted();
15947
+ try {
15948
+ return await createWebChatWorkspaceNow(this.ctx, signal);
15949
+ } catch (error) {
15950
+ if (signal.aborted) throw error;
15951
+ throw webChatImportToRemoteError(error);
15952
+ }
15953
+ }
15954
+ /** Create a Desktop session from a captured/exported web transcript (no model call). */
15955
+ async importWebChatHistory(request, signal) {
15956
+ this.assertOwner();
15957
+ signal.throwIfAborted();
15958
+ try {
15959
+ return await importWebChatHistoryWithContext(this.ctx, request);
15960
+ } catch (error) {
15961
+ if (signal.aborted) throw error;
15962
+ throw webChatImportToRemoteError(error);
15963
+ }
15964
+ }
15965
+ /** Analyze an official export into selectable conversations (size limits enforced once). */
15966
+ async parseWebChatExport(request, signal) {
15967
+ this.assertOwner();
15968
+ signal.throwIfAborted();
15969
+ try {
15970
+ const bytes = Buffer.from(request.bytesBase64, "base64");
15971
+ return analyzeWebChatExport({ filename: request.filename, bytes });
15972
+ } catch (error) {
15973
+ if (signal.aborted) throw error;
15974
+ const detail = error instanceof Error ? error.message : String(error);
15975
+ throw webChatImportToRemoteError(
15976
+ error instanceof WebChatImportError ? error : new WebChatImportError("invalid-transcript", detail)
15977
+ );
15978
+ }
15979
+ }
15980
+ /**
15981
+ * Resolve a public DeepSeek share link (`chat.deepseek.com/share/…`) into a transcript.
15982
+ * Prefer `payloadJson` from the guest (same-origin) when WAF blocks Host fetch.
15983
+ */
15984
+ async resolveWebChatShareLink(request, signal) {
15985
+ this.assertOwner();
15986
+ signal.throwIfAborted();
15987
+ try {
15988
+ const shareId = extractWebChatShareId(request.shareUrl);
15989
+ if (shareId === null) {
15990
+ throw new WebChatImportError("invalid-transcript", "unrecognized-share: not a DeepSeek share link");
15991
+ }
15992
+ const shareUrl = webChatSharePageUrl(shareId);
15993
+ let data;
15994
+ if (typeof request.payloadJson === "string" && request.payloadJson.trim() !== "") {
15995
+ try {
15996
+ data = JSON.parse(request.payloadJson);
15997
+ } catch {
15998
+ throw new WebChatImportError("invalid-transcript", "unrecognized-share: invalid payload json");
15999
+ }
16000
+ } else {
16001
+ data = await fetchWebChatShareContent(shareId, signal);
16002
+ }
16003
+ const transcript = parseWebChatShareContent(data, { shareUrl, shareId });
16004
+ return { transcript };
16005
+ } catch (error) {
16006
+ if (signal.aborted) throw error;
16007
+ const detail = error instanceof Error ? error.message : String(error);
16008
+ throw webChatImportToRemoteError(
16009
+ error instanceof WebChatImportError ? error : new WebChatImportError("invalid-transcript", detail)
16010
+ );
16011
+ }
16012
+ }
16013
+ webChatPluginDataRoot() {
16014
+ return this.installLedgerRoot ?? join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
16015
+ }
16016
+ /** User-level web chat guest login snapshot (non-HttpOnly storage only). */
16017
+ async loadWebChatLoginSnapshot(_request, signal) {
16018
+ this.assertOwner();
16019
+ signal.throwIfAborted();
16020
+ return { snapshot: loadWebChatLoginSnapshot(this.webChatPluginDataRoot()) };
16021
+ }
16022
+ async saveWebChatLoginSnapshot(request, signal) {
16023
+ this.assertOwner();
16024
+ signal.throwIfAborted();
16025
+ saveWebChatLoginSnapshot(this.webChatPluginDataRoot(), request);
16026
+ return { ok: true };
16027
+ }
16028
+ async clearWebChatLoginSnapshot(_request, signal) {
16029
+ this.assertOwner();
16030
+ signal.throwIfAborted();
16031
+ return { cleared: clearWebChatLoginSnapshot(this.webChatPluginDataRoot()) };
16032
+ }
14410
16033
  /** Read a workspace UTF-8 text file for the in-app Monaco editor. */
14411
16034
  async readWorkspaceFile(request, signal) {
14412
16035
  this.assertOwner();
@@ -14520,7 +16143,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14520
16143
  signal.throwIfAborted();
14521
16144
  const agent = this.ctx.agents.get(request.sessionId);
14522
16145
  if (agent === void 0) {
14523
- throw new RemoteError("agent-enhancer/failed", "Session not available for compaction", {
16146
+ throw new RemoteError2("agent-enhancer/failed", "Session not available for compaction", {
14524
16147
  code: "SESSION_CHANGED"
14525
16148
  });
14526
16149
  }
@@ -14537,7 +16160,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14537
16160
  const code = error instanceof AuxiliaryError ? error.code : "COMPACT_FAILED";
14538
16161
  const detail = error instanceof Error ? error.message : String(error);
14539
16162
  this.ctx.logger.warn(`agent-enhancer compact failed (${code}): ${detail}`);
14540
- throw new RemoteError("agent-enhancer/failed", detail || "Context compaction failed", { code });
16163
+ throw new RemoteError2("agent-enhancer/failed", detail || "Context compaction failed", { code });
14541
16164
  }
14542
16165
  }
14543
16166
  /** Read-only version probe — same gate policy as `listCatalog` (settings-safe). */
@@ -14851,7 +16474,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
14851
16474
  snapshot: this.browserSnapshotNow()
14852
16475
  };
14853
16476
  }
14854
- const preference = request.browser ?? settings.browser;
16477
+ const preference = hostBrowserPreference(request.browser ?? settings.browser);
14855
16478
  this.setBrowserAgentBrowser(preference);
14856
16479
  const launched = await this.browserAgent?.launchDedicated(void 0, preference);
14857
16480
  const snapshot = this.browserSnapshotNow();
@@ -14865,14 +16488,15 @@ var AgentEnhancerService = class extends TypertRemoteService {
14865
16488
  }
14866
16489
  async browserAgentSetBrowser(request) {
14867
16490
  this.assertOwner();
14868
- this.setBrowserAgentBrowser(request.browser);
16491
+ const preference = hostBrowserPreference(request.browser);
16492
+ this.setBrowserAgentBrowser(preference);
14869
16493
  const settings = this.browserAgentSettings();
14870
16494
  if (settings.enabled && this.browserAgent?.driverStatus()?.ready === true) {
14871
16495
  await this.browserAgent.alignToPreference();
14872
16496
  }
14873
16497
  return {
14874
16498
  ok: true,
14875
- browser: request.browser,
16499
+ browser: preference,
14876
16500
  snapshot: this.browserSnapshotNow()
14877
16501
  };
14878
16502
  }
@@ -14888,16 +16512,16 @@ var AgentEnhancerService = class extends TypertRemoteService {
14888
16512
  }
14889
16513
  };
14890
16514
  function resolveCheckpointRoot(dshHome2) {
14891
- const base = join31(dshHome2, "profiles", "desktop", "plugin-data");
14892
- const nextPkg = join31(base, PACKAGE_NAME);
14893
- const next = join31(nextPkg, "checkpoint");
14894
- const prev = join31(base, LEGACY_PACKAGE_NAME, "checkpoint");
14895
- if (!existsSync17(next) && existsSync17(prev)) {
14896
- mkdirSync10(nextPkg, { recursive: true });
14897
- renameSync8(prev, next);
14898
- const prevPkg = join31(base, LEGACY_PACKAGE_NAME);
16515
+ const base = join33(dshHome2, "profiles", "desktop", "plugin-data");
16516
+ const nextPkg = join33(base, PACKAGE_NAME);
16517
+ const next = join33(nextPkg, "checkpoint");
16518
+ const prev = join33(base, LEGACY_PACKAGE_NAME, "checkpoint");
16519
+ if (!existsSync21(next) && existsSync21(prev)) {
16520
+ mkdirSync11(nextPkg, { recursive: true });
16521
+ renameSync9(prev, next);
16522
+ const prevPkg = join33(base, LEGACY_PACKAGE_NAME);
14899
16523
  try {
14900
- if (existsSync17(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
16524
+ if (existsSync21(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
14901
16525
  } catch {
14902
16526
  }
14903
16527
  }
@@ -14905,28 +16529,28 @@ function resolveCheckpointRoot(dshHome2) {
14905
16529
  }
14906
16530
  function fileEditRemoteError(error) {
14907
16531
  if (error instanceof FileEditError) {
14908
- return new RemoteError("agent-enhancer/failed", error.message, { code: error.code });
16532
+ return new RemoteError2("agent-enhancer/failed", error.message, { code: error.code });
14909
16533
  }
14910
16534
  const detail = error instanceof Error ? error.message : String(error);
14911
- return new RemoteError("agent-enhancer/failed", detail || "File edit failed", {
16535
+ return new RemoteError2("agent-enhancer/failed", detail || "File edit failed", {
14912
16536
  code: "FILE_EDIT_FAILED"
14913
16537
  });
14914
16538
  }
14915
16539
  function extraFoldersRemoteError(error) {
14916
16540
  if (error instanceof ExtraFoldersError) {
14917
- return new RemoteError("agent-enhancer/failed", error.message, { code: error.code });
16541
+ return new RemoteError2("agent-enhancer/failed", error.message, { code: error.code });
14918
16542
  }
14919
16543
  const detail = error instanceof Error ? error.message : String(error);
14920
- return new RemoteError("agent-enhancer/failed", detail || "Extra folders failed", {
16544
+ return new RemoteError2("agent-enhancer/failed", detail || "Extra folders failed", {
14921
16545
  code: "FILE_EDIT_FAILED"
14922
16546
  });
14923
16547
  }
14924
16548
  function instructionsSkillsRemoteError(error) {
14925
16549
  if (error instanceof AuxiliaryError) {
14926
- return new RemoteError("agent-enhancer/failed", error.message, { code: error.code });
16550
+ return new RemoteError2("agent-enhancer/failed", error.message, { code: error.code });
14927
16551
  }
14928
16552
  const detail = error instanceof Error ? error.message : String(error);
14929
- return new RemoteError("agent-enhancer/failed", detail || "Instructions & skills failed", {
16553
+ return new RemoteError2("agent-enhancer/failed", detail || "Instructions & skills failed", {
14930
16554
  code: "FILE_EDIT_FAILED"
14931
16555
  });
14932
16556
  }
@@ -14968,7 +16592,8 @@ function readSettings(config) {
14968
16592
  runAlertsEnabled: config.runAlertsEnabled.get(),
14969
16593
  runAlertsLevel: resolveRunAlertsLevel(config.runAlertsLevel.get()),
14970
16594
  browserAgentEnabled: config.browserAgentEnabled.get(),
14971
- browserAgentBrowser: resolveBrowserAgentBrowser(config.browserAgentBrowser.get()),
16595
+ browserAgentBrowser: hostBrowserPreference(config.browserAgentBrowser.get()),
16596
+ webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
14972
16597
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
14973
16598
  mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
14974
16599
  optimizeProvider: config.optimizeProvider.get(),
@@ -14999,9 +16624,9 @@ function apply(ctx, config) {
14999
16624
  const settings = () => readSettings(config);
15000
16625
  const models = new AuxiliaryModels(ctx, settings);
15001
16626
  installAutoSessionRoute(ctx, { settings });
15002
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join31(homedir6(), ".dsh"));
15003
- const pluginDataPackageRoot = join31(storageRoot, "..");
15004
- const usage = new UsageLedger(join31(storageRoot, "..", "usage"), (message) => {
16627
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join33(homedir7(), ".dsh"));
16628
+ const pluginDataPackageRoot = join33(storageRoot, "..");
16629
+ const usage = new UsageLedger(join33(storageRoot, "..", "usage"), (message) => {
15005
16630
  ctx.logger.warn(message);
15006
16631
  });
15007
16632
  const balancesFacade = (() => {
@@ -15031,12 +16656,12 @@ function apply(ctx, config) {
15031
16656
  })();
15032
16657
  installUsageObserver(ctx, usage);
15033
16658
  const store = new CheckpointStore(storageRoot);
15034
- const cutStore = new SessionCutStore(join31(storageRoot, "cuts"));
16659
+ const cutStore = new SessionCutStore(join33(storageRoot, "cuts"));
15035
16660
  const cutCache = /* @__PURE__ */ new Map();
15036
16661
  const sessionCleanup = new SessionCleanupRegistry();
15037
16662
  sessionCleanup.register(createCheckpointCleaner({ store, cutStore, storageRoot }));
15038
- sessionCleanup.register(createContextExcludeCleaner(join31(storageRoot, "..")));
15039
- const extraFoldersStore = createExtraFoldersStore(join31(storageRoot, "..", "extra-folders"));
16663
+ sessionCleanup.register(createContextExcludeCleaner(join33(storageRoot, "..")));
16664
+ const extraFoldersStore = createExtraFoldersStore(join33(storageRoot, "..", "extra-folders"));
15040
16665
  const softPauseGate = new SoftPauseGate();
15041
16666
  const mcpStore = createMcpConnectorsStore(mcpConnectorsRoot(pluginDataPackageRoot));
15042
16667
  const mcpRuntime = new McpConnectorRuntime(ctx, mcpStore);
@@ -15103,7 +16728,7 @@ function apply(ctx, config) {
15103
16728
  browser: browserAgentLive.browser
15104
16729
  }),
15105
16730
  (browser) => {
15106
- browserAgentLive.browser = resolveBrowserAgentBrowser(browser);
16731
+ browserAgentLive.browser = hostBrowserPreference(browser);
15107
16732
  },
15108
16733
  browserAgentProfileDir
15109
16734
  );
@@ -15119,7 +16744,7 @@ function apply(ctx, config) {
15119
16744
  const prevEnabled = browserAgentLive.enabled;
15120
16745
  const prevBrowser = browserAgentLive.browser;
15121
16746
  browserAgentLive.enabled = cfg.browserAgentEnabled.get();
15122
- browserAgentLive.browser = resolveBrowserAgentBrowser(cfg.browserAgentBrowser.get());
16747
+ browserAgentLive.browser = hostBrowserPreference(cfg.browserAgentBrowser.get());
15123
16748
  if (prevEnabled !== browserAgentLive.enabled) {
15124
16749
  browserAgent.refresh();
15125
16750
  } else if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
@@ -15226,13 +16851,13 @@ var CheckpointRollbackRemoteService = class extends TypertRemoteService {
15226
16851
  }
15227
16852
  assertOwner() {
15228
16853
  if (this.ctx.invocation?.peer.principal.kind !== "owner") {
15229
- throw new RemoteError("agent-enhancer/forbidden", "Only the desktop owner may use checkpoint rollback", {});
16854
+ throw new RemoteError2("agent-enhancer/forbidden", "Only the desktop owner may use checkpoint rollback", {});
15230
16855
  }
15231
16856
  }
15232
16857
  remoteError(error, signal) {
15233
16858
  if (signal.aborted) return error;
15234
16859
  const code = error instanceof CheckpointRollbackError ? error.code : "ROLLBACK_FAILED";
15235
- return new RemoteError("agent-enhancer/rollback-failed", "Checkpoint rollback request failed", { code });
16860
+ return new RemoteError2("agent-enhancer/rollback-failed", "Checkpoint rollback request failed", { code });
15236
16861
  }
15237
16862
  };
15238
16863
  function applyCheckpointRollback(ctx, rollback) {