dsh-agent-enhancer 0.3.12 → 0.3.14

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 (76) hide show
  1. package/README.en.md +11 -10
  2. package/README.md +11 -10
  3. package/lib/client/browser-agent/overlay.d.ts.map +1 -1
  4. package/lib/client/browser-agent/tab.d.ts.map +1 -1
  5. package/lib/client/dsh/settings-about.d.ts +0 -3
  6. package/lib/client/dsh/settings-about.d.ts.map +1 -1
  7. package/lib/client/dsh/settings-features.d.ts +2 -0
  8. package/lib/client/dsh/settings-features.d.ts.map +1 -1
  9. package/lib/client/dsh/settings.d.ts +0 -3
  10. package/lib/client/dsh/settings.d.ts.map +1 -1
  11. package/lib/client/index.d.ts.map +1 -1
  12. package/lib/client/locales.d.ts +63 -51
  13. package/lib/client/locales.d.ts.map +1 -1
  14. package/lib/client/remote.d.ts +4 -8
  15. package/lib/client/remote.d.ts.map +1 -1
  16. package/lib/client/web-chat-bridge/preview.d.ts.map +1 -1
  17. package/lib/client/web-chat-bridge/share-fetch.d.ts +13 -2
  18. package/lib/client/web-chat-bridge/share-fetch.d.ts.map +1 -1
  19. package/lib/client.js +1578 -1778
  20. package/lib/client.js.map +1 -1
  21. package/lib/config.d.ts +4 -0
  22. package/lib/config.d.ts.map +1 -1
  23. package/lib/host/browser-agent/capture.d.ts +55 -0
  24. package/lib/host/browser-agent/capture.d.ts.map +1 -0
  25. package/lib/host/browser-agent/diagnose.d.ts +38 -0
  26. package/lib/host/browser-agent/diagnose.d.ts.map +1 -0
  27. package/lib/host/browser-agent/driver.d.ts +35 -0
  28. package/lib/host/browser-agent/driver.d.ts.map +1 -1
  29. package/lib/host/browser-agent/human-gate.d.ts +8 -0
  30. package/lib/host/browser-agent/human-gate.d.ts.map +1 -1
  31. package/lib/host/browser-agent/install.d.ts +18 -0
  32. package/lib/host/browser-agent/install.d.ts.map +1 -1
  33. package/lib/host/browser-agent/playwright-driver.d.ts +49 -5
  34. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  35. package/lib/host/browser-agent/playwright-snapshot.d.ts +16 -2
  36. package/lib/host/browser-agent/playwright-snapshot.d.ts.map +1 -1
  37. package/lib/host/browser-agent/protocol.d.ts +17 -0
  38. package/lib/host/browser-agent/protocol.d.ts.map +1 -1
  39. package/lib/host/browser-agent/session-state.d.ts +24 -9
  40. package/lib/host/browser-agent/session-state.d.ts.map +1 -1
  41. package/lib/host/browser-agent/tab-registry.d.ts +32 -0
  42. package/lib/host/browser-agent/tab-registry.d.ts.map +1 -0
  43. package/lib/host/browser-agent/tab-scope.d.ts +22 -0
  44. package/lib/host/browser-agent/tab-scope.d.ts.map +1 -0
  45. package/lib/host/browser-agent/tools.d.ts +8 -0
  46. package/lib/host/browser-agent/tools.d.ts.map +1 -1
  47. package/lib/host/index.d.ts +10 -5
  48. package/lib/host/index.d.ts.map +1 -1
  49. package/lib/host/rpc.d.ts +586 -38
  50. package/lib/host/rpc.d.ts.map +1 -1
  51. package/lib/host/web-chat-bridge/convert-conversation.d.ts +38 -0
  52. package/lib/host/web-chat-bridge/convert-conversation.d.ts.map +1 -0
  53. package/lib/host/web-chat-bridge/fragments.d.ts +72 -0
  54. package/lib/host/web-chat-bridge/fragments.d.ts.map +1 -0
  55. package/lib/host/web-chat-bridge/import-session.d.ts +2 -1
  56. package/lib/host/web-chat-bridge/import-session.d.ts.map +1 -1
  57. package/lib/host/web-chat-bridge/share-link.d.ts.map +1 -1
  58. package/lib/host/web-chat-bridge/types.d.ts +9 -0
  59. package/lib/host/web-chat-bridge/types.d.ts.map +1 -1
  60. package/lib/index.js +1724 -596
  61. package/lib/index.js.map +4 -4
  62. package/package.json +15 -12
  63. package/lib/client/dsh/settings-update.d.ts +0 -9
  64. package/lib/client/dsh/settings-update.d.ts.map +0 -1
  65. package/lib/host/update/check.d.ts +0 -32
  66. package/lib/host/update/check.d.ts.map +0 -1
  67. package/lib/host/update/cli.d.ts +0 -41
  68. package/lib/host/update/cli.d.ts.map +0 -1
  69. package/lib/host/update/install-kind.d.ts +0 -3
  70. package/lib/host/update/install-kind.d.ts.map +0 -1
  71. package/lib/host/update/registry.d.ts +0 -16
  72. package/lib/host/update/registry.d.ts.map +0 -1
  73. package/lib/host/update/semver.d.ts +0 -2
  74. package/lib/host/update/semver.d.ts.map +0 -1
  75. package/lib/host/update/types.d.ts +0 -17
  76. package/lib/host/update/types.d.ts.map +0 -1
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/host/index.ts
2
- import { existsSync as existsSync21, mkdirSync as mkdirSync12, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
- import { homedir as homedir7 } from "node:os";
4
- import { join as join32 } from "node:path";
2
+ import { existsSync as existsSync20, mkdirSync as mkdirSync12, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
+ import { homedir as homedir5 } from "node:os";
4
+ import { join as join30 } from "node:path";
5
5
  import z5 from "@deepseek-ai/schemastery";
6
6
  import { RemoteError as RemoteError2, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
7
7
 
@@ -68,6 +68,8 @@ var DEFAULT_SETTINGS = {
68
68
  runAlertsLevel: "unfocused",
69
69
  browserAgentEnabled: false,
70
70
  browserAgentBrowser: "auto",
71
+ browserAgentDebugTools: false,
72
+ browserAgentIdleClose: true,
71
73
  webChatBridgeEnabled: true,
72
74
  instructionsSkillsEnabled: true,
73
75
  mcpConnectorsEnabled: true,
@@ -113,6 +115,8 @@ function resolveSettings(value) {
113
115
  runAlertsLevel: resolveRunAlertsLevel(value?.runAlertsLevel),
114
116
  browserAgentEnabled: value?.browserAgentEnabled ?? false,
115
117
  browserAgentBrowser: resolveBrowserAgentBrowser(value?.browserAgentBrowser),
118
+ browserAgentDebugTools: value?.browserAgentDebugTools === true,
119
+ browserAgentIdleClose: value?.browserAgentIdleClose !== false,
116
120
  webChatBridgeEnabled: value?.webChatBridgeEnabled ?? true,
117
121
  instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
118
122
  mcpConnectorsEnabled: value?.mcpConnectorsEnabled ?? true,
@@ -358,6 +362,7 @@ var BrowserHumanGate = class {
358
362
  const request = {
359
363
  id,
360
364
  sessionId: input.sessionId,
365
+ kind: input.kind ?? "human",
361
366
  prompt: input.prompt,
362
367
  detail: input.detail,
363
368
  ...input.url === void 0 ? {} : { url: input.url }
@@ -605,7 +610,6 @@ function stopAgentBrowserProcesses(profileDir) {
605
610
 
606
611
  // src/host/browser-agent/playwright-driver.ts
607
612
  import { existsSync as existsSync2, mkdirSync } from "node:fs";
608
- import { chromium, webkit } from "playwright-core";
609
613
 
610
614
  // src/host/browser-agent/proximity.ts
611
615
  function attachHrefByProximity(nodes, anchors) {
@@ -675,7 +679,7 @@ function attachHrefByProximity(nodes, anchors) {
675
679
  }
676
680
 
677
681
  // src/host/browser-agent/playwright-snapshot.ts
678
- var PLAYWRIGHT_DRIVER_VERSION = "pw-0.1.0";
682
+ var PLAYWRIGHT_DRIVER_VERSION = "pw-0.2.0";
679
683
  var PLAYWRIGHT_REF_ATTR = "data-dsh-ba-ref";
680
684
  var MAX_NODES = 80;
681
685
  var HARVEST_PAGE_SNAPSHOT_SOURCE = `"use strict";
@@ -851,7 +855,32 @@ for (var ri = 0; ri < records.length; ri++) {
851
855
  preferred.setAttribute(attr, String(rec.ref));
852
856
  }
853
857
  `;
854
- async function capturePlaywrightSnapshot(page) {
858
+ function selectSnapshotRows(rows, max) {
859
+ const budget = Math.max(0, Math.trunc(max));
860
+ if (budget === 0) return [];
861
+ const links = rows.filter((row) => row.priority <= 0);
862
+ const controls = rows.filter((row) => row.priority === 1);
863
+ const anchors = rows.filter((row) => row.priority > 1);
864
+ const controlSlots = Math.min(controls.length, Math.max(1, Math.floor(budget / 2)));
865
+ const linkSlots = Math.min(links.length, budget - controlSlots);
866
+ let remaining = budget - controlSlots - linkSlots;
867
+ const anchorSlots = Math.min(anchors.length, remaining);
868
+ remaining -= anchorSlots;
869
+ const picked = /* @__PURE__ */ new Set([
870
+ ...controls.slice(0, controlSlots),
871
+ ...links.slice(0, linkSlots),
872
+ ...anchors.slice(0, anchorSlots)
873
+ ]);
874
+ if (remaining > 0) {
875
+ for (const row of [...links.slice(linkSlots), ...controls.slice(controlSlots)]) {
876
+ if (remaining === 0) break;
877
+ picked.add(row);
878
+ remaining -= 1;
879
+ }
880
+ }
881
+ return rows.filter((row) => picked.has(row));
882
+ }
883
+ async function capturePlaywrightSnapshot(page, options = {}) {
855
884
  const harvest = await page.evaluate(`(() => { ${HARVEST_PAGE_SNAPSHOT_SOURCE} })()`);
856
885
  const proximityNodes = harvest.interactive.map((item) => ({
857
886
  href: item.href,
@@ -880,7 +909,10 @@ async function capturePlaywrightSnapshot(page) {
880
909
  x: typeof node.x === "number" ? node.x : 0,
881
910
  y: typeof node.y === "number" ? node.y : 0,
882
911
  sensitive: item?.sensitive === true,
883
- priority: node.priority ?? (href ? 0 : 1)
912
+ // Rank by element kind, not by whether proximity bound an href: a button
913
+ // sitting near a link would otherwise be treated as a link and lose the
914
+ // node budget to real anchors.
915
+ priority: (item?.tag ?? "a") === "a" ? 0 : 1
884
916
  };
885
917
  });
886
918
  const knownHrefs = new Set(rows.map((r) => r.href).filter((h) => h !== ""));
@@ -895,15 +927,17 @@ async function capturePlaywrightSnapshot(page) {
895
927
  x: anchor.x + anchor.w / 2,
896
928
  y: anchor.y + anchor.h / 2,
897
929
  sensitive: false,
898
- priority: 0
930
+ // 2, not 0: a synthetic anchor (harvested from geometry, not an element)
931
+ // must never push a real button/input out of the node budget.
932
+ priority: 2
899
933
  });
900
934
  }
901
- rows.sort((a, b) => a.priority - b.priority);
902
- const limited = rows.slice(0, MAX_NODES);
935
+ const limited = selectSnapshotRows(rows, MAX_NODES);
903
936
  const nodes = [];
904
937
  const refs = /* @__PURE__ */ new Map();
938
+ const refBase = Number.isFinite(options.startRef) ? Math.max(1, Math.trunc(options.startRef)) : 1;
905
939
  for (const row of limited) {
906
- const ref = nodes.length + 1;
940
+ const ref = refBase + nodes.length;
907
941
  nodes.push({
908
942
  ref,
909
943
  role: row.role,
@@ -939,10 +973,14 @@ async function capturePlaywrightSnapshot(page) {
939
973
  title: await page.title().catch(() => ""),
940
974
  nodes,
941
975
  textPreview: harvest.textPreview,
942
- tabId: 1,
943
976
  source: harvest.anchors.length > 0 || proximityHits > 0 ? "playwright+anchors" : "playwright",
944
977
  extensionVersion: PLAYWRIGHT_DRIVER_VERSION,
945
978
  anchorCount: harvest.anchors.length,
979
+ harvest: {
980
+ interactive: harvest.interactive.length,
981
+ controls: rows.filter((row) => row.priority === 1).length,
982
+ anchors: proximityAnchors.length
983
+ },
946
984
  ...withHref === 0 ? {
947
985
  note: `No http(s) href on interactive refs yet (anchors_in_dom=${harvest.anchors.length}). browser_wait then browser_snapshot again.`
948
986
  } : proximityHits > 0 ? { note: `Bound ${proximityHits} ref(s) to nearby document hrefs (anchors_in_dom=${harvest.anchors.length}).` } : { note: `anchors_in_dom=${harvest.anchors.length}` }
@@ -950,6 +988,60 @@ async function capturePlaywrightSnapshot(page) {
950
988
  return { body, refs };
951
989
  }
952
990
 
991
+ // src/host/browser-agent/capture.ts
992
+ var SECRET_PARAM = /^(access_?token|id_?token|auth|authorization|code|key|password|secret|session|sessionid|sig|signature|token)$/i;
993
+ var URL_IN_TEXT = /https?:\/\/[^\s"'<>]+/g;
994
+ function redactUrl(raw) {
995
+ const withoutUserInfo = raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
996
+ const withoutFragment = withoutUserInfo.replace(/#.*$/, "");
997
+ const masked = withoutFragment.replace(
998
+ /([?&])([^=&#]+)=([^&#]*)/g,
999
+ (match, separator, key) => SECRET_PARAM.test(decodeURIComponent(key)) ? `${separator}${key}=***` : match
1000
+ );
1001
+ return masked.length > 300 ? `${masked.slice(0, 300)}\u2026` : masked;
1002
+ }
1003
+ function redactText(text3) {
1004
+ return text3.replace(URL_IN_TEXT, (match) => {
1005
+ const trailing = match.match(/[),.;]+$/)?.[0] ?? "";
1006
+ const core = trailing === "" ? match : match.slice(0, -trailing.length);
1007
+ return `${redactUrl(core)}${trailing}`;
1008
+ });
1009
+ }
1010
+ var CaptureBuffer = class {
1011
+ constructor(max = 300) {
1012
+ this.max = max;
1013
+ }
1014
+ max;
1015
+ entries = [];
1016
+ dropped = 0;
1017
+ get size() {
1018
+ return this.entries.length;
1019
+ }
1020
+ push(entry) {
1021
+ this.entries.push(entry);
1022
+ while (this.entries.length > this.max) {
1023
+ this.entries.shift();
1024
+ this.dropped += 1;
1025
+ }
1026
+ }
1027
+ /** Newest `limit` entries of the requested kind, optionally clearing them. */
1028
+ read(kind, options = {}) {
1029
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 40), 1), 200);
1030
+ const matched = this.entries.filter((entry) => kind === "all" || entry.kind === (kind === "network" ? "request" : "console"));
1031
+ const selected = matched.slice(-limit);
1032
+ if (options.clear === true) {
1033
+ const keep = this.entries.filter((entry) => !selected.includes(entry));
1034
+ this.entries.length = 0;
1035
+ this.entries.push(...keep);
1036
+ }
1037
+ return { entries: selected, dropped: this.dropped };
1038
+ }
1039
+ clear() {
1040
+ this.entries.length = 0;
1041
+ this.dropped = 0;
1042
+ }
1043
+ };
1044
+
953
1045
  // src/host/browser-agent/auto-nav.ts
954
1046
  function pathKey(raw) {
955
1047
  try {
@@ -1006,7 +1098,70 @@ function pickAutoNavigateHref(links, beforeUrl, preferredName = "") {
1006
1098
  return best;
1007
1099
  }
1008
1100
 
1101
+ // src/host/browser-agent/tab-registry.ts
1102
+ var EMPTY_REFS = /* @__PURE__ */ new Map();
1103
+ var TabRegistry = class {
1104
+ idByPage = /* @__PURE__ */ new WeakMap();
1105
+ pageById = /* @__PURE__ */ new Map();
1106
+ refsById = /* @__PURE__ */ new Map();
1107
+ nextId = 1;
1108
+ /** Stable id for a page, assigned on first sight. */
1109
+ idOf(page) {
1110
+ const known = this.idByPage.get(page);
1111
+ if (known !== void 0) return known;
1112
+ const id = this.nextId;
1113
+ this.nextId += 1;
1114
+ this.idByPage.set(page, id);
1115
+ this.pageById.set(id, page);
1116
+ this.refsById.set(id, /* @__PURE__ */ new Map());
1117
+ return id;
1118
+ }
1119
+ /** Forget a closed page. Its id is retired, never handed to another page. */
1120
+ release(page) {
1121
+ const id = this.idByPage.get(page);
1122
+ if (id === void 0) return;
1123
+ this.idByPage.delete(page);
1124
+ this.pageById.delete(id);
1125
+ this.refsById.delete(id);
1126
+ }
1127
+ page(tabId) {
1128
+ return this.pageById.get(tabId);
1129
+ }
1130
+ refsOf(tabId) {
1131
+ return this.refsById.get(tabId) ?? EMPTY_REFS;
1132
+ }
1133
+ ref(tabId, ref) {
1134
+ return this.refsById.get(tabId)?.get(ref);
1135
+ }
1136
+ setRefs(tabId, refs) {
1137
+ this.refsById.set(tabId, new Map(refs));
1138
+ }
1139
+ clearRefs(tabId) {
1140
+ this.refsById.set(tabId, /* @__PURE__ */ new Map());
1141
+ }
1142
+ /** Which other tab still holds this ref — used to explain a cross-tab mistake. */
1143
+ tabHolding(ref, exceptTabId) {
1144
+ for (const [tabId, refs] of this.refsById) {
1145
+ if (tabId !== exceptTabId && refs.has(ref)) return tabId;
1146
+ }
1147
+ return void 0;
1148
+ }
1149
+ /** Actionable message for a ref that is not in the active tab. */
1150
+ unknownRefMessage(ref, activeTabId) {
1151
+ const other = this.tabHolding(ref, activeTabId);
1152
+ if (other !== void 0) {
1153
+ return `Ref ${ref} belongs to tab ${other}; tab ${activeTabId} is active. Switch back with browser_follow_tab (tabId ${other}) or call browser_snapshot for refs in this tab.`;
1154
+ }
1155
+ return `Unknown ref ${ref}; call browser_snapshot first`;
1156
+ }
1157
+ };
1158
+
1009
1159
  // src/host/browser-agent/playwright-driver.ts
1160
+ var playwrightModule = null;
1161
+ async function loadPlaywright() {
1162
+ playwrightModule ??= await import("playwright-core");
1163
+ return playwrightModule;
1164
+ }
1010
1165
  var PlaywrightDriver = class {
1011
1166
  kind = "playwright";
1012
1167
  profileDirOption;
@@ -1018,7 +1173,18 @@ var PlaywrightDriver = class {
1018
1173
  lastError = null;
1019
1174
  channel = null;
1020
1175
  launchedProfileDir = null;
1021
- lastRefs = /* @__PURE__ */ new Map();
1176
+ tabs = new TabRegistry();
1177
+ trackedPages = /* @__PURE__ */ new WeakSet();
1178
+ /** Monotonic per-driver ref counter, so refs never collide across tabs. */
1179
+ nextRef = 1;
1180
+ /** Null until the debug tools ask for capture; stays on for the driver lifetime. */
1181
+ capture = null;
1182
+ captureStartedPages = /* @__PURE__ */ new WeakSet();
1183
+ requestStart = /* @__PURE__ */ new WeakMap();
1184
+ /** Last applied emulation per tab, echoed in snapshot so the agent can see it. */
1185
+ emulationByTab = /* @__PURE__ */ new Map();
1186
+ /** Last agent/UI use per page; a page's clock starts when it is first seen. */
1187
+ lastUse = /* @__PURE__ */ new WeakMap();
1022
1188
  constructor(options) {
1023
1189
  this.profileDirOption = options.profileDir;
1024
1190
  this.preferenceOption = options.preference ?? "auto";
@@ -1038,9 +1204,56 @@ var PlaywrightDriver = class {
1038
1204
  }
1039
1205
  return this.currentProfileDir();
1040
1206
  }
1041
- /** Latest snapshot refs — used by the click/type path. */
1042
- refOf(ref) {
1043
- return this.lastRefs.get(ref);
1207
+ /**
1208
+ * Stable id for a page, and the place its refs live. Ids survive other tabs
1209
+ * opening/closing and are never reused; refs stay with the tab that captured
1210
+ * them, so switching tabs no longer invalidates the snapshot you came from.
1211
+ */
1212
+ tabIdFor(page) {
1213
+ const tabId = this.tabs.idOf(page);
1214
+ if (!this.lastUse.has(page)) this.lastUse.set(page, Date.now());
1215
+ if (!this.trackedPages.has(page)) {
1216
+ this.trackedPages.add(page);
1217
+ page.on("close", () => {
1218
+ this.tabs.release(page);
1219
+ this.emulationByTab.delete(tabId);
1220
+ this.trackedPages.delete(page);
1221
+ });
1222
+ }
1223
+ return tabId;
1224
+ }
1225
+ clearRefs(page) {
1226
+ this.tabs.clearRefs(this.tabIdFor(page));
1227
+ }
1228
+ /** Any real use of a page resets its idle clock; sidebar listing does not. */
1229
+ touch(page) {
1230
+ this.lastUse.set(page, Date.now());
1231
+ }
1232
+ async sweepIdleTabs(input) {
1233
+ const context = this.context;
1234
+ if (context === null) return [];
1235
+ const keep = new Set(input.keep ?? []);
1236
+ const pages = context.pages();
1237
+ const closed = [];
1238
+ const now = Date.now();
1239
+ for (const page of pages) {
1240
+ if (pages.length - closed.length <= 1) break;
1241
+ if (page === this.page || page.isClosed()) continue;
1242
+ const tabId = this.tabIdFor(page);
1243
+ if (keep.has(tabId)) continue;
1244
+ const last = this.lastUse.get(page) ?? now;
1245
+ if (now - last < input.idleMs) continue;
1246
+ await page.close().catch(() => void 0);
1247
+ if (page.isClosed()) closed.push(tabId);
1248
+ }
1249
+ return closed;
1250
+ }
1251
+ /** Page still attached to this context and not closed. */
1252
+ isLivePage(page) {
1253
+ if (page === null || typeof page !== "object") return false;
1254
+ const candidate = page;
1255
+ if (typeof candidate.isClosed !== "function" || candidate.isClosed()) return false;
1256
+ return this.context?.pages().includes(candidate) === true;
1044
1257
  }
1045
1258
  status() {
1046
1259
  const ready = this.context !== null && this.page !== null && !this.page.isClosed();
@@ -1093,7 +1306,7 @@ var PlaywrightDriver = class {
1093
1306
  this.context = null;
1094
1307
  this.page = null;
1095
1308
  this.launchedProfileDir = null;
1096
- this.lastRefs.clear();
1309
+ this.capture = null;
1097
1310
  });
1098
1311
  return;
1099
1312
  } catch (error) {
@@ -1122,6 +1335,7 @@ var PlaywrightDriver = class {
1122
1335
  }
1123
1336
  }
1124
1337
  let webkitExe;
1338
+ const { webkit } = await loadPlaywright();
1125
1339
  try {
1126
1340
  webkitExe = webkit.executablePath();
1127
1341
  } catch (error) {
@@ -1149,6 +1363,7 @@ var PlaywrightDriver = class {
1149
1363
  this.lastError = `${kind} is not installed or not found on PATH`;
1150
1364
  return null;
1151
1365
  }
1366
+ const { chromium } = await loadPlaywright();
1152
1367
  return chromium.launchPersistentContext(profileDir, {
1153
1368
  executablePath: resolved.executable,
1154
1369
  headless: this.headless,
@@ -1176,6 +1391,7 @@ var PlaywrightDriver = class {
1176
1391
  if (this.page === null || this.page.isClosed()) {
1177
1392
  throw new Error("Playwright page is not available");
1178
1393
  }
1394
+ this.touch(this.page);
1179
1395
  return this.page;
1180
1396
  }
1181
1397
  async pageStatus() {
@@ -1184,7 +1400,7 @@ var PlaywrightDriver = class {
1184
1400
  connected: true,
1185
1401
  url: page.url(),
1186
1402
  title: await page.title().catch(() => ""),
1187
- tabId: tabIdOf(page.context(), page),
1403
+ tabId: this.tabIdFor(page),
1188
1404
  bound: true
1189
1405
  };
1190
1406
  }
@@ -1199,18 +1415,22 @@ var PlaywrightDriver = class {
1199
1415
  }
1200
1416
  await page.goto(url, { waitUntil: "domcontentloaded" });
1201
1417
  await settlePage(page);
1202
- this.lastRefs.clear();
1418
+ this.touch(page);
1419
+ this.clearRefs(page);
1203
1420
  return {
1204
1421
  url: page.url(),
1205
1422
  title: await page.title().catch(() => ""),
1206
- tabId: tabIdOf(page.context(), page)
1423
+ tabId: this.tabIdFor(page)
1207
1424
  };
1208
1425
  }
1209
1426
  async snapshot() {
1210
1427
  const page = await this.requirePage();
1211
- const { body, refs } = await capturePlaywrightSnapshot(page);
1212
- this.lastRefs = new Map(refs);
1213
- return { ...body, tabId: tabIdOf(page.context(), page) };
1428
+ const tabId = this.tabIdFor(page);
1429
+ const { body, refs } = await capturePlaywrightSnapshot(page, { startRef: this.nextRef });
1430
+ this.nextRef += body.nodes.length;
1431
+ this.tabs.setRefs(tabId, refs);
1432
+ const emulation = this.emulationByTab.get(tabId);
1433
+ return { ...body, ...emulation === void 0 ? {} : { emulation }, tabId };
1214
1434
  }
1215
1435
  async extract(input = {}) {
1216
1436
  const page = await this.requirePage();
@@ -1223,14 +1443,15 @@ var PlaywrightDriver = class {
1223
1443
  text: clipped.slice(0, maxChars),
1224
1444
  truncated: clipped.length > maxChars,
1225
1445
  ...input.focus === void 0 || input.focus.trim() === "" ? {} : { focus: input.focus.trim() },
1226
- tabId: tabIdOf(page.context(), page)
1446
+ tabId: this.tabIdFor(page)
1227
1447
  };
1228
1448
  }
1229
1449
  async click(ref) {
1230
1450
  const page = await this.requirePage();
1231
- const record2 = this.lastRefs.get(ref);
1451
+ const tabId = this.tabIdFor(page);
1452
+ const record2 = this.tabs.ref(tabId, ref);
1232
1453
  if (record2 === void 0) {
1233
- throw new Error(`Unknown ref ${ref}; call browser_snapshot first`);
1454
+ throw new Error(this.tabs.unknownRefMessage(ref, tabId));
1234
1455
  }
1235
1456
  const beforeUrl = page.url();
1236
1457
  const href = /^https?:\/\//i.test(record2.href) ? record2.href : "";
@@ -1246,14 +1467,14 @@ var PlaywrightDriver = class {
1246
1467
  if (href !== "" && pathsDiffer(beforeUrl, href)) {
1247
1468
  await page.goto(href, { waitUntil: "domcontentloaded" });
1248
1469
  await settlePage(page);
1249
- this.lastRefs.clear();
1470
+ this.clearRefs(page);
1250
1471
  const after = page.url();
1251
1472
  return {
1252
1473
  url: after,
1253
1474
  title: await page.title().catch(() => ""),
1254
1475
  changed: pathsDiffer(beforeUrl, after),
1255
1476
  href,
1256
- tabId: tabIdOf(page.context(), page),
1477
+ tabId: this.tabIdFor(page),
1257
1478
  warning: "Opened this ref's href after snapshot bound a nearby document link."
1258
1479
  };
1259
1480
  }
@@ -1265,14 +1486,14 @@ var PlaywrightDriver = class {
1265
1486
  const adopted = await adoptPopup(popup, beforeUrl);
1266
1487
  if (adopted) {
1267
1488
  this.page = popup;
1268
- this.lastRefs.clear();
1489
+ this.clearRefs(page);
1269
1490
  await settlePage(popup);
1270
1491
  return {
1271
1492
  url: popup.url(),
1272
1493
  title: await popup.title().catch(() => ""),
1273
1494
  changed: true,
1274
1495
  ...href !== "" ? { href } : {},
1275
- tabId: tabIdOf(context, popup),
1496
+ tabId: this.tabIdFor(popup),
1276
1497
  warning: "Click opened a new tab; rebound the browser-agent session to it."
1277
1498
  };
1278
1499
  }
@@ -1296,7 +1517,7 @@ var PlaywrightDriver = class {
1296
1517
  changed = pathsDiffer(beforeUrl, afterUrl);
1297
1518
  followedHref = changed;
1298
1519
  }
1299
- this.lastRefs.clear();
1520
+ this.clearRefs(page);
1300
1521
  let pageLinks = [];
1301
1522
  if (!changed && href === "") {
1302
1523
  pageLinks = await listHttpAnchors(page);
@@ -1305,7 +1526,7 @@ var PlaywrightDriver = class {
1305
1526
  url: afterUrl,
1306
1527
  title: await page.title().catch(() => ""),
1307
1528
  changed,
1308
- tabId: tabIdOf(page.context(), page),
1529
+ tabId: this.tabIdFor(page),
1309
1530
  ...href !== "" ? { href } : {},
1310
1531
  ...pageLinks.length > 0 ? { pageLinks: pageLinks.slice(0, 8) } : {},
1311
1532
  ...followedHref ? { warning: "Click missed; opened this ref's own href via navigation." } : !changed ? {
@@ -1317,14 +1538,14 @@ var PlaywrightDriver = class {
1317
1538
  if (href !== "" && pathsDiffer(beforeUrl, href)) {
1318
1539
  await page.goto(href, { waitUntil: "domcontentloaded" });
1319
1540
  await settlePage(page);
1320
- this.lastRefs.clear();
1541
+ this.clearRefs(page);
1321
1542
  const after = page.url();
1322
1543
  return {
1323
1544
  url: after,
1324
1545
  title: await page.title().catch(() => ""),
1325
1546
  changed: pathsDiffer(beforeUrl, after),
1326
1547
  href,
1327
- tabId: tabIdOf(page.context(), page),
1548
+ tabId: this.tabIdFor(page),
1328
1549
  warning: "Ref stamp missing; opened this ref's href directly."
1329
1550
  };
1330
1551
  }
@@ -1334,12 +1555,12 @@ var PlaywrightDriver = class {
1334
1555
  await settlePage(page);
1335
1556
  const afterUrl = page.url();
1336
1557
  const changed = pathsDiffer(beforeUrl, afterUrl);
1337
- this.lastRefs.clear();
1558
+ this.clearRefs(page);
1338
1559
  return {
1339
1560
  url: afterUrl,
1340
1561
  title: await page.title().catch(() => ""),
1341
1562
  changed,
1342
- tabId: tabIdOf(page.context(), page),
1563
+ tabId: this.tabIdFor(page),
1343
1564
  ...href !== "" ? { href } : {},
1344
1565
  ...!changed ? {
1345
1566
  warning: "Pathname unchanged after coordinate click. browser_snapshot again or browser_navigate by href."
@@ -1348,8 +1569,9 @@ var PlaywrightDriver = class {
1348
1569
  }
1349
1570
  async type(ref, text3) {
1350
1571
  const page = await this.requirePage();
1351
- if (this.lastRefs.get(ref) === void 0) {
1352
- throw new Error(`Unknown ref ${ref}; call browser_snapshot first`);
1572
+ const tabId = this.tabIdFor(page);
1573
+ if (this.tabs.ref(tabId, ref) === void 0) {
1574
+ throw new Error(this.tabs.unknownRefMessage(ref, tabId));
1353
1575
  }
1354
1576
  const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
1355
1577
  const count = await locator.count().catch(() => 0);
@@ -1364,12 +1586,12 @@ var PlaywrightDriver = class {
1364
1586
  await locator.pressSequentially(text3, { delay: 10 });
1365
1587
  }
1366
1588
  await settlePage(page);
1367
- this.lastRefs.clear();
1589
+ this.clearRefs(page);
1368
1590
  return {
1369
1591
  url: page.url(),
1370
1592
  title: await page.title().catch(() => ""),
1371
1593
  changed: false,
1372
- tabId: tabIdOf(page.context(), page)
1594
+ tabId: this.tabIdFor(page)
1373
1595
  };
1374
1596
  }
1375
1597
  async scroll(dy) {
@@ -1380,7 +1602,7 @@ var PlaywrightDriver = class {
1380
1602
  url: page.url(),
1381
1603
  title: await page.title().catch(() => ""),
1382
1604
  changed: false,
1383
- tabId: tabIdOf(page.context(), page)
1605
+ tabId: this.tabIdFor(page)
1384
1606
  };
1385
1607
  }
1386
1608
  async wait(input = {}) {
@@ -1401,7 +1623,7 @@ var PlaywrightDriver = class {
1401
1623
  url: page.url(),
1402
1624
  title: await page.title().catch(() => ""),
1403
1625
  matched,
1404
- tabId: tabIdOf(page.context(), page)
1626
+ tabId: this.tabIdFor(page)
1405
1627
  };
1406
1628
  }
1407
1629
  async screenshot() {
@@ -1410,7 +1632,7 @@ var PlaywrightDriver = class {
1410
1632
  return {
1411
1633
  mime: "image/png",
1412
1634
  base64: buf.toString("base64"),
1413
- tabId: tabIdOf(page.context(), page)
1635
+ tabId: this.tabIdFor(page)
1414
1636
  };
1415
1637
  }
1416
1638
  async listTabs() {
@@ -1419,25 +1641,151 @@ var PlaywrightDriver = class {
1419
1641
  return { tabs: [], boundTabId: null };
1420
1642
  }
1421
1643
  return {
1422
- tabs: await Promise.all(pages.map(async (p, index) => ({
1423
- tabId: index + 1,
1644
+ tabs: await Promise.all(pages.map(async (p) => ({
1645
+ tabId: this.tabIdFor(p),
1424
1646
  title: await p.title().catch(() => ""),
1425
1647
  url: p.url(),
1426
1648
  active: p === this.page,
1427
- // Session bind is layered in install.listTabs; driver marks the live page.
1428
- bound: p === this.page
1649
+ // Session bind and read-only scope are layered in install.listTabs.
1650
+ bound: p === this.page,
1651
+ readOnly: false
1429
1652
  }))),
1430
- boundTabId: this.page ? pages.indexOf(this.page) + 1 : null
1653
+ boundTabId: this.page === null ? null : this.tabIdFor(this.page)
1431
1654
  };
1432
1655
  }
1656
+ startCapture() {
1657
+ if (this.capture !== null) return;
1658
+ const context = this.context;
1659
+ if (context === null) return;
1660
+ this.capture = new CaptureBuffer(300);
1661
+ for (const page of context.pages()) this.attachCapture(page);
1662
+ context.on("page", (page) => this.attachCapture(page));
1663
+ }
1664
+ attachCapture(page) {
1665
+ const buffer = this.capture;
1666
+ if (buffer === null || this.captureStartedPages.has(page)) return;
1667
+ this.captureStartedPages.add(page);
1668
+ const tabId = this.tabIdFor(page);
1669
+ const stamp = () => Date.now();
1670
+ page.on("console", (message) => {
1671
+ try {
1672
+ buffer.push({
1673
+ kind: "console",
1674
+ at: stamp(),
1675
+ tabId,
1676
+ level: message.type(),
1677
+ // Console text can embed a request URL, so it gets the same masking as
1678
+ // the network layer; otherwise a failed fetch leaks its query string.
1679
+ text: clipText(redactText(message.text()), 500),
1680
+ ...message.location().url === "" ? {} : { location: redactText(`${message.location().url}:${message.location().lineNumber}`) }
1681
+ });
1682
+ } catch {
1683
+ }
1684
+ });
1685
+ page.on("pageerror", (error) => {
1686
+ buffer.push({
1687
+ kind: "console",
1688
+ at: stamp(),
1689
+ tabId,
1690
+ level: "pageerror",
1691
+ text: clipText(redactText(error instanceof Error ? error.message : String(error)), 500)
1692
+ });
1693
+ });
1694
+ page.on("request", (request) => {
1695
+ this.requestStart.set(request, performance.now());
1696
+ });
1697
+ page.on("response", (response) => {
1698
+ const request = response.request();
1699
+ const started = this.requestStart.get(request);
1700
+ buffer.push({
1701
+ kind: "request",
1702
+ at: stamp(),
1703
+ tabId,
1704
+ method: request.method(),
1705
+ url: redactUrl(response.url()),
1706
+ resourceType: request.resourceType(),
1707
+ status: response.status(),
1708
+ ...started === void 0 ? {} : { durationMs: Math.round(performance.now() - started) }
1709
+ });
1710
+ });
1711
+ page.on("requestfailed", (request) => {
1712
+ const started = this.requestStart.get(request);
1713
+ buffer.push({
1714
+ kind: "request",
1715
+ at: stamp(),
1716
+ tabId,
1717
+ method: request.method(),
1718
+ url: redactUrl(request.url()),
1719
+ resourceType: request.resourceType(),
1720
+ ...started === void 0 ? {} : { durationMs: Math.round(performance.now() - started) },
1721
+ failure: clipText(request.failure()?.errorText ?? "request failed", 160)
1722
+ });
1723
+ });
1724
+ }
1725
+ readCapture(input) {
1726
+ if (this.capture === null) return { entries: [], dropped: 0 };
1727
+ return this.capture.read(input.kind, {
1728
+ ...input.limit === void 0 ? {} : { limit: input.limit },
1729
+ ...input.clear === void 0 ? {} : { clear: input.clear }
1730
+ });
1731
+ }
1732
+ async emulate(input) {
1733
+ const page = await this.requirePage();
1734
+ const applied = [];
1735
+ const media = {};
1736
+ if (input.colorScheme !== void 0) {
1737
+ media.colorScheme = input.colorScheme === "reset" ? null : input.colorScheme;
1738
+ applied.push(`colorScheme=${input.colorScheme}`);
1739
+ }
1740
+ if (input.reducedMotion !== void 0) {
1741
+ media.reducedMotion = input.reducedMotion === "reset" ? null : input.reducedMotion;
1742
+ applied.push(`reducedMotion=${input.reducedMotion}`);
1743
+ }
1744
+ if (Object.keys(media).length > 0) await page.emulateMedia(media);
1745
+ if (input.viewport !== void 0) {
1746
+ const width = Math.min(Math.max(Math.trunc(input.viewport.width), 320), 3840);
1747
+ const height = Math.min(Math.max(Math.trunc(input.viewport.height), 240), 2160);
1748
+ await page.setViewportSize({ width, height });
1749
+ applied.push(`viewport=${width}x${height}`);
1750
+ }
1751
+ const tabId = this.tabIdFor(page);
1752
+ this.rememberEmulation(tabId, input);
1753
+ return {
1754
+ url: page.url(),
1755
+ title: await page.title().catch(() => ""),
1756
+ applied,
1757
+ tabId: this.tabIdFor(page)
1758
+ };
1759
+ }
1760
+ /** Record what is now emulated on this tab, so snapshot can echo it. */
1761
+ rememberEmulation(tabId, input) {
1762
+ const next = { ...this.emulationByTab.get(tabId) ?? {} };
1763
+ if (input.colorScheme !== void 0) {
1764
+ if (input.colorScheme === "reset") delete next.colorScheme;
1765
+ else next.colorScheme = input.colorScheme;
1766
+ }
1767
+ if (input.reducedMotion !== void 0) {
1768
+ if (input.reducedMotion === "reset") delete next.reducedMotion;
1769
+ else next.reducedMotion = input.reducedMotion;
1770
+ }
1771
+ if (input.viewport !== void 0) {
1772
+ next.viewport = {
1773
+ width: Math.min(Math.max(Math.trunc(input.viewport.width), 320), 3840),
1774
+ height: Math.min(Math.max(Math.trunc(input.viewport.height), 240), 2160)
1775
+ };
1776
+ }
1777
+ if (Object.keys(next).length === 0) this.emulationByTab.delete(tabId);
1778
+ else this.emulationByTab.set(tabId, next);
1779
+ }
1433
1780
  async followTab(tabId, _activate = false) {
1434
1781
  await this.ensureReady();
1435
- const pages = this.context?.pages() ?? [];
1436
- const page = pages[tabId - 1];
1437
- if (page === void 0) throw new Error(`No Playwright page for tabId ${tabId}`);
1438
- this.page = page;
1439
- this.lastRefs.clear();
1440
- return { tabId, url: page.url(), title: await page.title().catch(() => "") };
1782
+ const candidate = this.tabs.page(tabId);
1783
+ if (!this.isLivePage(candidate)) {
1784
+ throw new Error(`No running browser tab for tabId ${tabId} (it may have been closed); call browser_list_tabs for current ids`);
1785
+ }
1786
+ this.page = candidate;
1787
+ this.touch(candidate);
1788
+ return { tabId, url: candidate.url(), title: await candidate.title().catch(() => "") };
1441
1789
  }
1442
1790
  async bind(tabId, _sessionId) {
1443
1791
  return this.followTab(tabId, true);
@@ -1449,7 +1797,7 @@ var PlaywrightDriver = class {
1449
1797
  this.page = null;
1450
1798
  this.channel = null;
1451
1799
  this.launchedProfileDir = null;
1452
- this.lastRefs.clear();
1800
+ this.capture = null;
1453
1801
  if (ctx !== null) {
1454
1802
  await ctx.close().catch(() => void 0);
1455
1803
  }
@@ -1463,6 +1811,10 @@ function sleep(ms) {
1463
1811
  setTimeout(resolve17, ms);
1464
1812
  });
1465
1813
  }
1814
+ function clipText(text3, max) {
1815
+ const flat = text3.replace(/\s+/g, " ").trim();
1816
+ return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
1817
+ }
1466
1818
  async function settlePage(page, quietMs = 800) {
1467
1819
  await page.waitForLoadState("domcontentloaded").catch(() => void 0);
1468
1820
  await Promise.race([
@@ -1482,11 +1834,6 @@ async function adoptPopup(popup, beforeUrl) {
1482
1834
  const url = popup.isClosed() ? "" : popup.url();
1483
1835
  return /^https?:\/\//i.test(url) && pathsDiffer(beforeUrl, url);
1484
1836
  }
1485
- function tabIdOf(context, page) {
1486
- const pages = context.pages();
1487
- const index = pages.indexOf(page);
1488
- return index >= 0 ? index + 1 : 1;
1489
- }
1490
1837
  async function listHttpAnchors(page) {
1491
1838
  return page.evaluate(`(() => {
1492
1839
  var out = [];
@@ -1559,22 +1906,43 @@ function registerBrowserAgentPrompt(ctx) {
1559
1906
 
1560
1907
  // src/host/browser-agent/session-state.ts
1561
1908
  var MAX_AUDIT = 40;
1909
+ function emptyMemory() {
1910
+ return { refs: /* @__PURE__ */ new Set(), hrefs: /* @__PURE__ */ new Map(), names: /* @__PURE__ */ new Map(), dead: /* @__PURE__ */ new Set() };
1911
+ }
1562
1912
  var BrowserSessionState = class {
1563
1913
  tabBySession = /* @__PURE__ */ new Map();
1564
1914
  sessionByTab = /* @__PURE__ */ new Map();
1565
1915
  needsHumanBySession = /* @__PURE__ */ new Map();
1566
- /** Refs from the latest successful browser_snapshot for this session. */
1567
- lastRefsBySession = /* @__PURE__ */ new Map();
1568
- /** Optional href per ref from the latest snapshot (follow only that ref's href after a dead click). */
1569
- lastHrefBySession = /* @__PURE__ */ new Map();
1570
- /** Optional accessible name per ref from the latest snapshot (name-matched auto-nav). */
1571
- lastNameBySession = /* @__PURE__ */ new Map();
1572
- /** Refs that already failed a click with no navigation — block re-click until a fresh snapshot. */
1573
- deadClickRefsBySession = /* @__PURE__ */ new Map();
1916
+ /**
1917
+ * Snapshot memory lives with the tab, not the session: refs captured in a tab
1918
+ * stay valid when the session switches away and back (refs are unique per
1919
+ * driver, so there is no cross-tab aliasing).
1920
+ */
1921
+ memoryByTab = /* @__PURE__ */ new Map();
1922
+ /** Snapshots taken before a tab is bound (rare, first call) land here. */
1923
+ memoryUnbound = /* @__PURE__ */ new Map();
1574
1924
  /** Last http(s) page URL for approval origin when pageStatus is blank/about:blank. */
1575
1925
  lastHttpUrlBySession = /* @__PURE__ */ new Map();
1576
1926
  conflict = null;
1577
1927
  audit = [];
1928
+ /** Memory for this session's current tab, creating it on first use. */
1929
+ memoryOf(sessionId) {
1930
+ const tabId = this.tabBySession.get(sessionId);
1931
+ if (tabId === void 0) {
1932
+ let memory2 = this.memoryUnbound.get(sessionId);
1933
+ if (memory2 === void 0) {
1934
+ memory2 = emptyMemory();
1935
+ this.memoryUnbound.set(sessionId, memory2);
1936
+ }
1937
+ return memory2;
1938
+ }
1939
+ let memory = this.memoryByTab.get(tabId);
1940
+ if (memory === void 0) {
1941
+ memory = emptyMemory();
1942
+ this.memoryByTab.set(tabId, memory);
1943
+ }
1944
+ return memory;
1945
+ }
1578
1946
  bind(sessionId, tabId) {
1579
1947
  const prev = this.tabBySession.get(sessionId);
1580
1948
  if (prev !== void 0 && prev !== tabId) this.sessionByTab.delete(prev);
@@ -1590,15 +1958,49 @@ var BrowserSessionState = class {
1590
1958
  sessionOf(tabId) {
1591
1959
  return this.sessionByTab.get(tabId);
1592
1960
  }
1961
+ /** Tab ids that some session is bound to; idle-close must never take these. */
1962
+ boundTabIds() {
1963
+ return [...this.sessionByTab.keys()];
1964
+ }
1965
+ /**
1966
+ * The tab went away (closed by idle sweep or by the user): drop the binding and
1967
+ * the refs captured there, so the next tool call re-snapshots instead of
1968
+ * resolving refs that no longer exist.
1969
+ */
1970
+ unbindTab(tabId) {
1971
+ const sessionId = this.sessionByTab.get(tabId);
1972
+ this.sessionByTab.delete(tabId);
1973
+ this.memoryByTab.delete(tabId);
1974
+ if (sessionId === void 0) return void 0;
1975
+ if (this.tabBySession.get(sessionId) === tabId) this.tabBySession.delete(sessionId);
1976
+ this.memoryUnbound.delete(sessionId);
1977
+ if (this.conflict?.sessionId === sessionId) this.conflict = null;
1978
+ return sessionId;
1979
+ }
1980
+ /** Which tab still holds this ref (refs are driver-unique), if any. */
1981
+ tabHoldingRef(ref, exceptTabId) {
1982
+ for (const [tabId, memory] of this.memoryByTab) {
1983
+ if (tabId === exceptTabId) continue;
1984
+ if (memory.refs.has(ref)) return tabId;
1985
+ }
1986
+ return void 0;
1987
+ }
1988
+ /** Drop snapshot memory for tabs that no longer exist. */
1989
+ retainTabs(tabIds) {
1990
+ const alive = new Set(tabIds);
1991
+ for (const tabId of [...this.memoryByTab.keys()]) {
1992
+ if (!alive.has(tabId)) this.memoryByTab.delete(tabId);
1993
+ }
1994
+ }
1593
1995
  clearSession(sessionId) {
1594
1996
  const tabId = this.tabBySession.get(sessionId);
1595
1997
  this.tabBySession.delete(sessionId);
1596
- if (tabId !== void 0) this.sessionByTab.delete(tabId);
1998
+ if (tabId !== void 0) {
1999
+ this.sessionByTab.delete(tabId);
2000
+ this.memoryByTab.delete(tabId);
2001
+ }
2002
+ this.memoryUnbound.delete(sessionId);
1597
2003
  this.needsHumanBySession.delete(sessionId);
1598
- this.lastRefsBySession.delete(sessionId);
1599
- this.lastHrefBySession.delete(sessionId);
1600
- this.lastNameBySession.delete(sessionId);
1601
- this.deadClickRefsBySession.delete(sessionId);
1602
2004
  this.lastHttpUrlBySession.delete(sessionId);
1603
2005
  if (this.conflict?.sessionId === sessionId) this.conflict = null;
1604
2006
  for (let i = this.audit.length - 1; i >= 0; i -= 1) {
@@ -1606,36 +2008,36 @@ var BrowserSessionState = class {
1606
2008
  }
1607
2009
  }
1608
2010
  setLastRefs(sessionId, refs) {
1609
- this.lastRefsBySession.set(sessionId, new Set(refs.filter((ref) => Number.isFinite(ref))));
1610
- this.deadClickRefsBySession.delete(sessionId);
2011
+ const memory = this.memoryOf(sessionId);
2012
+ memory.refs = new Set(refs.filter((ref) => Number.isFinite(ref)));
2013
+ memory.dead = /* @__PURE__ */ new Set();
1611
2014
  }
1612
2015
  setLastHrefs(sessionId, hrefs) {
1613
- this.lastHrefBySession.set(sessionId, hrefs);
2016
+ this.memoryOf(sessionId).hrefs = new Map(hrefs);
1614
2017
  }
1615
2018
  setLastNames(sessionId, names) {
1616
- this.lastNameBySession.set(sessionId, names);
2019
+ this.memoryOf(sessionId).names = new Map(names);
1617
2020
  }
1618
2021
  clearLastRefs(sessionId) {
1619
- this.lastRefsBySession.delete(sessionId);
1620
- this.lastHrefBySession.delete(sessionId);
1621
- this.lastNameBySession.delete(sessionId);
2022
+ const memory = this.memoryOf(sessionId);
2023
+ memory.refs = /* @__PURE__ */ new Set();
2024
+ memory.hrefs = /* @__PURE__ */ new Map();
2025
+ memory.names = /* @__PURE__ */ new Map();
1622
2026
  }
1623
2027
  markDeadClickRef(sessionId, ref) {
1624
- const set = this.deadClickRefsBySession.get(sessionId) ?? /* @__PURE__ */ new Set();
1625
- set.add(ref);
1626
- this.deadClickRefsBySession.set(sessionId, set);
2028
+ this.memoryOf(sessionId).dead.add(ref);
1627
2029
  }
1628
2030
  isDeadClickRef(sessionId, ref) {
1629
- return this.deadClickRefsBySession.get(sessionId)?.has(ref) === true;
2031
+ return this.memoryOf(sessionId).dead.has(ref);
1630
2032
  }
1631
2033
  hasRef(sessionId, ref) {
1632
- return this.lastRefsBySession.get(sessionId)?.has(ref) === true;
2034
+ return this.memoryOf(sessionId).refs.has(ref);
1633
2035
  }
1634
2036
  hrefOfRef(sessionId, ref) {
1635
- return this.lastHrefBySession.get(sessionId)?.get(ref);
2037
+ return this.memoryOf(sessionId).hrefs.get(ref);
1636
2038
  }
1637
2039
  nameOfRef(sessionId, ref) {
1638
- return this.lastNameBySession.get(sessionId)?.get(ref);
2040
+ return this.memoryOf(sessionId).names.get(ref);
1639
2041
  }
1640
2042
  rememberHttpUrl(sessionId, url) {
1641
2043
  if (!/^https?:\/\//i.test(url)) return;
@@ -1645,7 +2047,7 @@ var BrowserSessionState = class {
1645
2047
  return this.lastHttpUrlBySession.get(sessionId);
1646
2048
  }
1647
2049
  lastRefList(sessionId) {
1648
- return [...this.lastRefsBySession.get(sessionId) ?? []];
2050
+ return [...this.memoryOf(sessionId).refs];
1649
2051
  }
1650
2052
  setConflict(conflict) {
1651
2053
  this.conflict = conflict;
@@ -1656,18 +2058,18 @@ var BrowserSessionState = class {
1656
2058
  currentConflict() {
1657
2059
  return this.conflict;
1658
2060
  }
1659
- setNeedsHuman(sessionId, detail) {
1660
- this.needsHumanBySession.set(sessionId, detail);
2061
+ setNeedsHuman(sessionId, detail, kind = "human") {
2062
+ this.needsHumanBySession.set(sessionId, { detail, kind });
1661
2063
  }
1662
2064
  clearNeedsHuman(sessionId) {
1663
2065
  this.needsHumanBySession.delete(sessionId);
1664
2066
  }
1665
2067
  needsHuman(sessionId) {
1666
- return this.needsHumanBySession.get(sessionId);
2068
+ return this.needsHumanBySession.get(sessionId)?.detail;
1667
2069
  }
1668
2070
  anyNeedsHuman() {
1669
- for (const [sessionId, detail] of this.needsHumanBySession) {
1670
- return { sessionId, detail };
2071
+ for (const [sessionId, value] of this.needsHumanBySession) {
2072
+ return { sessionId, detail: value.detail, kind: value.kind };
1671
2073
  }
1672
2074
  return null;
1673
2075
  }
@@ -1680,6 +2082,101 @@ var BrowserSessionState = class {
1680
2082
  }
1681
2083
  };
1682
2084
 
2085
+ // src/host/browser-agent/tab-scope.ts
2086
+ var TabScopeStore = class {
2087
+ readOnlyTabs = /* @__PURE__ */ new Set();
2088
+ setReadOnly(tabId, readOnly) {
2089
+ if (readOnly) {
2090
+ this.readOnlyTabs.add(tabId);
2091
+ return;
2092
+ }
2093
+ this.readOnlyTabs.delete(tabId);
2094
+ }
2095
+ isReadOnly(tabId) {
2096
+ return tabId !== void 0 && this.readOnlyTabs.has(tabId);
2097
+ }
2098
+ /** Drop scopes for tabs that no longer exist. */
2099
+ retain(tabIds) {
2100
+ const alive = new Set(tabIds);
2101
+ for (const tabId of [...this.readOnlyTabs]) {
2102
+ if (!alive.has(tabId)) this.readOnlyTabs.delete(tabId);
2103
+ }
2104
+ }
2105
+ clear() {
2106
+ this.readOnlyTabs.clear();
2107
+ }
2108
+ /** Model-facing refusal, shared so every mutating tool says the same thing. */
2109
+ refusal(tabId) {
2110
+ return `tab_read_only: tab ${tabId} is read-only (set by the user). Nothing was changed. Reading tools still work: browser_snapshot, browser_extract, browser_scroll, browser_wait. Ask the user to unlock the tab in the sidebar tab list, or open a new tab with browser_navigate({ newTab: true }).`;
2111
+ }
2112
+ };
2113
+
2114
+ // src/host/browser-agent/diagnose.ts
2115
+ var PROFILE_LOCK = /ProcessSingleton|SingletonLock|already in use|profile.*(?:lock|use)|EBUSY|EACCES|EPERM/i;
2116
+ var AVAILABILITY = { chrome: "chrome", edge: "edge", safari: "safari" };
2117
+ function usableBrowsers(input) {
2118
+ const { availability, platform } = input;
2119
+ const order = input.preference === "auto" ? platform === "win32" ? ["edge", "chrome"] : platform === "darwin" ? ["safari", "chrome"] : ["chrome"] : [AVAILABILITY[input.preference]];
2120
+ return order.filter((name2) => availability[name2] === true);
2121
+ }
2122
+ function diagnose(input) {
2123
+ return { ...classify(input), browsers: input.availability };
2124
+ }
2125
+ function classify(input) {
2126
+ const detail = typeof input.lastError === "string" && input.lastError.trim() !== "" ? input.lastError.trim() : void 0;
2127
+ if (!input.enabled) {
2128
+ return {
2129
+ code: "disabled",
2130
+ nextStep: "Browser agent is off. Ask the user to enable \u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent, then retry."
2131
+ };
2132
+ }
2133
+ if (input.ready) {
2134
+ return {
2135
+ code: "ok",
2136
+ nextStep: "Ready: page tools act on the bound tab listed above."
2137
+ };
2138
+ }
2139
+ const usable = usableBrowsers(input);
2140
+ if (detail !== void 0 && /WEBKIT_MISSING/i.test(detail)) {
2141
+ return {
2142
+ code: "webkit_missing",
2143
+ detail,
2144
+ nextStep: "The WebKit engine for the Safari option is not installed. Either run `npx playwright install webkit` and retry, or switch the browser setting to Chrome/Edge, which needs no extra download."
2145
+ };
2146
+ }
2147
+ if (input.preference === "safari" && !input.availability.safari) {
2148
+ return {
2149
+ code: "browser_missing",
2150
+ detail,
2151
+ nextStep: "Safari is not present on this machine, and the Safari option drives the WebKit engine. Switch the browser setting to Chrome, or on macOS install Safari first."
2152
+ };
2153
+ }
2154
+ if (usable.length === 0 && detail === void 0) {
2155
+ return {
2156
+ code: "browser_missing",
2157
+ nextStep: `No usable browser found for preference "${input.preference}" on ${input.platform}. Install Chrome (or Edge on Windows) or change the browser setting, then retry.`
2158
+ };
2159
+ }
2160
+ if (detail !== void 0 && PROFILE_LOCK.test(detail)) {
2161
+ return {
2162
+ code: "profile_locked",
2163
+ detail,
2164
+ nextStep: "The dedicated profile is still held by another process \u2014 usually a leftover agent browser window or a second Desktop instance. Close it (or quit the other instance), then retry; no settings change needed."
2165
+ };
2166
+ }
2167
+ if (detail !== void 0) {
2168
+ return {
2169
+ code: "launch_failed",
2170
+ detail,
2171
+ nextStep: "Launch failed. Check the browser choice in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent, and retry once. If it keeps failing, the detail above names the missing piece."
2172
+ };
2173
+ }
2174
+ return {
2175
+ code: "idle",
2176
+ nextStep: "Nothing launched yet. Call browser_navigate (or Alt+click a chat link) to launch the dedicated browser; do not ask the user to start it manually."
2177
+ };
2178
+ }
2179
+
1683
2180
  // src/host/browser-agent/tools.ts
1684
2181
  import { defineTool } from "@deepseek-ai/dsh-tools";
1685
2182
  var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
@@ -1714,9 +2211,21 @@ function formatSnapshot(body, extra) {
1714
2211
  typeof body.source === "string" ? `snapshot_source: ${body.source}` : null,
1715
2212
  typeof body.extensionVersion === "string" ? `extension: ${body.extensionVersion}` : null,
1716
2213
  typeof body.anchorCount === "number" ? `anchors_in_dom: ${body.anchorCount}` : null,
2214
+ body.harvest === void 0 ? null : `harvest: interactive=${body.harvest.interactive} controls=${body.harvest.controls} anchors=${body.harvest.anchors}`,
2215
+ body.emulation === void 0 ? null : `emulation: ${[
2216
+ body.emulation.colorScheme === void 0 ? null : `colorScheme=${body.emulation.colorScheme}`,
2217
+ body.emulation.reducedMotion === void 0 ? null : `reducedMotion=${body.emulation.reducedMotion}`,
2218
+ body.emulation.viewport === void 0 ? null : `viewport=${body.emulation.viewport.width}x${body.emulation.viewport.height}`
2219
+ ].filter((part) => part !== null).join(" ")}`,
1717
2220
  typeof body.note === "string" && body.note.trim() !== "" ? `note: ${body.note.trim()}` : null,
1718
2221
  ...extra ?? [],
1719
- "interactive (prefer refs that include href=\u2026 ; never invent URLs; re-snapshot after navigation):",
2222
+ (() => {
2223
+ const links = body.nodes.filter((node) => node.tag === "a").length;
2224
+ const controls = body.nodes.length - links;
2225
+ const shown = body.nodes.length;
2226
+ const tally = controls > 0 ? `${links} link / ${controls} control` : `${links} link`;
2227
+ return controls > 0 ? `interactive (${shown} shown: ${tally} \u2014 controls are at the end; prefer refs that include href=\u2026 ; never invent URLs; re-snapshot after navigation):` : `interactive (${shown} shown: ${tally}; prefer refs that include href=\u2026 ; never invent URLs; re-snapshot after navigation):`;
2228
+ })(),
1720
2229
  ...body.nodes.slice(0, 80).map((node) => `- [${node.ref}] ${node.role}${node.tag !== void 0 ? `/${node.tag}` : ""}${node.sensitive === true ? " [sensitive]" : ""}${typeof node.href === "string" && node.href !== "" ? ` href=${JSON.stringify(node.href)}` : ""} ${JSON.stringify(node.name)}`),
1721
2230
  "text_preview (short \u2014 use browser_extract for long/below-fold content):",
1722
2231
  body.textPreview.slice(0, 2e3)
@@ -1780,6 +2289,14 @@ function driverOf(options) {
1780
2289
  const value = options.driver;
1781
2290
  return typeof value === "function" ? value() : value;
1782
2291
  }
2292
+ function pickEnum(value, allowed, field) {
2293
+ if (value === void 0 || value === null || value === "") return void 0;
2294
+ const text3 = String(value).trim().toLowerCase();
2295
+ if (!allowed.includes(text3)) {
2296
+ throw new Error(`${field} must be one of: ${allowed.join(" | ")}`);
2297
+ }
2298
+ return text3;
2299
+ }
1783
2300
  function registerBrowserTools(ctx, options) {
1784
2301
  const disposers = [];
1785
2302
  const guardEnabled = () => {
@@ -1810,6 +2327,25 @@ function registerBrowserTools(ctx, options) {
1810
2327
  }
1811
2328
  await driverOf(options).ensureReady(startUrl);
1812
2329
  };
2330
+ const requireDebugTools = (tool) => {
2331
+ if (options.debugTools?.() === true) return;
2332
+ throw new Error(
2333
+ `${tool}: debug tools are off. Nothing ran. Ask the user to enable \u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent \u2192 \u8C03\u8BD5\u5DE5\u5177, then retry.`
2334
+ );
2335
+ };
2336
+ const requireWritableTab = (sessionId, tool) => {
2337
+ const scope = options.tabScope;
2338
+ if (scope === void 0) return;
2339
+ const tabId = options.sessions.tabOf(sessionId);
2340
+ if (tabId === void 0 || !scope.isReadOnly(tabId)) return;
2341
+ options.sessions.record({
2342
+ sessionId,
2343
+ tool,
2344
+ summary: `Blocked: tab ${tabId} is read-only`,
2345
+ outcome: "denied"
2346
+ });
2347
+ throw new Error(scope.refusal(tabId));
2348
+ };
1813
2349
  const requireMutation = async (exec, tool, summary, url) => {
1814
2350
  const sessionId = sessionIdOf(exec);
1815
2351
  let effectiveUrl = typeof url === "string" && /^https?:\/\//i.test(url) ? url : void 0;
@@ -1856,13 +2392,14 @@ function registerBrowserTools(ctx, options) {
1856
2392
  }
1857
2393
  };
1858
2394
  const pauseForHuman = async (input) => {
1859
- options.sessions.setNeedsHuman(input.sessionId, input.detail);
2395
+ options.sessions.setNeedsHuman(input.sessionId, input.detail, input.kind ?? "human");
1860
2396
  await focusBoundTab(input.sessionId, input.tabId);
1861
2397
  try {
1862
2398
  return await options.human.waitForHuman({
1863
2399
  sessionId: input.sessionId,
1864
2400
  prompt: input.prompt,
1865
2401
  detail: input.detail,
2402
+ ...input.kind === void 0 ? {} : { kind: input.kind },
1866
2403
  ...input.url === void 0 ? {} : { url: input.url },
1867
2404
  signal: input.signal
1868
2405
  });
@@ -1889,6 +2426,13 @@ function registerBrowserTools(ctx, options) {
1889
2426
  };
1890
2427
  const requireFreshRef = (sessionId, ref, tool) => {
1891
2428
  if (options.sessions.hasRef(sessionId, ref)) return;
2429
+ const active = options.sessions.tabOf(sessionId);
2430
+ const owner = options.sessions.tabHoldingRef(ref, active);
2431
+ if (owner !== void 0) {
2432
+ throw new Error(
2433
+ `${tool}: ref ${ref} belongs to tab ${owner}, but tab ${active ?? "none"} is active. Switch back with browser_follow_tab (tabId ${owner}) \u2014 that tab's refs are still valid \u2014 or call browser_snapshot to get refs for the current tab.`
2434
+ );
2435
+ }
1892
2436
  const known = options.sessions.lastRefList(sessionId);
1893
2437
  if (known.length === 0) {
1894
2438
  throw new Error(
@@ -1976,30 +2520,29 @@ function registerBrowserTools(ctx, options) {
1976
2520
  };
1977
2521
  disposers.push(ctx.tools.register(textTool(
1978
2522
  "browser_status",
1979
- "Check the Desktop dedicated-browser bridge (Mac: Safari/Chrome; Windows: Chrome/Edge): connection, bound tab URL/title/tabId. Use this for any real-browser / webpage / on-page task. Auto-launches the dedicated browser when disconnected \u2014 do not ask the user to launch manually first.",
2523
+ "Check the Desktop dedicated browser (Mac: Safari/Chrome; Windows: Chrome/Edge): whether it is usable, the bound tab URL/title/tabId, and \u2014 when something is wrong \u2014 the concrete next step. 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.",
1980
2524
  {},
1981
2525
  async (_args, exec) => {
1982
2526
  guardEnabled();
1983
2527
  const sessionId = sessionIdOf(exec);
2528
+ const diag = options.diagnosis?.();
2529
+ const diagLines = diag === void 0 ? [] : [
2530
+ `diagnosis: ${diag.code}`,
2531
+ `next: ${diag.nextStep}`,
2532
+ diag.detail === void 0 ? null : `detail: ${diag.detail}`
2533
+ ].filter((line) => line !== null);
1984
2534
  const st = driverOf(options).status();
1985
- if (!st.listening) {
1986
- return [
1987
- `driver: ${st.kind}`,
1988
- "bridge: not listening",
1989
- st.port !== void 0 ? `port: ${st.port}` : null,
1990
- `error: ${st.lastError ?? "not started"}`
1991
- ].filter((line) => line !== null).join("\n");
1992
- }
1993
- if (!st.ready) {
2535
+ if (!st.listening || !st.ready) {
1994
2536
  try {
1995
2537
  await ensureConnected();
1996
2538
  } catch (error) {
1997
2539
  return [
1998
2540
  `driver: ${st.kind}`,
1999
- st.endpoint !== void 0 ? `bridge: listening on ${st.endpoint}` : "bridge: listening",
2000
- "extension: disconnected",
2541
+ `browser: ${st.listening ? "listening, not ready" : "not started"}`,
2542
+ st.endpoint !== void 0 ? `endpoint: ${st.endpoint}` : null,
2543
+ ...diagLines,
2001
2544
  formatBridgeError(error)
2002
- ].join("\n");
2545
+ ].filter((line) => line !== null).join("\n");
2003
2546
  }
2004
2547
  }
2005
2548
  try {
@@ -2008,8 +2551,8 @@ function registerBrowserTools(ctx, options) {
2008
2551
  await rememberTab(sessionId, tab.tabId);
2009
2552
  return [
2010
2553
  `driver: ${driverOf(options).kind}`,
2011
- "bridge: ok",
2012
- "extension: connected",
2554
+ "browser: ready",
2555
+ ...diagLines,
2013
2556
  `url: ${tab.url}`,
2014
2557
  `title: ${tab.title}`,
2015
2558
  `tabId: ${tab.tabId}`,
@@ -2020,9 +2563,12 @@ function registerBrowserTools(ctx, options) {
2020
2563
  ].filter((line) => line !== null).join("\n");
2021
2564
  } catch (error) {
2022
2565
  noteHuman(sessionId, {}, error);
2023
- return `driver: ${driverOf(options).kind}
2024
- bridge: listening
2025
- extension: connected but status failed: ${formatBridgeError(error)}`;
2566
+ return [
2567
+ `driver: ${driverOf(options).kind}`,
2568
+ "browser: ready, status call failed",
2569
+ ...diagLines,
2570
+ formatBridgeError(error)
2571
+ ].join("\n");
2026
2572
  }
2027
2573
  }
2028
2574
  )));
@@ -2087,6 +2633,8 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2087
2633
  sessionId,
2088
2634
  prompt,
2089
2635
  detail: prompt.slice(0, 240),
2636
+ // A generic "do this in the browser" request must not wear the login card.
2637
+ kind: "ask",
2090
2638
  ...url === void 0 ? {} : { url },
2091
2639
  ...tabId === void 0 ? {} : { tabId },
2092
2640
  signal: exec.signal
@@ -2132,6 +2680,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2132
2680
  if (url === "") throw new Error("url is required");
2133
2681
  await ensureConnected(url);
2134
2682
  await ensureSessionTab(sessionId);
2683
+ if (!newTab) requireWritableTab(sessionId, "browser_navigate");
2135
2684
  await requireMutation(
2136
2685
  exec,
2137
2686
  "browser_navigate",
@@ -2187,6 +2736,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2187
2736
  if (!Number.isFinite(ref)) throw new Error("ref must be a number");
2188
2737
  await ensureConnected();
2189
2738
  await ensureSessionTab(sessionId);
2739
+ requireWritableTab(sessionId, "browser_click");
2190
2740
  let url;
2191
2741
  try {
2192
2742
  url = (await driverOf(options).pageStatus()).url;
@@ -2307,6 +2857,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2307
2857
  if (!Number.isFinite(ref)) throw new Error("ref must be a number");
2308
2858
  await ensureConnected();
2309
2859
  await ensureSessionTab(sessionId);
2860
+ requireWritableTab(sessionId, "browser_type");
2310
2861
  let url;
2311
2862
  try {
2312
2863
  url = (await driverOf(options).pageStatus()).url;
@@ -2546,6 +3097,138 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
2546
3097
  ].filter((line) => line !== null).join("\n");
2547
3098
  }
2548
3099
  )));
3100
+ disposers.push(ctx.tools.register(textTool(
3101
+ "browser_network",
3102
+ "Read buffered network activity for the bound tab (method, url, status, duration, failures). Read-only; no approval. Headers, cookies and bodies are never recorded; secret-looking query values are masked. Requires the Debug tools switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent. Capture starts automatically when that switch is on, so navigate first, then read.",
3103
+ {
3104
+ limit: {
3105
+ type: "number",
3106
+ description: "Newest N entries (default 40, max 200)."
3107
+ },
3108
+ clear: {
3109
+ type: "boolean",
3110
+ description: "Drop the returned entries from the buffer."
3111
+ }
3112
+ },
3113
+ async (args, exec) => {
3114
+ guardEnabled();
3115
+ requireDebugTools("browser_network");
3116
+ const sessionId = sessionIdOf(exec);
3117
+ await ensureConnected();
3118
+ await ensureSessionTab(sessionId);
3119
+ const limit = Number(args.limit);
3120
+ const driver = driverOf(options);
3121
+ driver.startCapture();
3122
+ const { entries, dropped } = driver.readCapture({
3123
+ kind: "network",
3124
+ ...Number.isFinite(limit) ? { limit } : {},
3125
+ ...args.clear === true ? { clear: true } : {}
3126
+ });
3127
+ const rows = entries.filter((entry) => entry.kind === "request");
3128
+ if (rows.length === 0) {
3129
+ return "no network activity buffered yet. Navigate or wait for the page to load, then call browser_network again.";
3130
+ }
3131
+ return [
3132
+ `network entries: ${rows.length}${dropped > 0 ? ` (${dropped} older dropped)` : ""}`,
3133
+ ...rows.map((entry) => {
3134
+ const status = entry.kind !== "request" ? "" : entry.status === void 0 ? entry.failure ?? "failed" : String(entry.status);
3135
+ const ms = entry.kind === "request" && entry.durationMs !== void 0 ? ` ${entry.durationMs}ms` : "";
3136
+ const method = entry.kind === "request" ? entry.method : "GET";
3137
+ return `- [${entry.tabId}] ${status} ${method} ${entry.kind === "request" ? entry.url : ""}${ms}`;
3138
+ })
3139
+ ].join("\n");
3140
+ }
3141
+ )));
3142
+ disposers.push(ctx.tools.register(textTool(
3143
+ "browser_console",
3144
+ "Read buffered console messages and uncaught page errors for the bound tab. Read-only; no approval. Requires the Debug tools switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent.",
3145
+ {
3146
+ limit: {
3147
+ type: "number",
3148
+ description: "Newest N entries (default 40, max 200)."
3149
+ },
3150
+ clear: {
3151
+ type: "boolean",
3152
+ description: "Drop the returned entries from the buffer."
3153
+ }
3154
+ },
3155
+ async (args, exec) => {
3156
+ guardEnabled();
3157
+ requireDebugTools("browser_console");
3158
+ const sessionId = sessionIdOf(exec);
3159
+ await ensureConnected();
3160
+ await ensureSessionTab(sessionId);
3161
+ const limit = Number(args.limit);
3162
+ const driver = driverOf(options);
3163
+ driver.startCapture();
3164
+ const { entries } = driver.readCapture({
3165
+ kind: "console",
3166
+ ...Number.isFinite(limit) ? { limit } : {},
3167
+ ...args.clear === true ? { clear: true } : {}
3168
+ });
3169
+ if (entries.length === 0) {
3170
+ return "no console output buffered yet. Reload or interact with the page, then call browser_console again.";
3171
+ }
3172
+ return [
3173
+ `console entries: ${entries.length}`,
3174
+ ...entries.map((entry) => {
3175
+ if (entry.kind !== "console") return "";
3176
+ const where = entry.location === void 0 ? "" : ` (${entry.location})`;
3177
+ return `- [${entry.tabId}] ${entry.level}: ${entry.text}${where}`;
3178
+ })
3179
+ ].filter((line) => line !== "").join("\n");
3180
+ }
3181
+ )));
3182
+ disposers.push(ctx.tools.register(textTool(
3183
+ "browser_emulate",
3184
+ "Change how the bound page renders for testing: color scheme, reduced motion, viewport size. Read-only on page data; no approval. Requires the Debug tools switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent. Call browser_snapshot afterwards to see the effect.",
3185
+ {
3186
+ colorScheme: {
3187
+ type: "string",
3188
+ description: "light | dark | no-preference | reset"
3189
+ },
3190
+ reducedMotion: {
3191
+ type: "string",
3192
+ description: "reduce | no-preference | reset"
3193
+ },
3194
+ width: {
3195
+ type: "number",
3196
+ description: "Viewport width in CSS px (320\u20133840)."
3197
+ },
3198
+ height: {
3199
+ type: "number",
3200
+ description: "Viewport height in CSS px (240\u20132160)."
3201
+ }
3202
+ },
3203
+ async (args, exec) => {
3204
+ guardEnabled();
3205
+ requireDebugTools("browser_emulate");
3206
+ const sessionId = sessionIdOf(exec);
3207
+ const colorScheme = pickEnum(args.colorScheme, ["light", "dark", "no-preference", "reset"], "colorScheme");
3208
+ const reducedMotion = pickEnum(args.reducedMotion, ["reduce", "no-preference", "reset"], "reducedMotion");
3209
+ const width = Number(args.width);
3210
+ const height = Number(args.height);
3211
+ const hasViewport = Number.isFinite(width) && Number.isFinite(height);
3212
+ if (colorScheme === void 0 && reducedMotion === void 0 && !hasViewport) {
3213
+ throw new Error("browser_emulate: pass colorScheme, reducedMotion, or width+height");
3214
+ }
3215
+ await ensureConnected();
3216
+ await ensureSessionTab(sessionId);
3217
+ const result = await runBridge(() => driverOf(options).emulate({
3218
+ ...colorScheme === void 0 ? {} : { colorScheme },
3219
+ ...reducedMotion === void 0 ? {} : { reducedMotion },
3220
+ ...hasViewport ? { viewport: { width, height } } : {}
3221
+ }));
3222
+ await rememberTab(sessionId, result.tabId);
3223
+ return [
3224
+ `emulated: ${result.applied.join(", ")}`,
3225
+ `url: ${result.url}`,
3226
+ `title: ${result.title}`,
3227
+ result.tabId !== void 0 ? `tabId: ${result.tabId}` : null,
3228
+ "Action: browser_snapshot now echoes the emulation line, so you can confirm the mode the page is in."
3229
+ ].filter((line) => line !== null).join("\n");
3230
+ }
3231
+ )));
2549
3232
  disposers.push(ctx.tools.register(textTool(
2550
3233
  "browser_list_tabs",
2551
3234
  "List open browser tabs (id, title, url, active, bound). Read-only; no approval. Use with browser_follow_tab to bind this session to another tab.",
@@ -2626,10 +3309,34 @@ title: ${result.title}`;
2626
3309
  }
2627
3310
 
2628
3311
  // src/host/browser-agent/install.ts
3312
+ var IDLE_TICK_MS = 6e4;
3313
+ var IDLE_CLOSE_MS = 10 * 6e4;
2629
3314
  function installBrowserAgent(ctx, options) {
2630
3315
  const approval = new BrowserApprovalGate();
2631
3316
  const human = new BrowserHumanGate();
2632
3317
  const sessions = new BrowserSessionState();
3318
+ const tabScope = new TabScopeStore();
3319
+ let availabilityCache = null;
3320
+ const browserAvailability = () => {
3321
+ if (availabilityCache !== null) return availabilityCache;
3322
+ availabilityCache = {
3323
+ chrome: resolveBrowserExecutable("chrome") !== null,
3324
+ edge: resolveBrowserExecutable("edge") !== null,
3325
+ safari: resolveBrowserExecutable("safari") !== null
3326
+ };
3327
+ return availabilityCache;
3328
+ };
3329
+ const diagnoseNow = () => {
3330
+ const status = activeDriver?.status();
3331
+ return diagnose({
3332
+ enabled: options.enabled(),
3333
+ ready: status?.ready === true,
3334
+ preference: options.browserPreference(),
3335
+ platform: process.platform,
3336
+ lastError: status?.lastError ?? null,
3337
+ availability: browserAvailability()
3338
+ });
3339
+ };
2633
3340
  let unregisterTools = null;
2634
3341
  let unregisterPrompt = null;
2635
3342
  let active = false;
@@ -2667,6 +3374,7 @@ function installBrowserAgent(ctx, options) {
2667
3374
  const previousPreference = mountedPreference;
2668
3375
  activeDriver = null;
2669
3376
  mountedPreference = null;
3377
+ tabScope.clear();
2670
3378
  const pw = playwrightDriver;
2671
3379
  playwrightDriver = null;
2672
3380
  if (pw !== null) {
@@ -2724,6 +3432,9 @@ function installBrowserAgent(ctx, options) {
2724
3432
  approval,
2725
3433
  human,
2726
3434
  sessions,
3435
+ tabScope,
3436
+ debugTools: () => options.debugTools?.() === true,
3437
+ diagnosis: diagnoseNow,
2727
3438
  // Gate on settings only — `active` flips false during driver align and
2728
3439
  // must not make browser_* look "disabled" mid-turn.
2729
3440
  enabled: () => options.enabled(),
@@ -2738,6 +3449,7 @@ function installBrowserAgent(ctx, options) {
2738
3449
  try {
2739
3450
  if (preferenceMatchesRunning(preference)) {
2740
3451
  await requireDriver().ensureReady(startUrl);
3452
+ primeCapture();
2741
3453
  active = true;
2742
3454
  return { ok: true };
2743
3455
  }
@@ -2758,6 +3470,7 @@ function installBrowserAgent(ctx, options) {
2758
3470
  ensureToolsRegistered();
2759
3471
  active = true;
2760
3472
  await activeDriver.ensureReady(startUrl);
3473
+ primeCapture();
2761
3474
  mountedPreference = preference;
2762
3475
  return { ok: true };
2763
3476
  } catch (error) {
@@ -2768,12 +3481,20 @@ function installBrowserAgent(ctx, options) {
2768
3481
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
2769
3482
  }
2770
3483
  };
3484
+ const primeCapture = () => {
3485
+ if (options.debugTools?.() !== true) return;
3486
+ try {
3487
+ requireDriver().startCapture();
3488
+ } catch {
3489
+ }
3490
+ };
2771
3491
  const mount = () => {
2772
3492
  const preference = options.browserPreference();
2773
3493
  createDriver(preference);
2774
3494
  ensureToolsRegistered();
2775
3495
  };
2776
3496
  const refresh = () => {
3497
+ availabilityCache = null;
2777
3498
  const want = options.enabled();
2778
3499
  if (!want) {
2779
3500
  if (!active && playwrightDriver === null && unregisterTools === null && !switchPending) {
@@ -2797,6 +3518,35 @@ function installBrowserAgent(ctx, options) {
2797
3518
  active = true;
2798
3519
  };
2799
3520
  refresh();
3521
+ const sweepIdleTabs = async () => {
3522
+ if (!options.enabled() || options.idleClose?.() !== true) return;
3523
+ const driver = activeDriver;
3524
+ if (driver === null || driver.status().ready !== true) return;
3525
+ try {
3526
+ const closed = await driver.sweepIdleTabs({
3527
+ idleMs: IDLE_CLOSE_MS,
3528
+ keep: sessions.boundTabIds()
3529
+ });
3530
+ for (const tabId of closed) {
3531
+ const sessionId = sessions.unbindTab(tabId);
3532
+ tabScope.setReadOnly(tabId, false);
3533
+ sessions.record({
3534
+ sessionId: sessionId ?? "host",
3535
+ tool: "browser_idle_close",
3536
+ summary: `Closed idle tab ${tabId}`,
3537
+ outcome: "ok"
3538
+ });
3539
+ }
3540
+ } catch (error) {
3541
+ ctx.logger.warn(
3542
+ `agent-enhancer: idle tab sweep failed: ${error instanceof Error ? error.message : String(error)}`
3543
+ );
3544
+ }
3545
+ };
3546
+ const idleTimer = setInterval(() => {
3547
+ void sweepIdleTabs();
3548
+ }, IDLE_TICK_MS);
3549
+ idleTimer.unref?.();
2800
3550
  return {
2801
3551
  approval,
2802
3552
  human,
@@ -2804,6 +3554,9 @@ function installBrowserAgent(ctx, options) {
2804
3554
  driverStatus() {
2805
3555
  return activeDriver?.status() ?? null;
2806
3556
  },
3557
+ diagnose() {
3558
+ return diagnoseNow();
3559
+ },
2807
3560
  activeProfileDir() {
2808
3561
  if (mountedPreference !== null) {
2809
3562
  return browserAgentProfileDirFor(options.profileRoot, mountedPreference);
@@ -2823,10 +3576,13 @@ function installBrowserAgent(ctx, options) {
2823
3576
  }
2824
3577
  try {
2825
3578
  const body = await activeDriver.listTabs();
3579
+ tabScope.retain(body.tabs.map((tab) => tab.tabId));
3580
+ sessions.retainTabs(body.tabs.map((tab) => tab.tabId));
2826
3581
  return {
2827
3582
  tabs: body.tabs.map((tab) => ({
2828
3583
  ...tab,
2829
- bound: sessions.sessionOf(tab.tabId) !== void 0
3584
+ bound: sessions.sessionOf(tab.tabId) !== void 0,
3585
+ readOnly: tabScope.isReadOnly(tab.tabId)
2830
3586
  })),
2831
3587
  boundTabId: body.boundTabId
2832
3588
  };
@@ -2834,6 +3590,17 @@ function installBrowserAgent(ctx, options) {
2834
3590
  return { tabs: [], boundTabId: null };
2835
3591
  }
2836
3592
  },
3593
+ setTabReadOnly(input) {
3594
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
3595
+ tabScope.setReadOnly(input.tabId, input.readOnly);
3596
+ sessions.record({
3597
+ sessionId: "sidebar",
3598
+ tool: "browser_tab_read_only",
3599
+ summary: `${input.readOnly ? "Read-only" : "Writable"} tab ${input.tabId}`,
3600
+ outcome: "ok"
3601
+ });
3602
+ return { ok: true };
3603
+ },
2837
3604
  async selectTab(input) {
2838
3605
  if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
2839
3606
  await switchGate.catch(() => void 0);
@@ -2977,6 +3744,7 @@ function installBrowserAgent(ctx, options) {
2977
3744
  },
2978
3745
  async dispose() {
2979
3746
  active = false;
3747
+ clearInterval(idleTimer);
2980
3748
  approval.clearAll();
2981
3749
  human.clearAll();
2982
3750
  await switchGate.catch(() => void 0);
@@ -6613,7 +7381,7 @@ async function deleteSessionNow(options) {
6613
7381
  }
6614
7382
 
6615
7383
  // src/host/web-chat-bridge/import-session.ts
6616
- import { randomUUID as randomUUID6 } from "node:crypto";
7384
+ import { randomUUID as randomUUID7 } from "node:crypto";
6617
7385
  import { existsSync as existsSync5, mkdirSync as mkdirSync2, statSync } from "node:fs";
6618
7386
  import { resolve as resolve2 } from "node:path";
6619
7387
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
@@ -6624,7 +7392,7 @@ import {
6624
7392
  } from "@deepseek-ai/dsh-llm";
6625
7393
  import {
6626
7394
  SessionId,
6627
- SessionSeq as SessionSeq2
7395
+ SessionSeq as SessionSeq3
6628
7396
  } from "@deepseek-ai/dsh-session";
6629
7397
 
6630
7398
  // src/host/extra-folders/pick.ts
@@ -6855,6 +7623,413 @@ async function pickFileNow(signal, options = {}) {
6855
7623
  );
6856
7624
  }
6857
7625
 
7626
+ // src/host/web-chat-bridge/convert-conversation.ts
7627
+ import { randomUUID as randomUUID6 } from "node:crypto";
7628
+ import {
7629
+ MessageId as MessageId2,
7630
+ ToolCallId
7631
+ } from "@deepseek-ai/dsh-llm";
7632
+ import { SessionSeq as SessionSeq2 } from "@deepseek-ai/dsh-session";
7633
+ import {
7634
+ fetchMetaFromValue,
7635
+ formatFetchOutput,
7636
+ formatSearchOutput,
7637
+ searchMetaFromValue
7638
+ } from "@deepseek-ai/dsh-tool-web";
7639
+ var WEB_CHAT_IMPORTED_MODEL_SOURCE = {
7640
+ provider: "web-chat-bridge",
7641
+ model: "imported-history"
7642
+ };
7643
+ var FETCH_OUTPUT_CHARS = 4e3;
7644
+ var UNFINISHED_STATUS_CODES = /* @__PURE__ */ new Map([
7645
+ ["FAILED", "DEEPSEEK_EXPORT_FAILED"],
7646
+ ["TIMEOUT", "DEEPSEEK_EXPORT_TIMEOUT"],
7647
+ ["CONTEXT_LENGTH_EXCEEDED", "DEEPSEEK_EXPORT_CONTEXT_LENGTH_EXCEEDED"],
7648
+ ["INCOMPLETE", "DEEPSEEK_EXPORT_INCOMPLETE"],
7649
+ ["WIP", "DEEPSEEK_EXPORT_WIP"]
7650
+ ]);
7651
+ var WebChatConvertError = class extends Error {
7652
+ name = "WebChatConvertError";
7653
+ };
7654
+ function nonEmpty(value) {
7655
+ return value === null || value === void 0 || value.trim().length === 0 ? void 0 : value;
7656
+ }
7657
+ function selectWebChatBranch(messages, currentMessageId) {
7658
+ if (messages.length === 0) {
7659
+ throw new WebChatConvertError("conversation has no messages");
7660
+ }
7661
+ const ids = new Set(messages.map((message) => message.id));
7662
+ const resolved = messages.map((message) => {
7663
+ if (message.parent_id === null || ids.has(message.parent_id)) return message;
7664
+ return { ...message, parent_id: null };
7665
+ });
7666
+ const hasParents = resolved.some((message) => message.parent_id !== null);
7667
+ if (!hasParents) return resolved;
7668
+ const byId = /* @__PURE__ */ new Map();
7669
+ let newest;
7670
+ for (const message of resolved) {
7671
+ if (byId.has(message.id)) {
7672
+ return resolved;
7673
+ }
7674
+ byId.set(message.id, message);
7675
+ if (newest === void 0 || message.id > newest.id) newest = message;
7676
+ }
7677
+ if (newest === void 0) {
7678
+ throw new WebChatConvertError("conversation has no messages");
7679
+ }
7680
+ const selected = currentMessageId === null || currentMessageId === void 0 ? void 0 : byId.get(currentMessageId);
7681
+ const chain = [];
7682
+ for (let message = selected ?? newest; ; ) {
7683
+ if (chain.length === byId.size) {
7684
+ return resolved;
7685
+ }
7686
+ chain.push(message);
7687
+ if (message.parent_id === null) return chain.reverse();
7688
+ const parent = byId.get(message.parent_id);
7689
+ if (parent === void 0) return resolved;
7690
+ message = parent;
7691
+ }
7692
+ }
7693
+ function convertWebChatConversation(input, options = {}) {
7694
+ const createId = options.createId ?? (() => randomUUID6());
7695
+ const chain = selectWebChatBranch(input.messages, input.currentMessageId);
7696
+ const log = new LogBuilder(createId, options.provenancePrefix ?? "");
7697
+ const title = input.title !== null && input.title.trim() !== "" ? input.title.trim() : null;
7698
+ let turn = 0;
7699
+ let withdrawn = 0;
7700
+ for (let index = 0; index < chain.length; index++) {
7701
+ const user = chain[index];
7702
+ if (user.role !== "USER") continue;
7703
+ const next = chain[index + 1];
7704
+ const reply = next?.role === "ASSISTANT" ? next : void 0;
7705
+ if (reply !== void 0) index++;
7706
+ if (reply?.status === "CONTENT_FILTER") {
7707
+ withdrawn++;
7708
+ continue;
7709
+ }
7710
+ turn++;
7711
+ log.turn(turn, user, reply);
7712
+ if (turn === 1 && title !== null) {
7713
+ log.add({
7714
+ type: "session/title",
7715
+ data: { title, messageSeqs: [], source: { kind: "user" } }
7716
+ });
7717
+ }
7718
+ }
7719
+ if (turn === 0) {
7720
+ throw new WebChatConvertError(
7721
+ withdrawn === 0 ? "conversation has no user message" : "every question of the conversation was withdrawn by content filtering"
7722
+ );
7723
+ }
7724
+ return { title, events: log.events };
7725
+ }
7726
+ var LogBuilder = class {
7727
+ constructor(createId, provenancePrefix) {
7728
+ this.createId = createId;
7729
+ this.provenancePrefix = provenancePrefix;
7730
+ }
7731
+ createId;
7732
+ provenancePrefix;
7733
+ events = [];
7734
+ time = Date.now();
7735
+ add(event) {
7736
+ const seq = SessionSeq2(this.events.length);
7737
+ this.events.push({ ...event, seq, time: this.time });
7738
+ return seq;
7739
+ }
7740
+ turn(turn, user, reply) {
7741
+ this.add({ type: "turn/start", data: { turn } });
7742
+ let step = 1;
7743
+ this.add({ type: "step/start", data: { turn, step } });
7744
+ if (turn === 1) {
7745
+ const head = {
7746
+ id: MessageId2(this.id()),
7747
+ role: "system",
7748
+ content: [],
7749
+ source: { kind: "system-prompt" }
7750
+ };
7751
+ this.add({
7752
+ type: "system/message",
7753
+ data: { turn, step, message: head },
7754
+ surfaceOp: "append"
7755
+ });
7756
+ }
7757
+ this.add({
7758
+ type: "user/message",
7759
+ data: this.userMessage(user, turn === 1),
7760
+ surfaceOp: "append"
7761
+ });
7762
+ if (reply === void 0) {
7763
+ this.closeTurn(turn, step, failure(
7764
+ "DEEPSEEK_EXPORT_NO_REPLY",
7765
+ "The export contains no reply to this message."
7766
+ ));
7767
+ return;
7768
+ }
7769
+ const { steps, template } = this.replySteps(reply);
7770
+ const excluded = excludedReply(reply, template, steps.length);
7771
+ if (excluded !== void 0) {
7772
+ this.closeTurn(turn, step, { kind: "error", error: excluded });
7773
+ return;
7774
+ }
7775
+ for (const [position, { content, calls, elapsedMs }] of steps.entries()) {
7776
+ if (position > 0) {
7777
+ step++;
7778
+ this.add({ type: "step/start", data: { turn, step } });
7779
+ }
7780
+ this.time += elapsedMs;
7781
+ this.add({
7782
+ type: "assistant/message",
7783
+ data: {
7784
+ turn,
7785
+ step,
7786
+ message: assistantMessage(this.id(), [
7787
+ ...content,
7788
+ ...calls.map((call) => call.block)
7789
+ ]),
7790
+ stream: []
7791
+ },
7792
+ surfaceOp: "append"
7793
+ });
7794
+ const callSeqs = calls.map(({ block }) => this.add({
7795
+ type: "tool/call",
7796
+ data: {
7797
+ turn,
7798
+ step,
7799
+ callId: block.id,
7800
+ name: block.name,
7801
+ arguments: block.arguments
7802
+ }
7803
+ }));
7804
+ for (const [callIndex, call] of calls.entries()) {
7805
+ this.add({
7806
+ type: "tool/result",
7807
+ data: {
7808
+ turn,
7809
+ step,
7810
+ message: toolResult(this.id(), call),
7811
+ ...call.meta === void 0 ? {} : { meta: call.meta }
7812
+ },
7813
+ surfaceOp: "append",
7814
+ sourceEventSeqs: [callSeqs[callIndex]]
7815
+ });
7816
+ }
7817
+ if (position < steps.length - 1) {
7818
+ this.add({ type: "step/end", data: { turn, step } });
7819
+ }
7820
+ }
7821
+ this.closeTurn(turn, step, { kind: "completed" });
7822
+ }
7823
+ closeTurn(turn, step, reason) {
7824
+ this.add({ type: "step/end", data: { turn, step } });
7825
+ this.add({ type: "turn/end", data: { turn, reason } });
7826
+ }
7827
+ id() {
7828
+ return this.createId();
7829
+ }
7830
+ userMessage(message, firstTurn) {
7831
+ const lines = [];
7832
+ for (const fragment of message.fragments) {
7833
+ if (fragment.type === "REQUEST") lines.push(fragment.content);
7834
+ }
7835
+ let text3 = lines.join("\n");
7836
+ if (firstTurn && this.provenancePrefix !== "") {
7837
+ text3 = `${this.provenancePrefix}${text3}`;
7838
+ }
7839
+ const content = [{ type: "text", text: text3 }];
7840
+ return {
7841
+ id: MessageId2(this.id()),
7842
+ role: "user",
7843
+ content,
7844
+ source: { kind: "user" }
7845
+ };
7846
+ }
7847
+ replySteps(reply) {
7848
+ const steps = [];
7849
+ let template;
7850
+ let current = emptyStep();
7851
+ const pushStep = () => {
7852
+ if (current.content.length === 0 && current.calls.length === 0) return;
7853
+ steps.push(current);
7854
+ current = emptyStep();
7855
+ };
7856
+ const appendContent = (block) => {
7857
+ if (current.calls.length > 0) pushStep();
7858
+ current.content.push(block);
7859
+ };
7860
+ const appendCall = (call, stage) => {
7861
+ if (stage !== null) {
7862
+ if (current.stage !== null && stage !== current.stage) pushStep();
7863
+ current.stage = stage;
7864
+ }
7865
+ current.calls.push(call);
7866
+ };
7867
+ for (const fragment of reply.fragments) {
7868
+ switch (fragment.type) {
7869
+ case "THINK":
7870
+ if (fragment.content.length > 0) {
7871
+ appendContent({ type: "reasoning", text: fragment.content });
7872
+ }
7873
+ current.elapsedMs += Math.round((fragment.elapsed_secs ?? 0) * 1e3);
7874
+ break;
7875
+ case "RESPONSE":
7876
+ if (fragment.content.length > 0) {
7877
+ appendContent({ type: "text", text: fragment.content });
7878
+ }
7879
+ break;
7880
+ case "TOOL_SEARCH": {
7881
+ if (fragment.status === "WIP") break;
7882
+ const call = searchCall(this.id(), fragment);
7883
+ if (call !== void 0) appendCall(call, fragment.stage_id ?? null);
7884
+ break;
7885
+ }
7886
+ case "TOOL_OPEN": {
7887
+ const url = nonEmpty(fragment.url);
7888
+ if (fragment.status === "WIP" || url === void 0) break;
7889
+ appendCall(openCall(this.id(), fragment, url), fragment.stage_id ?? null);
7890
+ break;
7891
+ }
7892
+ case "READ_LINK": {
7893
+ const text3 = linkLines(fragment.results);
7894
+ if (text3 !== void 0) appendContent({ type: "text", text: text3 });
7895
+ break;
7896
+ }
7897
+ case "TEMPLATE_RESPONSE":
7898
+ template ??= fragment.content;
7899
+ break;
7900
+ case "REQUEST":
7901
+ break;
7902
+ default: {
7903
+ const _exhaustive = fragment;
7904
+ throw new WebChatConvertError(`unexpected fragment ${String(_exhaustive)}`);
7905
+ }
7906
+ }
7907
+ }
7908
+ pushStep();
7909
+ return { steps, template };
7910
+ }
7911
+ };
7912
+ function emptyStep() {
7913
+ return { content: [], calls: [], elapsedMs: 0, stage: null };
7914
+ }
7915
+ function excludedReply(reply, template, stepCount) {
7916
+ if (template !== void 0) {
7917
+ return { code: "DEEPSEEK_EXPORT_TEMPLATE_RESPONSE", message: template };
7918
+ }
7919
+ if (reply.status !== "FINISHED") {
7920
+ return {
7921
+ code: UNFINISHED_STATUS_CODES.get(reply.status) ?? "DEEPSEEK_EXPORT_UNFINISHED_REPLY",
7922
+ message: `The original reply ended with status ${JSON.stringify(reply.status)} and is excluded from the model context.`
7923
+ };
7924
+ }
7925
+ return stepCount === 0 ? {
7926
+ code: "DEEPSEEK_EXPORT_EMPTY_REPLY",
7927
+ message: "The original reply has no importable content."
7928
+ } : void 0;
7929
+ }
7930
+ function failure(code, message) {
7931
+ return { kind: "error", error: { code, message } };
7932
+ }
7933
+ function linkLines(results) {
7934
+ const lines = [];
7935
+ for (const result of results) {
7936
+ const url = nonEmpty(result.url);
7937
+ const title = nonEmpty(result.title);
7938
+ if (url !== void 0) lines.push(`[${title ?? url}](${url})`);
7939
+ else if (title !== void 0) lines.push(title);
7940
+ }
7941
+ return lines.length === 0 ? void 0 : lines.join("\n");
7942
+ }
7943
+ function assistantMessage(id, content) {
7944
+ return {
7945
+ id: MessageId2(id),
7946
+ role: "assistant",
7947
+ content,
7948
+ source: { kind: "model", ...WEB_CHAT_IMPORTED_MODEL_SOURCE }
7949
+ };
7950
+ }
7951
+ function toolResult(id, call) {
7952
+ return {
7953
+ id: MessageId2(id),
7954
+ role: "tool",
7955
+ content: call.result,
7956
+ isError: call.isError,
7957
+ source: { kind: "tool", callId: call.block.id },
7958
+ toolCallId: call.block.id
7959
+ };
7960
+ }
7961
+ function searchCall(id, fragment) {
7962
+ const queries = fragment.queries.filter((query) => query.trim().length > 0);
7963
+ const block = {
7964
+ type: "tool-call",
7965
+ id: ToolCallId(id),
7966
+ name: "web_search",
7967
+ arguments: JSON.stringify({ queries })
7968
+ };
7969
+ if (fragment.status === "FAILED") {
7970
+ return {
7971
+ block,
7972
+ result: [{ type: "text", text: "Error: the export records this search as failed." }],
7973
+ isError: true
7974
+ };
7975
+ }
7976
+ if (queries.length === 0) return void 0;
7977
+ const result = {
7978
+ sources: fragment.results.map((source) => {
7979
+ const title = nonEmpty(source.title);
7980
+ const snippet = nonEmpty(source.snippet);
7981
+ const publishedAt = nonEmpty(source.published_at);
7982
+ return {
7983
+ url: source.url,
7984
+ ...title === void 0 ? {} : { title },
7985
+ ...snippet === void 0 ? {} : { snippet },
7986
+ ...publishedAt === void 0 ? {} : { publishedAt }
7987
+ };
7988
+ }),
7989
+ truncated: false
7990
+ };
7991
+ return {
7992
+ block,
7993
+ result: [{ type: "text", text: formatSearchOutput(result) }],
7994
+ isError: false,
7995
+ meta: searchMetaFromValue(result)
7996
+ };
7997
+ }
7998
+ function openCall(id, fragment, url) {
7999
+ const block = {
8000
+ type: "tool-call",
8001
+ id: ToolCallId(id),
8002
+ name: "web_fetch",
8003
+ arguments: JSON.stringify({ url })
8004
+ };
8005
+ if (fragment.status !== "FINISHED") {
8006
+ return {
8007
+ block,
8008
+ result: [{ type: "text", text: "Error: the page could not be opened." }],
8009
+ isError: true
8010
+ };
8011
+ }
8012
+ const title = nonEmpty(fragment.title);
8013
+ const notice = "The page content is not included in the DeepSeek chat export.";
8014
+ const value = {
8015
+ url,
8016
+ statusCode: 200,
8017
+ truncated: false,
8018
+ body: {
8019
+ kind: "text",
8020
+ content: title === void 0 ? notice : `${title}
8021
+
8022
+ ${notice}`
8023
+ }
8024
+ };
8025
+ return {
8026
+ block,
8027
+ result: [{ type: "text", text: formatFetchOutput(value, FETCH_OUTPUT_CHARS) }],
8028
+ isError: false,
8029
+ meta: fetchMetaFromValue(value, FETCH_OUTPUT_CHARS)
8030
+ };
8031
+ }
8032
+
6858
8033
  // src/host/web-chat-bridge/limits.ts
6859
8034
  var WEB_CHAT_MAX_TEXT_BYTES = 5 * 1024 * 1024;
6860
8035
  var WEB_CHAT_MAX_MESSAGES = 5e3;
@@ -6936,6 +8111,9 @@ function resolveWebChatImportTitle(transcript) {
6936
8111
  if (raw !== "") return raw;
6937
8112
  return "Imported chat";
6938
8113
  }
8114
+ function transcriptHasRichMessages(transcript) {
8115
+ return Array.isArray(transcript.messages) && transcript.messages.length > 0;
8116
+ }
6939
8117
  function closeOpenTurn(session, turn) {
6940
8118
  session.append("turn/end", { turn, reason: { kind: "completed" } });
6941
8119
  }
@@ -6951,7 +8129,7 @@ function appendSessionTitle(session, title, firstUserMessageSeq) {
6951
8129
  if (trimmed === "") return;
6952
8130
  session.append("session/title", {
6953
8131
  title: trimmed,
6954
- messageSeqs: firstUserMessageSeq === void 0 ? [] : [SessionSeq2(firstUserMessageSeq)],
8132
+ messageSeqs: firstUserMessageSeq === void 0 ? [] : [SessionSeq3(firstUserMessageSeq)],
6955
8133
  source: { kind: "fallback" }
6956
8134
  });
6957
8135
  }
@@ -6983,6 +8161,12 @@ function appendProtectedSystemHead(session, turn, step) {
6983
8161
  ]);
6984
8162
  }
6985
8163
  function appendTranscript(session, transcript) {
8164
+ if (transcriptHasRichMessages(transcript)) {
8165
+ throw new WebChatImportError(
8166
+ "import-failed",
8167
+ "Rich web-chat transcripts require seed import"
8168
+ );
8169
+ }
6986
8170
  const provenance = importProvenancePrefix(transcript);
6987
8171
  const turns = transcript.turns;
6988
8172
  let turn = 1;
@@ -7041,11 +8225,29 @@ function appendTranscript(session, transcript) {
7041
8225
  appendSessionTitle(session, resolveWebChatImportTitle(transcript), firstUserMessageSeq);
7042
8226
  }
7043
8227
  function buildWebChatImportSeed(transcript) {
8228
+ if (transcriptHasRichMessages(transcript)) {
8229
+ try {
8230
+ const converted = convertWebChatConversation({
8231
+ title: resolveWebChatImportTitle(transcript),
8232
+ currentMessageId: transcript.currentMessageId,
8233
+ messages: transcript.messages
8234
+ }, {
8235
+ createId: () => randomUUID7(),
8236
+ provenancePrefix: importProvenancePrefix(transcript)
8237
+ });
8238
+ return [...converted.events];
8239
+ } catch (error) {
8240
+ if (error instanceof WebChatConvertError) {
8241
+ throw new WebChatImportError("invalid-transcript", error.message);
8242
+ }
8243
+ throw error;
8244
+ }
8245
+ }
7044
8246
  const events = [];
7045
8247
  const recordOne = (type, data, intent) => {
7046
8248
  const event = {
7047
8249
  type,
7048
- seq: SessionSeq2(events.length),
8250
+ seq: SessionSeq3(events.length),
7049
8251
  time: Date.now(),
7050
8252
  data,
7051
8253
  ...intent?.surfaceOp === void 0 ? {} : { surfaceOp: intent.surfaceOp }
@@ -7088,7 +8290,7 @@ function errorDetail(error) {
7088
8290
  }
7089
8291
  async function openAgentWorkSession(input, cwd) {
7090
8292
  const agents = input.agents;
7091
- if (typeof agents.createSession === "function") {
8293
+ if (typeof agents.createSession === "function" && !transcriptHasRichMessages(input.transcript)) {
7092
8294
  let created;
7093
8295
  try {
7094
8296
  created = await agents.createSession({
@@ -7118,7 +8320,7 @@ async function openAgentWorkSession(input, cwd) {
7118
8320
  if (typeof agents.create !== "function") {
7119
8321
  throw new WebChatImportError("import-failed", "Agent registry is unavailable");
7120
8322
  }
7121
- const sessionId = SessionId(`session-${randomUUID6()}`);
8323
+ const sessionId = SessionId(`session-${randomUUID7()}`);
7122
8324
  const seed = buildWebChatImportSeed(input.transcript);
7123
8325
  let handle;
7124
8326
  try {
@@ -7665,35 +8867,208 @@ function conversationsFromBytes(filename, bytes) {
7665
8867
  } catch {
7666
8868
  }
7667
8869
  }
7668
- return out;
8870
+ return out;
8871
+ }
8872
+ if (lowerName.endsWith(".json") || bytes[0] === 123 || bytes[0] === 91) {
8873
+ const text3 = bytes.toString("utf8");
8874
+ let parsed;
8875
+ try {
8876
+ parsed = JSON.parse(text3);
8877
+ } catch {
8878
+ throw new Error("unrecognized-export: invalid json");
8879
+ }
8880
+ return conversationsFromJsonValue(parsed, extractTitleFromMarkdown(filename));
8881
+ }
8882
+ if (lowerName.endsWith(".md") || lowerName.endsWith(".txt")) {
8883
+ return parseTextConversations(bytes.toString("utf8"), filename);
8884
+ }
8885
+ throw new Error("unrecognized-export: unsupported file type");
8886
+ }
8887
+ function analyzeWebChatExport(input) {
8888
+ assertPayloadSize(input.bytes);
8889
+ const conversations = conversationsFromBytes(input.filename, input.bytes);
8890
+ const items = toCatalogItems(input.filename, conversations);
8891
+ if (items.length === 0) {
8892
+ throw new Error("No messages found in export");
8893
+ }
8894
+ return {
8895
+ items,
8896
+ truncated: conversations.length > items.length
8897
+ };
8898
+ }
8899
+
8900
+ // src/host/web-chat-bridge/fragments.ts
8901
+ function nonEmptyString(value) {
8902
+ if (typeof value !== "string") return void 0;
8903
+ const trimmed = value.trim();
8904
+ return trimmed === "" ? void 0 : trimmed;
8905
+ }
8906
+ function optionalNumber(value) {
8907
+ if (value === null) return null;
8908
+ if (typeof value === "number" && Number.isFinite(value)) return value;
8909
+ return void 0;
8910
+ }
8911
+ function parseSearchResults(raw) {
8912
+ if (!Array.isArray(raw)) return [];
8913
+ const out = [];
8914
+ for (const row of raw) {
8915
+ if (row === null || typeof row !== "object") continue;
8916
+ const item = row;
8917
+ const url = nonEmptyString(item.url);
8918
+ if (url === void 0) continue;
8919
+ out.push({
8920
+ url,
8921
+ title: typeof item.title === "string" || item.title === null ? item.title : void 0,
8922
+ snippet: typeof item.snippet === "string" || item.snippet === null ? item.snippet : void 0,
8923
+ published_at: typeof item.published_at === "string" || item.published_at === null ? item.published_at : void 0
8924
+ });
8925
+ }
8926
+ return out;
8927
+ }
8928
+ function parseReadLinkResults(raw) {
8929
+ if (!Array.isArray(raw)) return [];
8930
+ const out = [];
8931
+ for (const row of raw) {
8932
+ if (row === null || typeof row !== "object") continue;
8933
+ const item = row;
8934
+ out.push({
8935
+ url: typeof item.url === "string" || item.url === null ? item.url : void 0,
8936
+ title: typeof item.title === "string" || item.title === null ? item.title : void 0
8937
+ });
8938
+ }
8939
+ return out;
8940
+ }
8941
+ function parseWebChatFragment(raw) {
8942
+ if (raw === null || typeof raw !== "object") return void 0;
8943
+ const item = raw;
8944
+ const type = String(item.type ?? "").toUpperCase();
8945
+ switch (type) {
8946
+ case "REQUEST": {
8947
+ const content = typeof item.content === "string" ? item.content : "";
8948
+ return { type: "REQUEST", content };
8949
+ }
8950
+ case "RESPONSE": {
8951
+ const content = typeof item.content === "string" ? item.content : "";
8952
+ return { type: "RESPONSE", content };
8953
+ }
8954
+ case "THINK": {
8955
+ const content = typeof item.content === "string" ? item.content : "";
8956
+ return {
8957
+ type: "THINK",
8958
+ content,
8959
+ elapsed_secs: optionalNumber(item.elapsed_secs)
8960
+ };
8961
+ }
8962
+ case "TEMPLATE_RESPONSE": {
8963
+ const content = typeof item.content === "string" ? item.content : "";
8964
+ return { type: "TEMPLATE_RESPONSE", content };
8965
+ }
8966
+ case "TOOL_SEARCH": {
8967
+ const queries = Array.isArray(item.queries) ? item.queries.filter((q) => typeof q === "string") : [];
8968
+ return {
8969
+ type: "TOOL_SEARCH",
8970
+ queries,
8971
+ results: parseSearchResults(item.results),
8972
+ status: typeof item.status === "string" ? item.status : void 0,
8973
+ stage_id: optionalNumber(item.stage_id)
8974
+ };
8975
+ }
8976
+ case "TOOL_OPEN": {
8977
+ const url = item.url === null ? null : typeof item.url === "string" ? item.url : null;
8978
+ return {
8979
+ type: "TOOL_OPEN",
8980
+ status: typeof item.status === "string" ? item.status : "FINISHED",
8981
+ url,
8982
+ title: typeof item.title === "string" || item.title === null ? item.title : void 0,
8983
+ stage_id: optionalNumber(item.stage_id)
8984
+ };
8985
+ }
8986
+ case "READ_LINK":
8987
+ return { type: "READ_LINK", results: parseReadLinkResults(item.results) };
8988
+ default:
8989
+ return void 0;
7669
8990
  }
7670
- if (lowerName.endsWith(".json") || bytes[0] === 123 || bytes[0] === 91) {
7671
- const text3 = bytes.toString("utf8");
7672
- let parsed;
7673
- try {
7674
- parsed = JSON.parse(text3);
7675
- } catch {
7676
- throw new Error("unrecognized-export: invalid json");
7677
- }
7678
- return conversationsFromJsonValue(parsed, extractTitleFromMarkdown(filename));
8991
+ }
8992
+ function normalizeExportRole(raw) {
8993
+ if (typeof raw !== "string") return null;
8994
+ const key = raw.trim().toUpperCase();
8995
+ if (key === "USER" || key === "HUMAN") return "USER";
8996
+ if (key === "ASSISTANT" || key === "AI" || key === "MODEL") return "ASSISTANT";
8997
+ return null;
8998
+ }
8999
+ function messageTextFallback(item) {
9000
+ const content = item.content ?? item.text ?? item.message;
9001
+ if (typeof content === "string") return content;
9002
+ if (Array.isArray(content)) {
9003
+ return content.map((part) => {
9004
+ if (typeof part === "string") return part;
9005
+ if (part && typeof part === "object" && "text" in part) {
9006
+ const text3 = Reflect.get(part, "text");
9007
+ return typeof text3 === "string" ? text3 : "";
9008
+ }
9009
+ return "";
9010
+ }).filter(Boolean).join("\n");
7679
9011
  }
7680
- if (lowerName.endsWith(".md") || lowerName.endsWith(".txt")) {
7681
- return parseTextConversations(bytes.toString("utf8"), filename);
9012
+ return "";
9013
+ }
9014
+ function numberId(raw) {
9015
+ if (typeof raw === "number" && Number.isFinite(raw)) return Math.trunc(raw);
9016
+ if (typeof raw === "string" && raw.trim() !== "") {
9017
+ const parsed = Number(raw);
9018
+ if (Number.isFinite(parsed)) return Math.trunc(parsed);
7682
9019
  }
7683
- throw new Error("unrecognized-export: unsupported file type");
9020
+ return void 0;
7684
9021
  }
7685
- function analyzeWebChatExport(input) {
7686
- assertPayloadSize(input.bytes);
7687
- const conversations = conversationsFromBytes(input.filename, input.bytes);
7688
- const items = toCatalogItems(input.filename, conversations);
7689
- if (items.length === 0) {
7690
- throw new Error("No messages found in export");
9022
+ function parseWebChatRichMessage(raw, fallbackId) {
9023
+ if (raw === null || typeof raw !== "object") return null;
9024
+ const item = raw;
9025
+ const role = normalizeExportRole(item.role ?? item.author ?? item.speaker);
9026
+ if (role === null) return null;
9027
+ const id = numberId(item.id) ?? numberId(item.message_id) ?? fallbackId;
9028
+ const parent_id = numberId(item.parent_id) ?? numberId(item.parent_message_id) ?? null;
9029
+ const fragments = [];
9030
+ if (Array.isArray(item.fragments)) {
9031
+ for (const frag of item.fragments) {
9032
+ const parsed = parseWebChatFragment(frag);
9033
+ if (parsed !== void 0) fragments.push(parsed);
9034
+ }
9035
+ }
9036
+ if (fragments.length === 0) {
9037
+ const text3 = messageTextFallback(item);
9038
+ if (role === "USER") fragments.push({ type: "REQUEST", content: text3 });
9039
+ else fragments.push({ type: "RESPONSE", content: text3 });
7691
9040
  }
7692
9041
  return {
7693
- items,
7694
- truncated: conversations.length > items.length
9042
+ id,
9043
+ parent_id,
9044
+ role,
9045
+ status: typeof item.status === "string" && item.status.trim() !== "" ? item.status.trim() : "FINISHED",
9046
+ inserted_at: typeof item.inserted_at === "string" ? item.inserted_at : void 0,
9047
+ fragments
7695
9048
  };
7696
9049
  }
9050
+ function previewTextFromFragments(fragments, role) {
9051
+ const prefer = role === "USER" ? "REQUEST" : "RESPONSE";
9052
+ const preferred = [];
9053
+ for (const frag of fragments) {
9054
+ if (frag.type === prefer && frag.content.trim() !== "") {
9055
+ preferred.push(frag.content.trim());
9056
+ }
9057
+ }
9058
+ return preferred.join("\n\n");
9059
+ }
9060
+ function richMessagesToPreviewTurns(messages) {
9061
+ const turns = [];
9062
+ for (const message of messages) {
9063
+ const text3 = previewTextFromFragments(message.fragments, message.role);
9064
+ if (text3 === "") continue;
9065
+ turns.push({
9066
+ role: message.role === "USER" ? "user" : "assistant",
9067
+ text: text3
9068
+ });
9069
+ }
9070
+ return turns;
9071
+ }
7697
9072
 
7698
9073
  // src/host/web-chat-bridge/share-link.ts
7699
9074
  var SHARE_URL_RE = /(?:https?:\/\/chat\.deepseek\.com)?\/share\/([A-Za-z0-9_-]+)/i;
@@ -7712,53 +9087,8 @@ function webChatSharePageUrl(shareId) {
7712
9087
  function webChatShareContentApiUrl(shareId) {
7713
9088
  return `https://chat.deepseek.com/api/v0/share/content?share_id=${encodeURIComponent(shareId)}`;
7714
9089
  }
7715
- function normalizeRole2(raw) {
7716
- if (typeof raw !== "string") return null;
7717
- const key = raw.trim().toLowerCase();
7718
- if (key === "user" || key === "human") return "user";
7719
- if (key === "assistant" || key === "ai" || key === "model") return "assistant";
7720
- return null;
7721
- }
7722
- function messageText2(raw) {
7723
- if (typeof raw === "string") return raw.trim();
7724
- if (Array.isArray(raw)) {
7725
- return raw.map((part) => {
7726
- if (typeof part === "string") return part;
7727
- if (part && typeof part === "object" && "text" in part) {
7728
- const text3 = Reflect.get(part, "text");
7729
- return typeof text3 === "string" ? text3 : "";
7730
- }
7731
- return "";
7732
- }).filter(Boolean).join("\n").trim();
7733
- }
7734
- return "";
7735
- }
7736
- function fragmentsText(fragments, preferTypes) {
7737
- if (!Array.isArray(fragments)) return "";
7738
- const preferred = new Set(preferTypes.map((type) => type.toUpperCase()));
7739
- const preferredParts = [];
7740
- const fallbackParts = [];
7741
- for (const frag of fragments) {
7742
- if (frag === null || typeof frag !== "object") continue;
7743
- const type = String(Reflect.get(frag, "type") ?? "").toUpperCase();
7744
- const content = Reflect.get(frag, "content");
7745
- if (typeof content !== "string" || content.trim() === "") continue;
7746
- const text3 = content.trim();
7747
- if (type === "THINK" || type === "TIP" || type.startsWith("TOOL_")) {
7748
- if (preferred.size === 0) fallbackParts.push(text3);
7749
- continue;
7750
- }
7751
- if (preferred.size === 0 || preferred.has(type)) preferredParts.push(text3);
7752
- else fallbackParts.push(text3);
7753
- }
7754
- if (preferredParts.length > 0) return preferredParts.join("\n\n");
7755
- return fallbackParts.join("\n\n");
7756
- }
7757
- function rowText(item, role) {
7758
- const direct = messageText2(item.content ?? item.text ?? item.message);
7759
- if (direct) return direct;
7760
- if (role === "user") return fragmentsText(item.fragments, ["REQUEST"]);
7761
- return fragmentsText(item.fragments, ["RESPONSE"]);
9090
+ function utf8ByteLength(text3) {
9091
+ return new TextEncoder().encode(text3).length;
7762
9092
  }
7763
9093
  function assertTurns(turns) {
7764
9094
  if (turns.length === 0) {
@@ -7769,12 +9099,28 @@ function assertTurns(turns) {
7769
9099
  }
7770
9100
  let bytes = 0;
7771
9101
  for (const turn of turns) {
7772
- bytes += Buffer.byteLength(turn.text, "utf8");
9102
+ bytes += utf8ByteLength(turn.text);
7773
9103
  if (bytes > WEB_CHAT_MAX_TEXT_BYTES) {
7774
9104
  throw new Error(`Share content exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
7775
9105
  }
7776
9106
  }
7777
9107
  }
9108
+ function assertRichBudget(messages) {
9109
+ if (messages.length > WEB_CHAT_MAX_MESSAGES) {
9110
+ throw new Error(`Exceeds message limit (${WEB_CHAT_MAX_MESSAGES})`);
9111
+ }
9112
+ let bytes = 0;
9113
+ for (const message of messages) {
9114
+ for (const frag of message.fragments) {
9115
+ if ("content" in frag && typeof frag.content === "string") {
9116
+ bytes += utf8ByteLength(frag.content);
9117
+ }
9118
+ if (bytes > WEB_CHAT_MAX_TEXT_BYTES) {
9119
+ throw new Error(`Share content exceeds ${WEB_CHAT_MAX_TEXT_BYTES} byte limit`);
9120
+ }
9121
+ }
9122
+ }
9123
+ }
7778
9124
  function bizRecord(data) {
7779
9125
  if (data === null || typeof data !== "object") return null;
7780
9126
  const root = data;
@@ -7789,42 +9135,63 @@ function bizRecord(data) {
7789
9135
  if (biz !== null && typeof biz === "object") return biz;
7790
9136
  return root;
7791
9137
  }
7792
- function turnsFromBizRecord(record2) {
9138
+ function messagesFromBizRecord(record2) {
7793
9139
  const rowsRaw = record2.messages ?? record2.chat_messages;
7794
9140
  const rows = Array.isArray(rowsRaw) ? rowsRaw : [];
7795
- const turns = [];
7796
- for (const row of rows) {
7797
- if (row === null || typeof row !== "object") continue;
7798
- const item = row;
7799
- const role = normalizeRole2(item.role ?? item.author ?? item.speaker);
7800
- if (!role) continue;
7801
- const text3 = rowText(item, role);
7802
- if (!text3) continue;
7803
- turns.push({ role, text: text3 });
9141
+ const messages = [];
9142
+ for (let i = 0; i < rows.length; i++) {
9143
+ const parsed = parseWebChatRichMessage(rows[i], i + 1);
9144
+ if (parsed !== null) messages.push(parsed);
7804
9145
  }
7805
- return turns;
9146
+ return messages;
7806
9147
  }
7807
- function parseWebChatShareContent(data, options) {
7808
- const record2 = bizRecord(data);
7809
- if (record2 === null) {
7810
- throw new Error("unrecognized-share: empty response");
9148
+ function coerceMessageId(raw) {
9149
+ if (raw === null) return null;
9150
+ if (typeof raw === "number" && Number.isFinite(raw)) return Math.trunc(raw);
9151
+ if (typeof raw === "string" && raw.trim() !== "") {
9152
+ const parsed = Number(raw);
9153
+ if (Number.isFinite(parsed)) return Math.trunc(parsed);
7811
9154
  }
7812
- const titleRaw = record2.title;
7813
- const title = typeof titleRaw === "string" && titleRaw.trim() !== "" ? titleRaw.trim() : `Shared chat ${options.shareId}`;
7814
- const turns = turnsFromBizRecord(record2);
9155
+ return void 0;
9156
+ }
9157
+ function currentMessageIdOf(record2) {
9158
+ const fromRoot = coerceMessageId(record2.current_message_id);
9159
+ if (fromRoot !== void 0) return fromRoot;
9160
+ const session = Reflect.get(record2, "chat_session");
9161
+ if (session !== null && typeof session === "object") {
9162
+ return coerceMessageId(Reflect.get(session, "current_message_id"));
9163
+ }
9164
+ return void 0;
9165
+ }
9166
+ function transcriptFromBiz(record2, title, source) {
9167
+ const messages = messagesFromBizRecord(record2);
9168
+ assertRichBudget(messages);
9169
+ const turns = richMessagesToPreviewTurns(messages);
7815
9170
  assertTurns(turns);
9171
+ const currentMessageId = currentMessageIdOf(record2);
7816
9172
  return {
7817
9173
  title,
7818
9174
  turns,
9175
+ messages,
9176
+ ...currentMessageId === void 0 ? {} : { currentMessageId },
7819
9177
  partial: false,
7820
- source: {
7821
- kind: "share-link",
7822
- url: options.shareUrl,
7823
- chatSessionId: options.shareId,
7824
- capturedAt: (/* @__PURE__ */ new Date()).toISOString()
7825
- }
9178
+ source
7826
9179
  };
7827
9180
  }
9181
+ function parseWebChatShareContent(data, options) {
9182
+ const record2 = bizRecord(data);
9183
+ if (record2 === null) {
9184
+ throw new Error("unrecognized-share: empty response");
9185
+ }
9186
+ const titleRaw = record2.title;
9187
+ const title = typeof titleRaw === "string" && titleRaw.trim() !== "" ? titleRaw.trim() : `Shared chat ${options.shareId}`;
9188
+ return transcriptFromBiz(record2, title, {
9189
+ kind: "share-link",
9190
+ url: options.shareUrl,
9191
+ chatSessionId: options.shareId,
9192
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString()
9193
+ });
9194
+ }
7828
9195
  async function fetchWebChatShareContent(shareId, signal) {
7829
9196
  signal.throwIfAborted();
7830
9197
  const response = await fetch(webChatShareContentApiUrl(shareId), {
@@ -12220,7 +13587,7 @@ function installAutoSessionRoute(ctx, options) {
12220
13587
  const settings = options.settings();
12221
13588
  const map = autoRouteMapOf(settings);
12222
13589
  const note = (agent === void 0 ? void 0 : notes.get(agent)) ?? loggedTurn(asAgent(agent));
12223
- const classify = settings.autoClassifierEnabled ? createClassifier({ prepareCall: innerPrepare }, map.classifier) : void 0;
13590
+ const classify2 = settings.autoClassifierEnabled ? createClassifier({ prepareCall: innerPrepare }, map.classifier) : void 0;
12224
13591
  let mapped;
12225
13592
  try {
12226
13593
  mapped = await resolveAutoRoute({
@@ -12229,7 +13596,7 @@ function installAutoSessionRoute(ctx, options) {
12229
13596
  toolHeavy: note?.toolHeavy ?? false,
12230
13597
  map,
12231
13598
  classifierEnabled: settings.autoClassifierEnabled,
12232
- classify,
13599
+ classify: classify2,
12233
13600
  isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
12234
13601
  signal,
12235
13602
  fallback: fallbackRoute(ctx, asAgent(agent))
@@ -12621,7 +13988,7 @@ var AuxiliaryModels = class {
12621
13988
  async resolveAutoRouteFor(session, override, text3, feature, toolHeavy) {
12622
13989
  const settings = this.enhancerSettings();
12623
13990
  const map = autoRouteMapOf(settings);
12624
- const classify = settings.autoClassifierEnabled ? createClassifier(this.ctx.llm, map.classifier) : void 0;
13991
+ const classify2 = settings.autoClassifierEnabled ? createClassifier(this.ctx.llm, map.classifier) : void 0;
12625
13992
  let mapped;
12626
13993
  try {
12627
13994
  mapped = await resolveAutoRoute({
@@ -12630,7 +13997,7 @@ var AuxiliaryModels = class {
12630
13997
  toolHeavy,
12631
13998
  map,
12632
13999
  classifierEnabled: settings.autoClassifierEnabled,
12633
- classify,
14000
+ classify: classify2,
12634
14001
  isAvailable: (provider, model) => this.modelExists(provider, model),
12635
14002
  fallback: this.fallbackFromSession(session, override)
12636
14003
  });
@@ -13561,7 +14928,7 @@ function mergeUsageCalls(stored, history) {
13561
14928
  }
13562
14929
 
13563
14930
  // src/host/usage/ledger.ts
13564
- import { randomUUID as randomUUID7 } from "node:crypto";
14931
+ import { randomUUID as randomUUID8 } from "node:crypto";
13565
14932
  import { chmod as chmod4, mkdir as mkdir5, readFile as readFile5, rename as rename4, unlink as unlink5, writeFile as writeFile4 } from "node:fs/promises";
13566
14933
  import { basename as basename14, join as join29 } from "node:path";
13567
14934
  import { z as z3 } from "zod";
@@ -13593,7 +14960,7 @@ async function removeIfPresent5(path) {
13593
14960
  }
13594
14961
  }
13595
14962
  async function writeAtomic4(path, value) {
13596
- const temporary = join29(join29(path, ".."), `.${basename14(path)}.${randomUUID7()}.tmp`);
14963
+ const temporary = join29(join29(path, ".."), `.${basename14(path)}.${randomUUID8()}.tmp`);
13597
14964
  try {
13598
14965
  await writeFile4(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
13599
14966
  await rename4(temporary, path);
@@ -13718,11 +15085,6 @@ function installUsageObserver(ctx, recorder) {
13718
15085
  // src/host/rpc.ts
13719
15086
  import { createTypertRemoteInfo } from "@deepseek-ai/dsh-typert-protocol/remote-info";
13720
15087
  import { z as z4 } from "zod";
13721
-
13722
- // src/host/update/types.ts
13723
- var APPLY_UPDATE_CODES = ["restart", "link", "manual", "none", "failed"];
13724
-
13725
- // src/host/rpc.ts
13726
15088
  var sessionIdSchema3 = z4.string().min(1).transform((value) => value);
13727
15089
  var recentExchangeSchema = z4.strictObject({
13728
15090
  turn: z4.number().int().nonnegative(),
@@ -13896,10 +15258,58 @@ var webChatTurnSchema = z4.strictObject({
13896
15258
  role: z4.enum(["user", "assistant"]),
13897
15259
  text: z4.string()
13898
15260
  });
15261
+ var webChatSearchResultSchema = z4.strictObject({
15262
+ url: z4.string(),
15263
+ title: z4.string().nullable().optional(),
15264
+ snippet: z4.string().nullable().optional(),
15265
+ published_at: z4.string().nullable().optional()
15266
+ });
15267
+ var webChatFragmentSchema = z4.discriminatedUnion("type", [
15268
+ z4.strictObject({ type: z4.literal("REQUEST"), content: z4.string() }),
15269
+ z4.strictObject({ type: z4.literal("RESPONSE"), content: z4.string() }),
15270
+ z4.strictObject({
15271
+ type: z4.literal("THINK"),
15272
+ content: z4.string(),
15273
+ elapsed_secs: z4.number().nonnegative().nullable().optional()
15274
+ }),
15275
+ z4.strictObject({ type: z4.literal("TEMPLATE_RESPONSE"), content: z4.string() }),
15276
+ z4.strictObject({
15277
+ type: z4.literal("TOOL_SEARCH"),
15278
+ queries: z4.array(z4.string()),
15279
+ results: z4.array(webChatSearchResultSchema),
15280
+ status: z4.string().optional(),
15281
+ stage_id: z4.number().int().nullable().optional()
15282
+ }),
15283
+ z4.strictObject({
15284
+ type: z4.literal("TOOL_OPEN"),
15285
+ status: z4.string(),
15286
+ url: z4.string().nullable(),
15287
+ title: z4.string().nullable().optional(),
15288
+ stage_id: z4.number().int().nullable().optional()
15289
+ }),
15290
+ z4.strictObject({
15291
+ type: z4.literal("READ_LINK"),
15292
+ results: z4.array(z4.strictObject({
15293
+ url: z4.string().nullable().optional(),
15294
+ title: z4.string().nullable().optional()
15295
+ }))
15296
+ })
15297
+ ]);
15298
+ var webChatRichMessageSchema = z4.strictObject({
15299
+ id: z4.number().int(),
15300
+ parent_id: z4.number().int().nullable(),
15301
+ role: z4.enum(["USER", "ASSISTANT"]),
15302
+ status: z4.string(),
15303
+ inserted_at: z4.string().optional(),
15304
+ fragments: z4.array(webChatFragmentSchema)
15305
+ });
13899
15306
  var webChatTranscriptSchema = z4.strictObject({
13900
15307
  title: z4.string(),
13901
15308
  partial: z4.boolean(),
13902
15309
  turns: z4.array(webChatTurnSchema).min(1),
15310
+ /** Share / history_messages tree for Session seed fidelity (optional for DOM capture). */
15311
+ messages: z4.array(webChatRichMessageSchema).optional(),
15312
+ currentMessageId: z4.number().int().nullable().optional(),
13903
15313
  source: z4.strictObject({
13904
15314
  kind: z4.enum(["rendered-capture", "official-export", "share-link", "account-history"]),
13905
15315
  url: z4.string().optional(),
@@ -14157,21 +15567,6 @@ var listExtraFolderEntriesResultCodec = codec(
14157
15567
  "dsh-agent-enhancer#ListExtraFolderEntriesResult",
14158
15568
  listExtraFolderEntriesResultSchema
14159
15569
  );
14160
- var updateCheckResultSchema = z4.strictObject({
14161
- current: z4.string(),
14162
- latest: z4.string().nullable(),
14163
- updateAvailable: z4.boolean(),
14164
- installKind: z4.enum(["npm", "link", "unknown"]),
14165
- canAutoApply: z4.boolean(),
14166
- command: z4.string()
14167
- });
14168
- var applyUpdateResultSchema = z4.strictObject({
14169
- ok: z4.boolean(),
14170
- message: z4.enum(APPLY_UPDATE_CODES),
14171
- command: z4.string().optional()
14172
- });
14173
- var updateCheckResultCodec = codec("dsh-agent-enhancer#UpdateCheckResult", updateCheckResultSchema);
14174
- var applyUpdateResultCodec = codec("dsh-agent-enhancer#ApplyUpdateResult", applyUpdateResultSchema);
14175
15570
  var usageTokenFields = {
14176
15571
  inputTokens: z4.number().int().nonnegative(),
14177
15572
  outputTokens: z4.number().int().nonnegative(),
@@ -14313,7 +15708,9 @@ var browserAgentTabConflictSchema = z4.strictObject({
14313
15708
  });
14314
15709
  var browserAgentNeedsHumanSchema = z4.strictObject({
14315
15710
  sessionId: z4.string().min(1),
14316
- detail: z4.string().min(1)
15711
+ detail: z4.string().min(1),
15712
+ /** `human` = login/captcha on the page; `ask` = any other browser-side request. */
15713
+ kind: z4.enum(["human", "ask"])
14317
15714
  });
14318
15715
  var browserAgentAuditEntrySchema = z4.strictObject({
14319
15716
  at: z4.number(),
@@ -14330,7 +15727,21 @@ var browserAgentTabEntrySchema = z4.strictObject({
14330
15727
  /** True when this is the driver's currently focused page. */
14331
15728
  active: z4.boolean(),
14332
15729
  /** True when any chat session is bound to this tab. */
14333
- bound: z4.boolean()
15730
+ bound: z4.boolean(),
15731
+ /** User marked the tab read-only: mutating tools fail fast there. */
15732
+ readOnly: z4.boolean()
15733
+ });
15734
+ var browserAgentAvailabilitySchema = z4.strictObject({
15735
+ chrome: z4.boolean(),
15736
+ edge: z4.boolean(),
15737
+ safari: z4.boolean()
15738
+ });
15739
+ var browserAgentDiagnosisSchema = z4.strictObject({
15740
+ code: z4.enum(["disabled", "idle", "ok", "webkit_missing", "browser_missing", "profile_locked", "launch_failed"]),
15741
+ /** English, model-facing: what to do next. */
15742
+ nextStep: z4.string(),
15743
+ detail: z4.string().optional(),
15744
+ browsers: browserAgentAvailabilitySchema
14334
15745
  });
14335
15746
  var browserAgentSnapshotSchema = z4.strictObject({
14336
15747
  enabled: z4.boolean(),
@@ -14349,6 +15760,8 @@ var browserAgentSnapshotSchema = z4.strictObject({
14349
15760
  lastError: z4.string().nullable()
14350
15761
  }),
14351
15762
  pending: browserAgentPendingSchema.nullable(),
15763
+ /** Why the browser is (not) usable and the concrete next step. */
15764
+ diagnosis: browserAgentDiagnosisSchema,
14352
15765
  tabConflict: browserAgentTabConflictSchema.nullable(),
14353
15766
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
14354
15767
  boundTabId: z4.number().int().nullable(),
@@ -14501,6 +15914,23 @@ var browserAgentSelectTabResultCodec = codec(
14501
15914
  "dsh-agent-enhancer#BrowserAgentSelectTabResult",
14502
15915
  browserAgentSelectTabResultSchema
14503
15916
  );
15917
+ var browserAgentSetTabReadOnlyRequestSchema = z4.strictObject({
15918
+ tabId: z4.number().int().positive(),
15919
+ readOnly: z4.boolean()
15920
+ });
15921
+ var browserAgentSetTabReadOnlyRequestCodec = codec(
15922
+ "dsh-agent-enhancer#BrowserAgentSetTabReadOnlyRequest",
15923
+ browserAgentSetTabReadOnlyRequestSchema
15924
+ );
15925
+ var browserAgentSetTabReadOnlyResultSchema = z4.strictObject({
15926
+ ok: z4.boolean(),
15927
+ error: z4.string().optional(),
15928
+ snapshot: browserAgentSnapshotSchema
15929
+ });
15930
+ var browserAgentSetTabReadOnlyResultCodec = codec(
15931
+ "dsh-agent-enhancer#BrowserAgentSetTabReadOnlyResult",
15932
+ browserAgentSetTabReadOnlyResultSchema
15933
+ );
14504
15934
  var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
14505
15935
  var instructionFileEntrySchema = z4.strictObject({
14506
15936
  id: z4.string().min(1),
@@ -15076,20 +16506,6 @@ var remoteInfo = createTypertRemoteInfo({
15076
16506
  cancellation: { parameter: "signal" },
15077
16507
  result: listExtraFolderEntriesResultCodec
15078
16508
  },
15079
- "agentEnhancer/checkUpdate": {
15080
- service: "agentEnhancer",
15081
- implementation: "checkUpdate",
15082
- invocation: { kind: "direct" },
15083
- parameters: [],
15084
- result: updateCheckResultCodec
15085
- },
15086
- "agentEnhancer/applyUpdate": {
15087
- service: "agentEnhancer",
15088
- implementation: "applyUpdate",
15089
- invocation: { kind: "direct" },
15090
- parameters: [],
15091
- result: applyUpdateResultCodec
15092
- },
15093
16509
  "agentEnhancer/usageSummary": {
15094
16510
  service: "agentEnhancer",
15095
16511
  implementation: "usageSummary",
@@ -15253,6 +16669,18 @@ var remoteInfo = createTypertRemoteInfo({
15253
16669
  }],
15254
16670
  result: browserAgentSelectTabResultCodec
15255
16671
  },
16672
+ "agentEnhancer/browserAgentSetTabReadOnly": {
16673
+ service: "agentEnhancer",
16674
+ implementation: "browserAgentSetTabReadOnly",
16675
+ invocation: { kind: "direct" },
16676
+ parameters: [{
16677
+ name: "request",
16678
+ source: "json",
16679
+ codec: browserAgentSetTabReadOnlyRequestCodec,
16680
+ strictCodec: browserAgentSetTabReadOnlyRequestCodec
16681
+ }],
16682
+ result: browserAgentSetTabReadOnlyResultCodec
16683
+ },
15256
16684
  "agentEnhancer/listInstructionsSkills": {
15257
16685
  service: "agentEnhancer",
15258
16686
  implementation: "listInstructionsSkills",
@@ -15886,319 +17314,6 @@ async function showOsNotificationNow(input) {
15886
17314
  return { shown: false, channel: "none" };
15887
17315
  }
15888
17316
 
15889
- // src/host/update/check.ts
15890
- import { homedir as homedir6 } from "node:os";
15891
- import { join as join31 } from "node:path";
15892
-
15893
- // src/host/update/cli.ts
15894
- import { spawn as nodeSpawn } from "node:child_process";
15895
- import { existsSync as existsSync20 } from "node:fs";
15896
- import { homedir as homedir5 } from "node:os";
15897
- import { posix as pathPosix2 } from "node:path";
15898
- function defaultSpawn(command, args, options) {
15899
- return nodeSpawn(command, [...args], options ?? {});
15900
- }
15901
- var PROBE_TIMEOUT_MS = 5e3;
15902
- var RUN_ADD_TIMEOUT_MS = 12e4;
15903
- var STRICT_SEMVER = /^\d+\.\d+\.\d+$/;
15904
- function isStrictVersion(value) {
15905
- return STRICT_SEMVER.test(value);
15906
- }
15907
- function dshFromElectronExecPath(execPath) {
15908
- const normalized = execPath.replace(/\\/g, "/");
15909
- const marker = "/Contents/MacOS/";
15910
- const idx = normalized.lastIndexOf(marker);
15911
- if (idx < 0) return null;
15912
- const contentsRoot = normalized.slice(0, idx + "/Contents".length);
15913
- return pathPosix2.join(contentsRoot, "Resources", "runtime", "cli", "bin", "dsh");
15914
- }
15915
- function dshExecutableCandidates(options = {}) {
15916
- const platform = options.platform ?? process.platform;
15917
- const env = options.env ?? process.env;
15918
- const home = options.home ?? env.HOME?.trim() ?? homedir5();
15919
- const execPath = options.execPath ?? process.execPath;
15920
- const out = [];
15921
- const push = (value) => {
15922
- const trimmed = typeof value === "string" ? value.trim() : "";
15923
- if (trimmed === "" || out.includes(trimmed)) return;
15924
- out.push(trimmed);
15925
- };
15926
- push(env.DSH_CLI);
15927
- if (platform === "darwin") {
15928
- push(dshFromElectronExecPath(execPath));
15929
- push("/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh");
15930
- push(pathPosix2.join(
15931
- home,
15932
- "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh"
15933
- ));
15934
- }
15935
- push("dsh");
15936
- return out;
15937
- }
15938
- function isCommandMissingDetail(detail) {
15939
- return /ENOENT|not found|spawn .*(ENOENT|not found)/i.test(detail);
15940
- }
15941
- function dshSpawnOptions() {
15942
- const base = { stdio: ["ignore", "pipe", "pipe"] };
15943
- return process.platform === "win32" ? { ...base, shell: true, windowsHide: true } : base;
15944
- }
15945
- function pluginAddArgs(latest) {
15946
- return ["plugin", "--profile", "desktop", "add", `${PACKAGE_NAME}@${latest}`];
15947
- }
15948
- function pluginAddCommand(latest) {
15949
- return `dsh plugin --profile desktop add ${PACKAGE_NAME}@${latest}`;
15950
- }
15951
- function resolveCanAutoApply(input) {
15952
- return input.installKind === "npm" && input.dshAvailable;
15953
- }
15954
- function waitForExit(child, timeoutMs) {
15955
- return new Promise((resolve17) => {
15956
- let settled = false;
15957
- const chunks = [];
15958
- const finish = (ok, detail) => {
15959
- if (settled) return;
15960
- settled = true;
15961
- clearTimeout(timer);
15962
- resolve17({ ok, detail });
15963
- };
15964
- const timer = setTimeout(() => {
15965
- child.kill();
15966
- finish(false, "timeout");
15967
- }, timeoutMs);
15968
- child.stdout?.on("data", (chunk) => chunks.push(chunk));
15969
- child.stderr?.on("data", (chunk) => chunks.push(chunk));
15970
- child.on("error", (err) => {
15971
- finish(false, err.message);
15972
- });
15973
- child.on("close", (code) => {
15974
- const detail = Buffer.concat(chunks).toString("utf8").trim();
15975
- finish(code === 0, detail);
15976
- });
15977
- });
15978
- }
15979
- async function runDshOnce(command, args, spawnFn, timeoutMs) {
15980
- let child;
15981
- try {
15982
- child = spawnFn(command, args, dshSpawnOptions());
15983
- } catch (err) {
15984
- return { ok: false, detail: err instanceof Error ? err.message : String(err) };
15985
- }
15986
- return waitForExit(child, timeoutMs);
15987
- }
15988
- async function runDsh(args, spawnFn, timeoutMs, options = {}) {
15989
- const candidates = options.candidates ?? dshExecutableCandidates();
15990
- const exists = options.exists ?? existsSync20;
15991
- let last = { ok: false, detail: "dsh not found" };
15992
- for (const command of candidates) {
15993
- if (command !== "dsh" && !exists(command)) continue;
15994
- const result = await runDshOnce(command, args, spawnFn, timeoutMs);
15995
- if (result.ok) return result;
15996
- last = result;
15997
- if (!isCommandMissingDetail(result.detail)) return result;
15998
- }
15999
- return last;
16000
- }
16001
- async function probeDsh(spawnFn = defaultSpawn, options = {}) {
16002
- const result = await runDsh(["--version"], spawnFn, PROBE_TIMEOUT_MS, options);
16003
- return result.ok;
16004
- }
16005
- async function runPluginAdd(latest, spawnFn = defaultSpawn, options = {}) {
16006
- if (!isStrictVersion(latest)) return { ok: false, detail: "invalid version" };
16007
- return runDsh(pluginAddArgs(latest), spawnFn, RUN_ADD_TIMEOUT_MS, options);
16008
- }
16009
-
16010
- // src/host/update/install-kind.ts
16011
- import { lstatSync as lstatSync5 } from "node:fs";
16012
- import { join as join30 } from "node:path";
16013
- function detectInstallKind(profileDir) {
16014
- const pkgPath = join30(profileDir, "node_modules", PACKAGE_NAME);
16015
- try {
16016
- const stat = lstatSync5(pkgPath);
16017
- if (stat.isSymbolicLink()) return "link";
16018
- if (stat.isDirectory()) return "npm";
16019
- return "unknown";
16020
- } catch {
16021
- return "unknown";
16022
- }
16023
- }
16024
-
16025
- // src/host/update/registry.ts
16026
- function defaultSources() {
16027
- return [
16028
- { kind: "npm-dist-tag", baseUrl: "https://registry.npmjs.org" },
16029
- // CDN package.json is reliable when the npm registry is unreachable.
16030
- {
16031
- kind: "package-json",
16032
- url: `https://cdn.jsdelivr.net/npm/${encodeURIComponent(PACKAGE_NAME)}/package.json`
16033
- },
16034
- // Mainland mirror last — some packages publish a misleading `latest` tag there.
16035
- { kind: "npm-dist-tag", baseUrl: "https://registry.npmmirror.com" }
16036
- ];
16037
- }
16038
- function isUsableReleaseVersion(value) {
16039
- return /^\d+\.\d+\.\d+$/.test(value);
16040
- }
16041
- function abortSignal(timeoutMs) {
16042
- try {
16043
- return AbortSignal.timeout(timeoutMs);
16044
- } catch {
16045
- return void 0;
16046
- }
16047
- }
16048
- function readDistTagLatest(body) {
16049
- if (body === null || typeof body !== "object") return null;
16050
- const distTags = body["dist-tags"];
16051
- if (distTags === null || typeof distTags !== "object") return null;
16052
- const latest = distTags.latest;
16053
- if (typeof latest !== "string" || !isUsableReleaseVersion(latest)) return null;
16054
- return latest;
16055
- }
16056
- function readPackageJsonVersion(body) {
16057
- if (body === null || typeof body !== "object") return null;
16058
- const version = body.version;
16059
- if (typeof version !== "string" || !isUsableReleaseVersion(version)) return null;
16060
- return version;
16061
- }
16062
- async function fetchJson(fetchImpl, url, currentVersion, timeoutMs) {
16063
- try {
16064
- const response = await fetchImpl(url, {
16065
- signal: abortSignal(timeoutMs),
16066
- headers: {
16067
- Accept: "application/json",
16068
- "User-Agent": `dsh-agent-enhancer/${currentVersion}`
16069
- }
16070
- });
16071
- if (!response.ok) {
16072
- console.error(`agent-enhancer update: registry ${url} returned ${response.status}`);
16073
- return null;
16074
- }
16075
- return await response.json();
16076
- } catch (error) {
16077
- console.error(`agent-enhancer update: registry fetch failed for ${url}`, error);
16078
- return null;
16079
- }
16080
- }
16081
- async function fetchLatestVersion(packageName, opts = {}) {
16082
- const fetchImpl = opts.fetch ?? globalThis.fetch;
16083
- const currentVersion = opts.currentVersion ?? PACKAGE_VERSION;
16084
- const timeoutMs = opts.timeoutMs ?? 12e3;
16085
- const sources = opts.sources ?? defaultSources();
16086
- for (const source of sources) {
16087
- switch (source.kind) {
16088
- case "npm-dist-tag": {
16089
- const url = `${source.baseUrl.replace(/\/$/, "")}/${encodeURIComponent(packageName)}`;
16090
- const body = await fetchJson(fetchImpl, url, currentVersion, timeoutMs);
16091
- const latest = readDistTagLatest(body);
16092
- if (latest !== null) return latest;
16093
- break;
16094
- }
16095
- case "package-json": {
16096
- const body = await fetchJson(fetchImpl, source.url, currentVersion, timeoutMs);
16097
- const version = readPackageJsonVersion(body);
16098
- if (version !== null) return version;
16099
- break;
16100
- }
16101
- default: {
16102
- const _exhaustive = source;
16103
- return _exhaustive;
16104
- }
16105
- }
16106
- }
16107
- return null;
16108
- }
16109
-
16110
- // src/host/update/semver.ts
16111
- function parseSemver(version) {
16112
- const trimmed = version.startsWith("v") ? version.slice(1) : version;
16113
- const parts = trimmed.split(".");
16114
- if (parts.length !== 3) {
16115
- return null;
16116
- }
16117
- const nums = [];
16118
- for (const part of parts) {
16119
- if (!/^\d+$/.test(part)) {
16120
- return null;
16121
- }
16122
- nums.push(Number(part));
16123
- }
16124
- return nums;
16125
- }
16126
- function isNewerVersion(latest, current) {
16127
- const latestParts = parseSemver(latest);
16128
- const currentParts = parseSemver(current);
16129
- if (latestParts === null || currentParts === null) {
16130
- return false;
16131
- }
16132
- const [lMajor, lMinor, lPatch] = latestParts;
16133
- const [cMajor, cMinor, cPatch] = currentParts;
16134
- if (lMajor !== cMajor) {
16135
- return lMajor > cMajor;
16136
- }
16137
- if (lMinor !== cMinor) {
16138
- return lMinor > cMinor;
16139
- }
16140
- return lPatch > cPatch;
16141
- }
16142
-
16143
- // src/host/update/check.ts
16144
- function resolveDesktopProfileDir(env = process.env, home = homedir6()) {
16145
- const dshHome2 = env.DSH_HOME ?? join31(home, ".dsh");
16146
- return join31(dshHome2, "profiles", "desktop");
16147
- }
16148
- async function checkPluginUpdate(deps) {
16149
- const latest = await deps.fetchLatest();
16150
- const installKind = deps.detectKind(deps.profileDir);
16151
- const dshAvailable = await deps.dshAvailable().catch(() => false);
16152
- const updateAvailable = latest !== null && isNewerVersion(latest, deps.currentVersion);
16153
- const command = pluginAddCommand(latest ?? "latest");
16154
- const canAutoApply = resolveCanAutoApply({ installKind, dshAvailable });
16155
- return {
16156
- current: deps.currentVersion,
16157
- latest,
16158
- updateAvailable,
16159
- installKind,
16160
- canAutoApply,
16161
- command
16162
- };
16163
- }
16164
- async function applyPluginUpdate(input) {
16165
- const { check, runAdd, messages } = input;
16166
- if (check.latest === null || !check.updateAvailable) {
16167
- return { ok: false, message: messages.noUpdate, command: check.command };
16168
- }
16169
- if (!check.canAutoApply) {
16170
- const message = check.installKind === "link" ? messages.linkBlocked : messages.manualOnly ?? messages.failed;
16171
- return { ok: false, message, command: check.command };
16172
- }
16173
- const result = await runAdd(check.latest);
16174
- if (!result.ok) {
16175
- return { ok: false, message: messages.failed, command: check.command };
16176
- }
16177
- return { ok: true, message: messages.success };
16178
- }
16179
- function defaultCheckDeps(overrides = {}) {
16180
- const profileDir = overrides.profileDir ?? resolveDesktopProfileDir();
16181
- return {
16182
- currentVersion: PACKAGE_VERSION,
16183
- fetchLatest: () => fetchLatestVersion(PACKAGE_NAME),
16184
- detectKind: (dir) => detectInstallKind(dir),
16185
- dshAvailable: () => probeDsh(),
16186
- profileDir,
16187
- ...overrides
16188
- };
16189
- }
16190
- async function checkPluginUpdateForHost(overrides) {
16191
- return checkPluginUpdate(defaultCheckDeps(overrides));
16192
- }
16193
- async function applyPluginUpdateForHost(messages, overrides) {
16194
- const check = await checkPluginUpdate(defaultCheckDeps(overrides));
16195
- return applyPluginUpdate({
16196
- check,
16197
- runAdd: (latest) => runPluginAdd(latest),
16198
- messages
16199
- });
16200
- }
16201
-
16202
17317
  // src/host/index.ts
16203
17318
  function hostBrowserPreference(value) {
16204
17319
  return coerceBrowserAgentBrowserForPlatform(
@@ -16241,6 +17356,10 @@ var Config = z5.object({
16241
17356
  /** High-risk; default off. */
16242
17357
  browserAgentEnabled: z5.boolean().default(false).volatile(),
16243
17358
  browserAgentBrowser: z5.string().default("auto").volatile(),
17359
+ /** Debug tools (network / console / emulate); default off, gated per tool. */
17360
+ browserAgentDebugTools: z5.boolean().default(false).volatile(),
17361
+ /** Close idle agent tabs after ~10 min; default on, never the bound/active tab. */
17362
+ browserAgentIdleClose: z5.boolean().default(true).volatile(),
16244
17363
  /** Default off; embeds official web chat + import to work. */
16245
17364
  webChatBridgeEnabled: z5.boolean().default(true).volatile(),
16246
17365
  instructionsSkillsEnabled: z5.boolean().default(true).volatile(),
@@ -16289,12 +17408,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
16289
17408
  };
16290
17409
  }
16291
17410
  }, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
16292
- join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
17411
+ join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
16293
17412
  ), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null, browserAgent = null, browserAgentSettings = () => ({
16294
17413
  enabled: false,
16295
17414
  browser: "auto"
16296
17415
  }), setBrowserAgentBrowser = () => void 0, browserAgentProfileDir = defaultBrowserAgentProfileDir(
16297
- join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
17416
+ join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
16298
17417
  )) {
16299
17418
  super(ctx, "agentEnhancer");
16300
17419
  this.models = models;
@@ -16332,10 +17451,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
16332
17451
  const waiting = this.browserAgent?.human.current() ?? null;
16333
17452
  const needsHuman = waiting !== null ? {
16334
17453
  sessionId: waiting.sessionId,
16335
- detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail
17454
+ detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail,
17455
+ kind: waiting.kind
16336
17456
  } : this.browserAgent?.sessions.anyNeedsHuman() ?? null;
16337
17457
  const overlayBound = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
16338
17458
  const connected = driverStatus?.ready === true;
17459
+ const diag = this.browserAgent?.diagnose();
16339
17460
  const listed = connected ? await this.browserAgent?.listTabs() : void 0;
16340
17461
  const tabs = listed?.tabs ?? [];
16341
17462
  const boundTabId = overlayBound ?? listed?.boundTabId ?? null;
@@ -16362,6 +17483,11 @@ var AgentEnhancerService = class extends TypertRemoteService {
16362
17483
  ...pending.url === void 0 ? {} : { url: pending.url },
16363
17484
  ...pending.origin === void 0 ? {} : { origin: pending.origin }
16364
17485
  },
17486
+ diagnosis: diag ?? {
17487
+ code: settings.enabled ? "idle" : "disabled",
17488
+ nextStep: settings.enabled ? "Nothing launched yet. Call browser_navigate (or Alt+click a chat link) to launch the dedicated browser." : "Browser agent is off. Enable it in \u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD.",
17489
+ browsers: { chrome: false, edge: false, safari: false }
17490
+ },
16365
17491
  tabConflict: conflict,
16366
17492
  needsHuman,
16367
17493
  boundTabId,
@@ -16544,7 +17670,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16544
17670
  }
16545
17671
  }
16546
17672
  webChatPluginDataRoot() {
16547
- return this.installLedgerRoot ?? join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
17673
+ return this.installLedgerRoot ?? join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
16548
17674
  }
16549
17675
  /** User-level web chat guest login snapshot (non-HttpOnly storage only). */
16550
17676
  async loadWebChatLoginSnapshot(_request, signal) {
@@ -16696,10 +17822,6 @@ var AgentEnhancerService = class extends TypertRemoteService {
16696
17822
  throw new RemoteError2("agent-enhancer/failed", detail || "Context compaction failed", { code });
16697
17823
  }
16698
17824
  }
16699
- /** Read-only version probe — same gate policy as `listCatalog` (settings-safe). */
16700
- async checkUpdate() {
16701
- return checkPluginUpdateForHost();
16702
- }
16703
17825
  async usageSummary(range) {
16704
17826
  this.assertOwner();
16705
17827
  return this.usage.summarize(range);
@@ -17068,28 +18190,30 @@ var AgentEnhancerService = class extends TypertRemoteService {
17068
18190
  snapshot: await this.browserSnapshotNow()
17069
18191
  };
17070
18192
  }
17071
- async applyUpdate() {
18193
+ async browserAgentSetTabReadOnly(request) {
17072
18194
  this.assertOwner();
17073
- return applyPluginUpdateForHost({
17074
- linkBlocked: "link",
17075
- success: "restart",
17076
- failed: "failed",
17077
- noUpdate: "none",
17078
- manualOnly: "manual"
18195
+ const result = this.browserAgent?.setTabReadOnly({
18196
+ tabId: request.tabId,
18197
+ readOnly: request.readOnly
17079
18198
  });
18199
+ return {
18200
+ ok: result?.ok === true,
18201
+ ...result?.error === void 0 ? {} : { error: result.error },
18202
+ snapshot: await this.browserSnapshotNow()
18203
+ };
17080
18204
  }
17081
18205
  };
17082
18206
  function resolveCheckpointRoot(dshHome2) {
17083
- const base = join32(dshHome2, "profiles", "desktop", "plugin-data");
17084
- const nextPkg = join32(base, PACKAGE_NAME);
17085
- const next = join32(nextPkg, "checkpoint");
17086
- const prev = join32(base, LEGACY_PACKAGE_NAME, "checkpoint");
17087
- if (!existsSync21(next) && existsSync21(prev)) {
18207
+ const base = join30(dshHome2, "profiles", "desktop", "plugin-data");
18208
+ const nextPkg = join30(base, PACKAGE_NAME);
18209
+ const next = join30(nextPkg, "checkpoint");
18210
+ const prev = join30(base, LEGACY_PACKAGE_NAME, "checkpoint");
18211
+ if (!existsSync20(next) && existsSync20(prev)) {
17088
18212
  mkdirSync12(nextPkg, { recursive: true });
17089
18213
  renameSync9(prev, next);
17090
- const prevPkg = join32(base, LEGACY_PACKAGE_NAME);
18214
+ const prevPkg = join30(base, LEGACY_PACKAGE_NAME);
17091
18215
  try {
17092
- if (existsSync21(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
18216
+ if (existsSync20(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
17093
18217
  } catch {
17094
18218
  }
17095
18219
  }
@@ -17161,6 +18285,8 @@ function readSettings(config) {
17161
18285
  runAlertsLevel: resolveRunAlertsLevel(config.runAlertsLevel.get()),
17162
18286
  browserAgentEnabled: config.browserAgentEnabled.get(),
17163
18287
  browserAgentBrowser: hostBrowserPreference(config.browserAgentBrowser.get()),
18288
+ browserAgentDebugTools: config.browserAgentDebugTools.get(),
18289
+ browserAgentIdleClose: config.browserAgentIdleClose.get(),
17164
18290
  webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
17165
18291
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
17166
18292
  mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
@@ -17192,9 +18318,9 @@ function apply(ctx, config) {
17192
18318
  const settings = () => readSettings(config);
17193
18319
  const models = new AuxiliaryModels(ctx, settings);
17194
18320
  installAutoSessionRoute(ctx, { settings });
17195
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join32(homedir7(), ".dsh"));
17196
- const pluginDataPackageRoot = join32(storageRoot, "..");
17197
- const usage = new UsageLedger(join32(storageRoot, "..", "usage"), (message) => {
18321
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join30(homedir5(), ".dsh"));
18322
+ const pluginDataPackageRoot = join30(storageRoot, "..");
18323
+ const usage = new UsageLedger(join30(storageRoot, "..", "usage"), (message) => {
17198
18324
  ctx.logger.warn(message);
17199
18325
  });
17200
18326
  const balancesFacade = (() => {
@@ -17224,12 +18350,12 @@ function apply(ctx, config) {
17224
18350
  })();
17225
18351
  installUsageObserver(ctx, usage);
17226
18352
  const store = new CheckpointStore(storageRoot);
17227
- const cutStore = new SessionCutStore(join32(storageRoot, "cuts"));
18353
+ const cutStore = new SessionCutStore(join30(storageRoot, "cuts"));
17228
18354
  const cutCache = /* @__PURE__ */ new Map();
17229
18355
  const sessionCleanup = new SessionCleanupRegistry();
17230
18356
  sessionCleanup.register(createCheckpointCleaner({ store, cutStore, storageRoot }));
17231
- sessionCleanup.register(createContextExcludeCleaner(join32(storageRoot, "..")));
17232
- const extraFoldersStore = createExtraFoldersStore(join32(storageRoot, "..", "extra-folders"));
18357
+ sessionCleanup.register(createContextExcludeCleaner(join30(storageRoot, "..")));
18358
+ const extraFoldersStore = createExtraFoldersStore(join30(storageRoot, "..", "extra-folders"));
17233
18359
  const softPauseGate = new SoftPauseGate();
17234
18360
  const mcpStore = createMcpConnectorsStore(mcpConnectorsRoot(pluginDataPackageRoot));
17235
18361
  const mcpRuntime = new McpConnectorRuntime(ctx, mcpStore);
@@ -17247,6 +18373,8 @@ function apply(ctx, config) {
17247
18373
  const browserAgent = installBrowserAgent(ctx, {
17248
18374
  enabled: () => browserAgentLive.enabled,
17249
18375
  browserPreference: () => browserAgentLive.browser,
18376
+ debugTools: () => settings().browserAgentDebugTools,
18377
+ idleClose: () => settings().browserAgentIdleClose,
17250
18378
  profileRoot: pluginDataPackageRoot,
17251
18379
  softPause: softPauseGate,
17252
18380
  softPauseEnabled: () => settings().softPauseEnabled,