dsh-agent-enhancer 0.3.16 → 0.3.18

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 (40) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/lib/client/browser-agent/approval-keys.d.ts +20 -0
  4. package/lib/client/browser-agent/approval-keys.d.ts.map +1 -0
  5. package/lib/client/browser-agent/banner-geometry.d.ts +13 -0
  6. package/lib/client/browser-agent/banner-geometry.d.ts.map +1 -0
  7. package/lib/client/browser-agent/overlay.d.ts.map +1 -1
  8. package/lib/client/browser-agent/tab.d.ts.map +1 -1
  9. package/lib/client/locales.d.ts +33 -5
  10. package/lib/client/locales.d.ts.map +1 -1
  11. package/lib/client/remote.d.ts +7 -1
  12. package/lib/client/remote.d.ts.map +1 -1
  13. package/lib/client.js +376 -23
  14. package/lib/client.js.map +1 -1
  15. package/lib/host/browser-agent/approval-thumbnail.d.ts +36 -0
  16. package/lib/host/browser-agent/approval-thumbnail.d.ts.map +1 -0
  17. package/lib/host/browser-agent/approval.d.ts +15 -0
  18. package/lib/host/browser-agent/approval.d.ts.map +1 -1
  19. package/lib/host/browser-agent/demo-recipes.d.ts +54 -0
  20. package/lib/host/browser-agent/demo-recipes.d.ts.map +1 -0
  21. package/lib/host/browser-agent/demo-replay.d.ts +85 -0
  22. package/lib/host/browser-agent/demo-replay.d.ts.map +1 -0
  23. package/lib/host/browser-agent/demo.d.ts +33 -5
  24. package/lib/host/browser-agent/demo.d.ts.map +1 -1
  25. package/lib/host/browser-agent/driver.d.ts +7 -0
  26. package/lib/host/browser-agent/driver.d.ts.map +1 -1
  27. package/lib/host/browser-agent/install.d.ts +22 -0
  28. package/lib/host/browser-agent/install.d.ts.map +1 -1
  29. package/lib/host/browser-agent/playwright-driver.d.ts +13 -4
  30. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  31. package/lib/host/browser-agent/prompt.d.ts.map +1 -1
  32. package/lib/host/browser-agent/tools.d.ts +3 -0
  33. package/lib/host/browser-agent/tools.d.ts.map +1 -1
  34. package/lib/host/index.d.ts +3 -1
  35. package/lib/host/index.d.ts.map +1 -1
  36. package/lib/host/rpc.d.ts +77 -0
  37. package/lib/host/rpc.d.ts.map +1 -1
  38. package/lib/index.js +883 -180
  39. package/lib/index.js.map +4 -4
  40. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/host/index.ts
2
- import { existsSync as existsSync20, mkdirSync as mkdirSync12, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
2
+ import { existsSync as existsSync20, mkdirSync as mkdirSync13, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
3
  import { homedir as homedir5 } from "node:os";
4
4
  import { join as join30 } from "node:path";
5
5
  import z5 from "@deepseek-ai/schemastery";
@@ -278,6 +278,10 @@ var BrowserApprovalGate = class {
278
278
  const first = this.pending.values().next().value;
279
279
  return first?.request ?? null;
280
280
  }
281
+ /** Crop for one pending approval, or null when it is gone or had none. */
282
+ thumbnailFor(id) {
283
+ return this.pending.get(id)?.request.thumbnail ?? null;
284
+ }
281
285
  /**
282
286
  * Returns true when the action may proceed without prompting.
283
287
  * Read-only tools should skip this gate entirely.
@@ -299,7 +303,8 @@ var BrowserApprovalGate = class {
299
303
  tool: input.tool,
300
304
  summary: input.summary,
301
305
  ...input.url === void 0 ? {} : { url: input.url },
302
- ...origin === void 0 ? {} : { origin }
306
+ ...origin === void 0 ? {} : { origin },
307
+ ...input.thumbnail === void 0 ? {} : { thumbnail: input.thumbnail }
303
308
  };
304
309
  const decision = await new Promise((resolve17, reject) => {
305
310
  const onAbort = () => {
@@ -1013,14 +1018,78 @@ async function capturePlaywrightSnapshot(page, options = {}) {
1013
1018
  return { body, refs };
1014
1019
  }
1015
1020
 
1021
+ // src/host/browser-agent/capture.ts
1022
+ var SECRET_PARAM = /^(access_?token|id_?token|auth|authorization|code|key|password|secret|session|sessionid|sig|signature|token)$/i;
1023
+ var URL_IN_TEXT = /https?:\/\/[^\s"'<>]+/g;
1024
+ function redactUrl(raw) {
1025
+ const withoutUserInfo = raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
1026
+ const withoutFragment = withoutUserInfo.replace(/#.*$/, "");
1027
+ const masked = withoutFragment.replace(
1028
+ /([?&])([^=&#]+)=([^&#]*)/g,
1029
+ (match, separator, key) => SECRET_PARAM.test(decodeURIComponent(key)) ? `${separator}${key}=***` : match
1030
+ );
1031
+ return masked.length > 300 ? `${masked.slice(0, 300)}\u2026` : masked;
1032
+ }
1033
+ function redactText(text3) {
1034
+ return text3.replace(URL_IN_TEXT, (match) => {
1035
+ const trailing = match.match(/[),.;]+$/)?.[0] ?? "";
1036
+ const core = trailing === "" ? match : match.slice(0, -trailing.length);
1037
+ return `${redactUrl(core)}${trailing}`;
1038
+ });
1039
+ }
1040
+ var CaptureBuffer = class {
1041
+ constructor(max = 300) {
1042
+ this.max = max;
1043
+ }
1044
+ max;
1045
+ entries = [];
1046
+ dropped = 0;
1047
+ get size() {
1048
+ return this.entries.length;
1049
+ }
1050
+ push(entry) {
1051
+ this.entries.push(entry);
1052
+ while (this.entries.length > this.max) {
1053
+ this.entries.shift();
1054
+ this.dropped += 1;
1055
+ }
1056
+ }
1057
+ /** Newest `limit` entries of the requested kind, optionally clearing them. */
1058
+ read(kind, options = {}) {
1059
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 40), 1), 200);
1060
+ const ofKind = this.entries.filter((entry) => kind === "all" || entry.kind === (kind === "network" ? "request" : "console"));
1061
+ const matched = options.tabId === void 0 ? ofKind : ofKind.filter((entry) => entry.tabId === options.tabId);
1062
+ const skipped = ofKind.length - matched.length;
1063
+ const selected = matched.slice(-limit);
1064
+ if (options.clear === true) {
1065
+ const keep = this.entries.filter((entry) => !selected.includes(entry));
1066
+ this.entries.length = 0;
1067
+ this.entries.push(...keep);
1068
+ }
1069
+ return { entries: selected, dropped: this.dropped, skipped };
1070
+ }
1071
+ clear() {
1072
+ this.entries.length = 0;
1073
+ this.dropped = 0;
1074
+ }
1075
+ };
1076
+
1016
1077
  // src/host/browser-agent/demo.ts
1078
+ function attachDemoTab(step, site) {
1079
+ if (site.tabId === void 0) return step;
1080
+ return {
1081
+ ...step,
1082
+ tabId: site.tabId,
1083
+ ...site.tabUrl === void 0 ? {} : { tabUrl: site.tabUrl }
1084
+ };
1085
+ }
1017
1086
  var SECRET_FIELD = /pass(word)?|\bpw\b|\bpwd\b|otp|one[-_]?time|code|pin|cvv|cvc|secret|token|card[-_]?number|iban/i;
1018
1087
  function isSensitiveFieldName(...parts) {
1019
1088
  return parts.some((part) => typeof part === "string" && SECRET_FIELD.test(part));
1020
1089
  }
1021
1090
  function pushDemoStep(steps, step, windowMs = 1500) {
1022
1091
  const last = steps[steps.length - 1];
1023
- if (last !== void 0 && step.at - last.at <= windowMs) {
1092
+ if (last !== void 0 && last.tabId === step.tabId && step.at - last.at <= windowMs) {
1024
1093
  if (last.kind === "fill" && step.kind === "fill" && last.selector === step.selector) {
1025
1094
  steps[steps.length - 1] = step;
1026
1095
  return;
@@ -1044,6 +1113,7 @@ function mergeDemoSteps(pageSteps, navSteps) {
1044
1113
  return out;
1045
1114
  }
1046
1115
  function sameStep(a, b) {
1116
+ if (a.tabId !== b.tabId) return false;
1047
1117
  if (a.kind !== b.kind) return false;
1048
1118
  if (a.kind === "navigate" && b.kind === "navigate") return a.url === b.url;
1049
1119
  if (a.kind === "click" && b.kind === "click") return a.selector === b.selector;
@@ -1053,39 +1123,66 @@ function sameStep(a, b) {
1053
1123
  }
1054
1124
  function sanitizeDemoSteps(steps) {
1055
1125
  return steps.map((step) => {
1126
+ if (step.kind === "navigate") {
1127
+ const url = redactUrl(step.url);
1128
+ return url === step.url ? step : { ...step, url };
1129
+ }
1056
1130
  if (step.kind !== "fill") return step;
1057
1131
  if (step.masked || !isSensitiveFieldName(step.field, step.name, step.selector)) return step;
1058
1132
  return { ...step, value: "***", masked: true };
1059
1133
  });
1060
1134
  }
1135
+ function describeDemoStep(step) {
1136
+ switch (step.kind) {
1137
+ case "navigate":
1138
+ return `navigate -> ${step.url}`;
1139
+ case "click":
1140
+ return `click ${step.role} ${JSON.stringify(step.name)}${step.href === void 0 ? "" : ` (href ${step.href})`} [selector ${step.selector}]`;
1141
+ case "fill": {
1142
+ const value = step.masked ? "***" : JSON.stringify(step.value);
1143
+ const checked = step.checked === void 0 ? "" : ` checked=${String(step.checked)}`;
1144
+ return `fill ${step.role} ${JSON.stringify(step.name)} = ${value}${checked} [selector ${step.selector}]`;
1145
+ }
1146
+ case "press":
1147
+ return `press ${step.key} [selector ${step.selector}]`;
1148
+ default: {
1149
+ const exhaustive = step;
1150
+ return JSON.stringify(exhaustive);
1151
+ }
1152
+ }
1153
+ }
1061
1154
  function summarizeDemoSteps(steps, max = 40) {
1062
1155
  const shown = steps.slice(0, Math.max(1, max));
1156
+ const tabs = collectTabs(shown);
1157
+ const multiTab = tabs.length > 1;
1063
1158
  const lines = shown.map((step, index) => {
1064
1159
  const n = index + 1;
1065
- switch (step.kind) {
1066
- case "navigate":
1067
- return `${n}. navigate -> ${step.url}`;
1068
- case "click":
1069
- return `${n}. click ${step.role} ${JSON.stringify(step.name)}${step.href === void 0 ? "" : ` (href ${step.href})`} [selector ${step.selector}]`;
1070
- case "fill": {
1071
- const value = step.masked ? "***" : JSON.stringify(step.value);
1072
- const checked = step.checked === void 0 ? "" : ` checked=${String(step.checked)}`;
1073
- return `${n}. fill ${step.role} ${JSON.stringify(step.name)} = ${value}${checked} [selector ${step.selector}]`;
1074
- }
1075
- case "press":
1076
- return `${n}. press ${step.key} [selector ${step.selector}]`;
1077
- default: {
1078
- const exhaustive = step;
1079
- return `${n}. ${JSON.stringify(exhaustive)}`;
1080
- }
1081
- }
1160
+ const tag = multiTab && step.tabId !== void 0 ? `[tab ${step.tabId}] ` : "";
1161
+ return `${n}. ${tag}${describeDemoStep(step)}`;
1082
1162
  });
1083
1163
  return {
1084
1164
  lines,
1085
1165
  shown: shown.length,
1086
- masked: shown.filter((step) => step.kind === "fill" && step.masked).length
1166
+ masked: shown.filter((step) => step.kind === "fill" && step.masked).length,
1167
+ tabs,
1168
+ multiTab
1087
1169
  };
1088
1170
  }
1171
+ function collectTabs(steps) {
1172
+ const seen = /* @__PURE__ */ new Map();
1173
+ for (const step of steps) {
1174
+ if (step.tabId === void 0 || seen.has(step.tabId)) continue;
1175
+ seen.set(step.tabId, { tabId: step.tabId, ...step.tabUrl === void 0 ? {} : { url: step.tabUrl } });
1176
+ }
1177
+ return [...seen.values()];
1178
+ }
1179
+ function demoTabLegend(summary) {
1180
+ if (!summary.multiTab) return [];
1181
+ return [
1182
+ `tabs: ${summary.tabs.length} (each step is tagged with the tab it happened in)`,
1183
+ ...summary.tabs.map((tab) => `tab ${tab.tabId}: ${tab.url ?? "(url unknown)"}`)
1184
+ ];
1185
+ }
1089
1186
  var DEMO_SYMBOL = "Symbol.for('dsh-demo')";
1090
1187
  var DEMO_RECORDER_SOURCE = `"use strict";
1091
1188
  var KEY = ${DEMO_SYMBOL};
@@ -1149,6 +1246,33 @@ function on(target, type, handler, capture) {
1149
1246
  target.addEventListener(type, handler, capture === true);
1150
1247
  OFF.push(function () { target.removeEventListener(type, handler, capture === true); });
1151
1248
  }
1249
+ // Single-page apps change the URL without loading a document, so the driver's
1250
+ // framenavigated never fires. Patch the history API and listen for the events
1251
+ // the browser dispatches for back/forward and hash routes.
1252
+ var lastUrl = String(location.href || "");
1253
+ function routeStep() {
1254
+ var url = String(location.href || "");
1255
+ if (url === lastUrl) return;
1256
+ lastUrl = url;
1257
+ if (!/^https?:\\/\\//i.test(url)) return;
1258
+ push({ kind: "navigate", url: url });
1259
+ }
1260
+ function wrapHistory(name) {
1261
+ var original = history[name];
1262
+ if (typeof original !== "function") return;
1263
+ try {
1264
+ history[name] = function () {
1265
+ var result = original.apply(this, arguments);
1266
+ try { setTimeout(routeStep, 0); } catch (e) { }
1267
+ return result;
1268
+ };
1269
+ OFF.push(function () { try { history[name] = original; } catch (e) { } });
1270
+ } catch (e) { }
1271
+ }
1272
+ wrapHistory("pushState");
1273
+ wrapHistory("replaceState");
1274
+ on(window, "popstate", routeStep);
1275
+ on(window, "hashchange", routeStep);
1152
1276
  on(document, "click", function (event) {
1153
1277
  var el = event.target && event.target.closest ? event.target.closest("a,button,input,select,textarea,[role],[contenteditable='true']") : null;
1154
1278
  if (!el) return;
@@ -1197,10 +1321,51 @@ on(document, "keydown", function (event) {
1197
1321
  if (!el || !el.tagName) return;
1198
1322
  push({ kind: "press", key: "Enter", selector: selectorOf(el) });
1199
1323
  }, true);
1324
+ // Visible "recording" marker. Styles are set through CSSOM (not a <style> tag)
1325
+ // so a strict style-src CSP cannot hide it; the host is pointer-events:none and
1326
+ // aria-hidden, so it can never eat a click or show up in a snapshot.
1327
+ function mountBadge() {
1328
+ try {
1329
+ var stale = document.querySelector("[data-dsh-demo-badge]");
1330
+ if (stale && stale.parentNode) stale.parentNode.removeChild(stale);
1331
+ var host = document.createElement("div");
1332
+ host.setAttribute("data-dsh-demo-badge", "");
1333
+ host.setAttribute("aria-hidden", "true");
1334
+ host.style.cssText = "position:fixed;right:18px;bottom:18px;z-index:2147483647;pointer-events:none;";
1335
+ var root = host.attachShadow ? host.attachShadow({ mode: "open" }) : host;
1336
+ var zh = /^zh/i.test(navigator.language || "");
1337
+ var bar = document.createElement("div");
1338
+ bar.style.cssText = "display:flex;align-items:center;gap:8px;padding:8px 12px;border-radius:12px;"
1339
+ + "background:rgba(17,24,39,.92);color:#fff;box-shadow:0 6px 20px rgba(0,0,0,.28);"
1340
+ + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;";
1341
+ var dot = document.createElement("span");
1342
+ dot.style.cssText = "width:9px;height:9px;border-radius:50%;background:#ef4444;flex:0 0 auto;"
1343
+ + "box-shadow:0 0 0 3px rgba(239,68,68,.22);";
1344
+ var text = document.createElement("span");
1345
+ text.style.cssText = "display:flex;flex-direction:column;gap:1px;font-size:12px;line-height:1.35;";
1346
+ var title = document.createElement("span");
1347
+ title.textContent = zh ? "\u6F14\u793A\u5F55\u5236\u4E2D" : "Recording";
1348
+ var hint = document.createElement("span");
1349
+ hint.textContent = zh ? "\u5B8C\u6210\u540E\u56DE\u5230 Desktop \u7ED3\u675F\u5F55\u5236" : "Return to Desktop to stop";
1350
+ hint.style.cssText = "font-size:11px;opacity:.72;";
1351
+ text.appendChild(title);
1352
+ text.appendChild(hint);
1353
+ bar.appendChild(dot);
1354
+ bar.appendChild(text);
1355
+ root.appendChild(bar);
1356
+ (document.body || document.documentElement).appendChild(host);
1357
+ return host;
1358
+ } catch (e) {
1359
+ return null;
1360
+ }
1361
+ }
1362
+ var badge = mountBadge();
1200
1363
  var recorder = {
1201
1364
  stop: function () {
1202
1365
  for (var i = 0; i < OFF.length; i++) { try { OFF[i](); } catch (e) { } }
1203
1366
  OFF.length = 0;
1367
+ try { if (badge && badge.parentNode) badge.parentNode.removeChild(badge); } catch (e) { }
1368
+ badge = null;
1204
1369
  delete window[KEY];
1205
1370
  },
1206
1371
  };
@@ -1213,62 +1378,6 @@ var DEMO_STOP_SOURCE = `(() => {
1213
1378
  return true;
1214
1379
  })()`;
1215
1380
 
1216
- // src/host/browser-agent/capture.ts
1217
- var SECRET_PARAM = /^(access_?token|id_?token|auth|authorization|code|key|password|secret|session|sessionid|sig|signature|token)$/i;
1218
- var URL_IN_TEXT = /https?:\/\/[^\s"'<>]+/g;
1219
- function redactUrl(raw) {
1220
- const withoutUserInfo = raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
1221
- const withoutFragment = withoutUserInfo.replace(/#.*$/, "");
1222
- const masked = withoutFragment.replace(
1223
- /([?&])([^=&#]+)=([^&#]*)/g,
1224
- (match, separator, key) => SECRET_PARAM.test(decodeURIComponent(key)) ? `${separator}${key}=***` : match
1225
- );
1226
- return masked.length > 300 ? `${masked.slice(0, 300)}\u2026` : masked;
1227
- }
1228
- function redactText(text3) {
1229
- return text3.replace(URL_IN_TEXT, (match) => {
1230
- const trailing = match.match(/[),.;]+$/)?.[0] ?? "";
1231
- const core = trailing === "" ? match : match.slice(0, -trailing.length);
1232
- return `${redactUrl(core)}${trailing}`;
1233
- });
1234
- }
1235
- var CaptureBuffer = class {
1236
- constructor(max = 300) {
1237
- this.max = max;
1238
- }
1239
- max;
1240
- entries = [];
1241
- dropped = 0;
1242
- get size() {
1243
- return this.entries.length;
1244
- }
1245
- push(entry) {
1246
- this.entries.push(entry);
1247
- while (this.entries.length > this.max) {
1248
- this.entries.shift();
1249
- this.dropped += 1;
1250
- }
1251
- }
1252
- /** Newest `limit` entries of the requested kind, optionally clearing them. */
1253
- read(kind, options = {}) {
1254
- const limit = Math.min(Math.max(Math.trunc(options.limit ?? 40), 1), 200);
1255
- const ofKind = this.entries.filter((entry) => kind === "all" || entry.kind === (kind === "network" ? "request" : "console"));
1256
- const matched = options.tabId === void 0 ? ofKind : ofKind.filter((entry) => entry.tabId === options.tabId);
1257
- const skipped = ofKind.length - matched.length;
1258
- const selected = matched.slice(-limit);
1259
- if (options.clear === true) {
1260
- const keep = this.entries.filter((entry) => !selected.includes(entry));
1261
- this.entries.length = 0;
1262
- this.entries.push(...keep);
1263
- }
1264
- return { entries: selected, dropped: this.dropped, skipped };
1265
- }
1266
- clear() {
1267
- this.entries.length = 0;
1268
- this.dropped = 0;
1269
- }
1270
- };
1271
-
1272
1381
  // src/host/browser-agent/auto-nav.ts
1273
1382
  function pathKey(raw) {
1274
1383
  try {
@@ -1383,6 +1492,28 @@ var TabRegistry = class {
1383
1492
  }
1384
1493
  };
1385
1494
 
1495
+ // src/host/browser-agent/approval-thumbnail.ts
1496
+ var THUMBNAIL_PADDING = 12;
1497
+ var THUMBNAIL_MAX_WIDTH = 520;
1498
+ var THUMBNAIL_MAX_HEIGHT = 260;
1499
+ var MAX_THUMBNAIL_BASE64 = 4e5;
1500
+ function clampThumbnailClip(box, viewport) {
1501
+ if (!Number.isFinite(box.x) || !Number.isFinite(box.y)) return null;
1502
+ if (!Number.isFinite(box.width) || !Number.isFinite(box.height)) return null;
1503
+ if (box.width <= 0 || box.height <= 0) return null;
1504
+ const left = Math.max(0, box.x - THUMBNAIL_PADDING);
1505
+ const top = Math.max(0, box.y - THUMBNAIL_PADDING);
1506
+ const right = Math.min(viewport.width, box.x + box.width + THUMBNAIL_PADDING);
1507
+ const bottom = Math.min(viewport.height, box.y + box.height + THUMBNAIL_PADDING);
1508
+ if (right - left < 8 || bottom - top < 8) return null;
1509
+ const width = Math.min(right - left, THUMBNAIL_MAX_WIDTH);
1510
+ const height = Math.min(bottom - top, THUMBNAIL_MAX_HEIGHT);
1511
+ return { x: Math.round(left), y: Math.round(top), width: Math.round(width), height: Math.round(height) };
1512
+ }
1513
+ function keepThumbnail(base64) {
1514
+ return base64.length > 0 && base64.length <= MAX_THUMBNAIL_BASE64;
1515
+ }
1516
+
1386
1517
  // src/host/browser-agent/playwright-driver.ts
1387
1518
  var playwrightModule = null;
1388
1519
  async function loadPlaywright() {
@@ -1828,6 +1959,17 @@ var PlaywrightDriver = class {
1828
1959
  tabId: this.tabIdFor(page)
1829
1960
  };
1830
1961
  }
1962
+ async press(key) {
1963
+ const page = await this.requirePage();
1964
+ await page.keyboard.press(key);
1965
+ await sleep(120);
1966
+ return {
1967
+ url: page.url(),
1968
+ title: await page.title().catch(() => ""),
1969
+ changed: false,
1970
+ tabId: this.tabIdFor(page)
1971
+ };
1972
+ }
1831
1973
  async scroll(dy) {
1832
1974
  const page = await this.requirePage();
1833
1975
  await page.mouse.wheel(0, dy);
@@ -1869,6 +2011,28 @@ var PlaywrightDriver = class {
1869
2011
  tabId: this.tabIdFor(page)
1870
2012
  };
1871
2013
  }
2014
+ /** Small crop around the control a pending approval is about. */
2015
+ async thumbnail(ref) {
2016
+ const page = await this.requirePage();
2017
+ const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
2018
+ const count = await locator.count().catch(() => 0);
2019
+ if (count === 0) return null;
2020
+ const box = await locator.boundingBox().catch(() => null);
2021
+ if (box === null) return null;
2022
+ const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
2023
+ const clip2 = clampThumbnailClip(box, viewport);
2024
+ if (clip2 === null) return null;
2025
+ const buffer = await page.screenshot({
2026
+ clip: clip2,
2027
+ type: "jpeg",
2028
+ quality: 60,
2029
+ scale: "css",
2030
+ timeout: 5e3
2031
+ }).catch(() => null);
2032
+ if (buffer === null) return null;
2033
+ const base64 = buffer.toString("base64");
2034
+ return keepThumbnail(base64) ? { mime: "image/jpeg", base64 } : null;
2035
+ }
1872
2036
  async listTabs() {
1873
2037
  const pages = this.context?.pages() ?? [];
1874
2038
  if (pages.length === 0) {
@@ -2006,7 +2170,7 @@ var PlaywrightDriver = class {
2006
2170
  tabId: this.tabIdFor(page)
2007
2171
  };
2008
2172
  }
2009
- /** Record a user demonstration in the bound tab until stopDemonstration(). */
2173
+ /** Record a user demonstration across every tab of the dedicated browser. */
2010
2174
  async startDemonstration() {
2011
2175
  const page = await this.requirePage();
2012
2176
  if (this.demoPage !== null) await this.stopDemonstration().catch(() => void 0);
@@ -2016,40 +2180,65 @@ var PlaywrightDriver = class {
2016
2180
  const context = page.context();
2017
2181
  if (!this.demoBindingReady) {
2018
2182
  try {
2019
- await context.exposeBinding("__dshDemoPush", (_source, step) => {
2183
+ await context.exposeBinding("__dshDemoPush", (source, step) => {
2020
2184
  if (this.demoPage === null) return;
2021
- pushDemoStep(this.demoPageSteps, step);
2185
+ const from = source.page;
2186
+ pushDemoStep(
2187
+ this.demoPageSteps,
2188
+ from === void 0 || from.isClosed() ? step : attachDemoTab(step, this.demoSite(from))
2189
+ );
2022
2190
  });
2023
2191
  this.demoBindingReady = true;
2024
2192
  } catch {
2025
2193
  this.demoBindingReady = true;
2026
2194
  }
2027
2195
  }
2028
- this.watchDemoNavigation(page);
2029
- await page.evaluate(`(() => { ${DEMO_RECORDER_SOURCE} })()`).catch(() => void 0);
2196
+ for (const open of context.pages()) this.armDemoPage(open);
2030
2197
  if (this.demoPageHandler === null) {
2031
2198
  this.demoPageHandler = (opened) => {
2032
2199
  if (this.demoPage === null) return;
2033
- this.watchDemoNavigation(opened);
2034
- void opened.evaluate(`(() => { ${DEMO_RECORDER_SOURCE} })()`).catch(() => void 0);
2200
+ this.armDemoPage(opened);
2035
2201
  };
2036
2202
  context.on("page", this.demoPageHandler);
2037
2203
  }
2038
2204
  }
2205
+ /** Tab id plus the redacted URL of a page, for tagging a step. */
2206
+ demoSite(page) {
2207
+ let raw = "";
2208
+ try {
2209
+ raw = page.url();
2210
+ } catch {
2211
+ raw = "";
2212
+ }
2213
+ return {
2214
+ tabId: this.tabIdFor(page),
2215
+ .../^https?:\/\//i.test(raw) ? { tabUrl: redactUrl(raw) } : {}
2216
+ };
2217
+ }
2039
2218
  /**
2040
- * Record top-level http(s) navigations of the pages the demo touches and
2041
- * re-arm the recorder on the new document (the old one dies with the page).
2219
+ * Wire one tab for recording: a navigation watcher (attached once per page)
2220
+ * plus the page-side recorder, which is re-injected every call so a second
2221
+ * demonstration in the same browser does not silently record nothing.
2042
2222
  */
2043
- watchDemoNavigation(page) {
2044
- if (this.demoTrackedPages.has(page)) return;
2045
- this.demoTrackedPages.add(page);
2046
- page.on("framenavigated", (frame) => {
2047
- if (this.demoPage === null || frame !== page.mainFrame()) return;
2048
- const url = frame.url();
2049
- if (!/^https?:\/\//i.test(url)) return;
2050
- this.demoNavSteps.push({ kind: "navigate", at: Date.now(), url: redactUrl(url) });
2051
- void frame.page().evaluate(`(() => { ${DEMO_RECORDER_SOURCE} })()`).catch(() => void 0);
2052
- });
2223
+ armDemoPage(page) {
2224
+ if (!this.demoTrackedPages.has(page)) {
2225
+ this.demoTrackedPages.add(page);
2226
+ page.on("framenavigated", (frame) => {
2227
+ if (this.demoPage === null || frame !== page.mainFrame()) return;
2228
+ const url = frame.url();
2229
+ if (!/^https?:\/\//i.test(url)) return;
2230
+ const safe = redactUrl(url);
2231
+ this.demoNavSteps.push({
2232
+ kind: "navigate",
2233
+ at: Date.now(),
2234
+ url: safe,
2235
+ tabId: this.tabIdFor(page),
2236
+ tabUrl: safe
2237
+ });
2238
+ void frame.page().evaluate(demoRecorderScript()).catch(() => void 0);
2239
+ });
2240
+ }
2241
+ void page.evaluate(demoRecorderScript()).catch(() => void 0);
2053
2242
  }
2054
2243
  /** Stop recording and return the flow, secrets masked, repeats dropped. */
2055
2244
  demonstrationActive() {
@@ -2128,6 +2317,9 @@ function sleep(ms) {
2128
2317
  setTimeout(resolve17, ms);
2129
2318
  });
2130
2319
  }
2320
+ function demoRecorderScript() {
2321
+ return `(() => { ${DEMO_RECORDER_SOURCE} })()`;
2322
+ }
2131
2323
  function clipText(text3, max) {
2132
2324
  const flat = text3.replace(/\s+/g, " ").trim();
2133
2325
  return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
@@ -2195,6 +2387,7 @@ var GUIDANCE = [
2195
2387
  "Mutation tools may pause for an in-app Allow card \u2014 wait for allow/deny.",
2196
2388
  "When the user says they will show you how something works (\u6F14\u793A / \u793A\u8303 / \u6211\u64CD\u4F5C\u4F60\u770B), or you cannot work out a flow after a couple of attempts, call browser_demonstrate with one short instruction instead of guessing. It blocks until the user presses Continue and returns numbered steps.",
2197
2389
  "browser_demonstrate returns click/fill/Enter/navigation steps with role + name. Replay them with browser_snapshot, then act by role and name; the selectors in the steps are for humans, and refs change between runs. If the tool reports that demonstration recording is off, ask the user to enable \u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent \u2192 \u6F14\u793A\u5F55\u5236.",
2390
+ 'Pass replay: true when the user wants you to just do it ("\u7136\u540E\u4F60\u6765"), not to read a list. Replay runs the recorded steps unattended and stops at the first step it cannot reproduce (a masked secret, a <select>, a control that moved). When it stops, do the remaining steps yourself and never say the flow completed.',
2198
2391
  "Login / captcha / 2FA: NEVER type passwords. When needs_human appears, call browser_ask_user and STOP until the user finishes in the dedicated window. A bare \u201CLog in\u201D chip on a normal page is not a wall.",
2199
2392
  "Do not invent page content or refs. Prefer finishing the user task over exploring more pages."
2200
2393
  ].join("\n");
@@ -2496,6 +2689,187 @@ function classify(input) {
2496
2689
  };
2497
2690
  }
2498
2691
 
2692
+ // src/host/browser-agent/demo-replay.ts
2693
+ function normalizeControlName(raw) {
2694
+ return raw.replace(/[\u200b-\u200d\ufeff]/gu, "").replace(/\s+/gu, " ").trim().toLowerCase();
2695
+ }
2696
+ function matchDemoControl(nodes, role, name2) {
2697
+ const wanted = normalizeControlName(name2);
2698
+ if (wanted === "") return void 0;
2699
+ const sameRole = nodes.filter((node) => node.role === role);
2700
+ const exact = sameRole.find((node) => normalizeControlName(node.name) === wanted);
2701
+ if (exact !== void 0) return exact;
2702
+ const exactAnyRole = nodes.find((node) => normalizeControlName(node.name) === wanted);
2703
+ if (exactAnyRole !== void 0) return exactAnyRole;
2704
+ const partial = sameRole.filter((node) => {
2705
+ const candidate = normalizeControlName(node.name);
2706
+ return candidate.includes(wanted) || wanted.includes(candidate);
2707
+ });
2708
+ return partial.length === 1 ? partial[0] : void 0;
2709
+ }
2710
+ function replayObstacle(step) {
2711
+ if (step.kind !== "fill") return null;
2712
+ if (step.masked) return `secret field ${JSON.stringify(step.name)} was masked; type it yourself`;
2713
+ if (step.role === "combobox") return `select ${JSON.stringify(step.name)} cannot be replayed by name`;
2714
+ if (step.role === "checkbox" || step.role === "radio") {
2715
+ return `${step.role} ${JSON.stringify(step.name)} cannot be replayed by name (click it, then continue)`;
2716
+ }
2717
+ return null;
2718
+ }
2719
+ async function performStep(driver, step) {
2720
+ switch (step.kind) {
2721
+ case "navigate": {
2722
+ const current = (await driver.snapshot()).url;
2723
+ if (current === step.url) return { ok: true, url: current };
2724
+ const result = await driver.navigate(step.url);
2725
+ return { ok: true, url: result.url };
2726
+ }
2727
+ case "click": {
2728
+ const snapshot = await driver.snapshot();
2729
+ const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2730
+ if (node === void 0) {
2731
+ return {
2732
+ ok: false,
2733
+ reason: `no control matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2734
+ };
2735
+ }
2736
+ const result = await driver.click(node.ref);
2737
+ return { ok: true, url: result.url };
2738
+ }
2739
+ case "fill": {
2740
+ const snapshot = await driver.snapshot();
2741
+ const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2742
+ if (node === void 0) {
2743
+ return {
2744
+ ok: false,
2745
+ reason: `no field matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2746
+ };
2747
+ }
2748
+ const result = await driver.type(node.ref, step.value);
2749
+ return { ok: true, url: result.url };
2750
+ }
2751
+ case "press": {
2752
+ const result = await driver.press(step.key);
2753
+ return { ok: true, url: result.url };
2754
+ }
2755
+ default: {
2756
+ const exhaustive = step;
2757
+ return { ok: false, reason: `unsupported step ${JSON.stringify(exhaustive)}` };
2758
+ }
2759
+ }
2760
+ }
2761
+ function samePage(a, b) {
2762
+ try {
2763
+ const left = new URL(a);
2764
+ const right = new URL(b);
2765
+ const path = (value) => value.replace(/\/+$/u, "");
2766
+ return left.origin === right.origin && path(left.pathname) === path(right.pathname);
2767
+ } catch {
2768
+ return a === b;
2769
+ }
2770
+ }
2771
+ async function replayDemoSteps(driver, steps) {
2772
+ const lines = [];
2773
+ let currentTab;
2774
+ let url;
2775
+ const recordedTabs = [];
2776
+ const tabUrls = /* @__PURE__ */ new Map();
2777
+ for (const step of steps) {
2778
+ if (step.tabId === void 0) continue;
2779
+ if (!recordedTabs.includes(step.tabId)) recordedTabs.push(step.tabId);
2780
+ if (!tabUrls.has(step.tabId) && step.tabUrl !== void 0) tabUrls.set(step.tabId, step.tabUrl);
2781
+ }
2782
+ const multiTab = recordedTabs.length > 1;
2783
+ const liveTabs = multiTab && typeof driver.listTabs === "function" ? await driver.listTabs().then((result) => result.tabs).catch(() => []) : [];
2784
+ const first = steps[0];
2785
+ if (first !== void 0 && first.kind !== "navigate" && first.tabUrl !== void 0 && /^https?:\/\//i.test(first.tabUrl)) {
2786
+ const current = await driver.snapshot().then((result) => result.url).catch(() => void 0);
2787
+ if (current === void 0 || !samePage(current, first.tabUrl)) {
2788
+ await driver.navigate(first.tabUrl).catch(() => void 0);
2789
+ }
2790
+ }
2791
+ const resolveTab = (recordedId) => {
2792
+ const wanted = tabUrls.get(recordedId);
2793
+ if (wanted === void 0) return void 0;
2794
+ return liveTabs.find((tab) => samePage(tab.url, wanted))?.tabId;
2795
+ };
2796
+ for (let index = 0; index < steps.length; index += 1) {
2797
+ const step = steps[index];
2798
+ if (multiTab && step.tabId !== void 0 && step.tabId !== currentTab) {
2799
+ try {
2800
+ const followed = await driver.followTab(resolveTab(step.tabId) ?? step.tabId);
2801
+ currentTab = step.tabId;
2802
+ url = followed.url;
2803
+ } catch {
2804
+ const tabUrl = tabUrls.get(step.tabId);
2805
+ if (tabUrl !== void 0) {
2806
+ try {
2807
+ const navigated = await driver.navigate(tabUrl);
2808
+ currentTab = step.tabId;
2809
+ url = navigated.url;
2810
+ } catch {
2811
+ return {
2812
+ status: "blocked",
2813
+ performed: index,
2814
+ total: steps.length,
2815
+ lines,
2816
+ reason: `tab ${step.tabId} is no longer open and ${tabUrl} could not be reopened`,
2817
+ pending: steps.slice(index),
2818
+ ...url === void 0 ? {} : { url }
2819
+ };
2820
+ }
2821
+ } else {
2822
+ return {
2823
+ status: "blocked",
2824
+ performed: index,
2825
+ total: steps.length,
2826
+ lines,
2827
+ reason: `tab ${step.tabId} is no longer open and the recording has no URL for it`,
2828
+ pending: steps.slice(index),
2829
+ ...url === void 0 ? {} : { url }
2830
+ };
2831
+ }
2832
+ }
2833
+ }
2834
+ const obstacle = replayObstacle(step);
2835
+ if (obstacle !== null) {
2836
+ return {
2837
+ status: "blocked",
2838
+ performed: index,
2839
+ total: steps.length,
2840
+ lines,
2841
+ reason: obstacle,
2842
+ pending: steps.slice(index),
2843
+ ...url === void 0 ? {} : { url }
2844
+ };
2845
+ }
2846
+ const outcome = await performStep(driver, step).catch((error) => ({
2847
+ ok: false,
2848
+ reason: error instanceof Error ? error.message : String(error)
2849
+ }));
2850
+ if (!outcome.ok) {
2851
+ return {
2852
+ status: "blocked",
2853
+ performed: index,
2854
+ total: steps.length,
2855
+ lines,
2856
+ reason: outcome.reason,
2857
+ pending: steps.slice(index),
2858
+ ...url === void 0 ? {} : { url }
2859
+ };
2860
+ }
2861
+ url = outcome.url;
2862
+ lines.push(`${index + 1}. ok ${describeDemoStep(step)}`);
2863
+ }
2864
+ return {
2865
+ status: "done",
2866
+ performed: steps.length,
2867
+ total: steps.length,
2868
+ lines,
2869
+ url: url ?? ""
2870
+ };
2871
+ }
2872
+
2499
2873
  // src/host/browser-agent/tools.ts
2500
2874
  import { defineTool } from "@deepseek-ai/dsh-tools";
2501
2875
  var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
@@ -2675,7 +3049,7 @@ function registerBrowserTools(ctx, options) {
2675
3049
  });
2676
3050
  throw new Error(scope.refusal(tabId));
2677
3051
  };
2678
- const requireMutation = async (exec, tool, summary, url) => {
3052
+ const requireMutation = async (exec, tool, summary, url, targetRef) => {
2679
3053
  const sessionId = sessionIdOf(exec);
2680
3054
  let effectiveUrl = typeof url === "string" && /^https?:\/\//i.test(url) ? url : void 0;
2681
3055
  if (effectiveUrl === void 0) {
@@ -2683,12 +3057,15 @@ function registerBrowserTools(ctx, options) {
2683
3057
  } else {
2684
3058
  options.sessions.rememberHttpUrl(sessionId, effectiveUrl);
2685
3059
  }
3060
+ const thumbDriver = driverOf(options);
3061
+ const thumbnail = targetRef === void 0 || typeof thumbDriver.thumbnail !== "function" ? null : await thumbDriver.thumbnail(targetRef).catch(() => null);
2686
3062
  const decision = await options.approval.requestApproval({
2687
3063
  sessionId,
2688
3064
  tool,
2689
3065
  summary,
2690
3066
  url: effectiveUrl,
2691
- signal: exec.signal
3067
+ signal: exec.signal,
3068
+ ...thumbnail === null ? {} : { thumbnail }
2692
3069
  });
2693
3070
  if (decision === "deny") {
2694
3071
  options.sessions.record({
@@ -3079,7 +3456,7 @@ function registerBrowserTools(ctx, options) {
3079
3456
  );
3080
3457
  }
3081
3458
  const snapshotHref = options.sessions.hrefOfRef(sessionId, ref);
3082
- await requireMutation(exec, "browser_click", `Click ref ${ref}`, url);
3459
+ await requireMutation(exec, "browser_click", `Click ref ${ref}`, url, ref);
3083
3460
  try {
3084
3461
  const beforeUrl = typeof url === "string" ? url : "";
3085
3462
  let result = await runBridge(() => driverOf(options).click(ref));
@@ -3194,7 +3571,7 @@ function registerBrowserTools(ctx, options) {
3194
3571
  url = void 0;
3195
3572
  }
3196
3573
  requireFreshRef(sessionId, ref, "browser_type");
3197
- await requireMutation(exec, "browser_type", `Type into ref ${ref}: ${maskTypeSummary(text3)}`, url);
3574
+ await requireMutation(exec, "browser_type", `Type into ref ${ref}: ${maskTypeSummary(text3)}`, url, ref);
3198
3575
  try {
3199
3576
  const result = await runBridge(() => driverOf(options).type(ref, text3));
3200
3577
  await rememberTab(sessionId, result.tabId);
@@ -3584,7 +3961,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
3584
3961
  )));
3585
3962
  disposers.push(ctx.tools.register(textTool(
3586
3963
  "browser_demonstrate",
3587
- "Ask the user to show you a flow in the dedicated browser window (they click and type, you watch), blocking until they press Continue. Records clicks, filled fields, Enter presses and top-level navigations; password / OTP / token fields are masked as ***. Use it when you cannot work out how a flow works. Returns numbered steps to replay with browser_snapshot then browser_click / browser_type by name (refs change between runs). Requires the Demonstrate switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent.",
3964
+ "Ask the user to show you a flow in the dedicated browser window (they click and type, you watch), blocking until they press Continue. Records clicks, filled fields, Enter presses, top-level navigations and single-page-app route changes in every tab of that browser; each step is tagged with the tab it happened in. Password / OTP / token fields are masked as ***. Use it when you cannot work out how a flow works. Returns numbered steps to replay with browser_snapshot then browser_click / browser_type by name (refs change between runs), or pass replay: true to run the recorded flow immediately. Requires the Demonstrate switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent.",
3588
3965
  {
3589
3966
  message: {
3590
3967
  type: "string",
@@ -3594,6 +3971,10 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
3594
3971
  timeoutMs: {
3595
3972
  type: "number",
3596
3973
  description: "How long to wait for the user, in ms (default 300000)."
3974
+ },
3975
+ replay: {
3976
+ type: "boolean",
3977
+ description: "Run the recorded flow once right after the user finishes (default false). Replay is by role + name against a fresh snapshot; a masked secret, a <select>, or a control that is gone stops it at that step and returns what is left."
3597
3978
  }
3598
3979
  },
3599
3980
  async (args, exec) => {
@@ -3627,25 +4008,69 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
3627
4008
  if (status === "cancelled") {
3628
4009
  return "user_ack: cancelled\nAction: the demonstration was cancelled. Ask what they want next.";
3629
4010
  }
4011
+ if (steps.length > 0) options.onDemonstration?.(steps);
3630
4012
  const summary = summarizeDemoSteps(steps);
3631
4013
  options.sessions.record({
3632
4014
  sessionId,
3633
4015
  tool: "browser_demonstrate",
3634
- summary: `Demonstrated ${summary.shown} step(s)`,
4016
+ summary: `Demonstrated ${summary.shown} step(s)${summary.multiTab ? ` across ${summary.tabs.length} tabs` : ""}`,
3635
4017
  outcome: "ok"
3636
4018
  });
3637
4019
  if (summary.shown === 0) {
3638
4020
  return [
3639
4021
  "demonstrated steps: 0",
3640
- "Nothing was recorded \u2014 the user may have pressed Continue without acting, or the flow happened in another tab.",
4022
+ "Nothing was recorded \u2014 the user may have pressed Continue without acting.",
3641
4023
  "Action: call browser_ask_user to check, or browser_snapshot and continue on your own."
3642
4024
  ].join("\n");
3643
4025
  }
4026
+ const heading = `demonstrated steps: ${summary.shown}${steps.length > summary.shown ? ` (of ${steps.length})` : ""}`;
4027
+ const maskedLine = summary.masked > 0 ? [`masked fields: ${summary.masked} (secret values are never shown)`] : [];
4028
+ if (args.replay === true) {
4029
+ const replay = await replayDemoSteps(driver, steps).catch((error) => ({
4030
+ status: "blocked",
4031
+ performed: 0,
4032
+ total: steps.length,
4033
+ lines: [],
4034
+ reason: error instanceof Error ? error.message : String(error),
4035
+ pending: steps
4036
+ }));
4037
+ options.sessions.record({
4038
+ sessionId,
4039
+ tool: "browser_demonstrate",
4040
+ summary: `Replayed ${replay.performed}/${replay.total} demonstrated step(s)`,
4041
+ outcome: replay.status === "done" ? "ok" : "error"
4042
+ });
4043
+ if (replay.status === "done") {
4044
+ return [
4045
+ `${heading} \u2014 replayed ${replay.performed}/${replay.total}`,
4046
+ ...maskedLine,
4047
+ ...demoTabLegend(summary),
4048
+ ...replay.lines,
4049
+ `url: ${replay.url}`,
4050
+ "Action: the recorded flow ran to the end. Report what changed on screen; call browser_snapshot if you need the new page."
4051
+ ].join("\n");
4052
+ }
4053
+ const pendingLines = replay.pending.map((step, offset) => {
4054
+ const n = replay.performed + offset + 1;
4055
+ const tag = summary.multiTab && step.tabId !== void 0 ? `[tab ${step.tabId}] ` : "";
4056
+ return `${n}. todo ${tag}${describeDemoStep(step)}`;
4057
+ });
4058
+ return [
4059
+ `${heading} \u2014 replayed ${replay.performed}/${replay.total}`,
4060
+ ...maskedLine,
4061
+ ...demoTabLegend(summary),
4062
+ ...replay.lines,
4063
+ `stopped at step ${replay.performed + 1}: ${replay.reason}`,
4064
+ ...pendingLines,
4065
+ "Action: the replay stopped, so the page is whatever the last ok step left behind. Do the remaining steps yourself with browser_snapshot then browser_click / browser_type (role+name), or browser_ask_user if a secret or an unusual control is in the way. Do not claim the flow finished."
4066
+ ].join("\n");
4067
+ }
3644
4068
  return [
3645
- `demonstrated steps: ${summary.shown}${steps.length > summary.shown ? ` (of ${steps.length})` : ""}`,
3646
- ...summary.masked > 0 ? [`masked fields: ${summary.masked} (secret values are never shown)`] : [],
4069
+ heading,
4070
+ ...maskedLine,
4071
+ ...demoTabLegend(summary),
3647
4072
  ...summary.lines,
3648
- "Action: replay with browser_snapshot, then browser_click / browser_type by the role+name shown here. Refs change between runs; never invent selectors."
4073
+ summary.multiTab ? "Action: the flow crossed tabs. browser_list_tabs, then browser_follow_tab for each tab N before acting in it (match by URL; ids are stable while this browser stays open). In each tab: browser_snapshot, then browser_click / browser_type by the role+name shown here. Refs change between runs; never invent selectors." : "Action: replay with browser_snapshot, then browser_click / browser_type by the role+name shown here. Refs change between runs; never invent selectors."
3649
4074
  ].join("\n");
3650
4075
  },
3651
4076
  HUMAN_WAIT_TIMEOUT_MS
@@ -3736,6 +4161,8 @@ function installBrowserAgent(ctx, options) {
3736
4161
  const human = new BrowserHumanGate();
3737
4162
  const sessions = new BrowserSessionState();
3738
4163
  const tabScope = new TabScopeStore();
4164
+ const recipes = options.recipes;
4165
+ let lastDemoSteps = [];
3739
4166
  let availabilityCache = null;
3740
4167
  const browserAvailability = () => {
3741
4168
  if (availabilityCache !== null) return availabilityCache;
@@ -3855,6 +4282,9 @@ function installBrowserAgent(ctx, options) {
3855
4282
  tabScope,
3856
4283
  debugTools: () => options.debugTools?.() === true,
3857
4284
  demonstrate: () => options.demonstrate?.() === true,
4285
+ onDemonstration: (steps) => {
4286
+ lastDemoSteps = steps;
4287
+ },
3858
4288
  diagnosis: diagnoseNow,
3859
4289
  // Gate on settings only — `active` flips false during driver align and
3860
4290
  // must not make browser_* look "disabled" mid-turn.
@@ -4034,6 +4464,7 @@ function installBrowserAgent(ctx, options) {
4034
4464
  const aligned = await alignToPreference();
4035
4465
  if (!aligned.ok) return { ok: false, error: aligned.error ?? "Browser agent failed to start" };
4036
4466
  await requireDriver().startDemonstration();
4467
+ lastDemoSteps = [];
4037
4468
  sessions.record({
4038
4469
  sessionId: "sidebar",
4039
4470
  tool: "browser_demonstrate",
@@ -4050,14 +4481,15 @@ function installBrowserAgent(ctx, options) {
4050
4481
  if (driver === null) return { ok: false, error: "Browser agent is not running" };
4051
4482
  try {
4052
4483
  const steps = await driver.stopDemonstration();
4484
+ lastDemoSteps = steps;
4053
4485
  const summary = summarizeDemoSteps(steps);
4054
4486
  sessions.record({
4055
4487
  sessionId: "sidebar",
4056
4488
  tool: "browser_demonstrate",
4057
- summary: `Demonstration stopped from the sidebar (${summary.shown} step(s))`,
4489
+ summary: `Demonstration stopped from the sidebar (${summary.shown} step(s)${summary.multiTab ? ` across ${summary.tabs.length} tabs` : ""})`,
4058
4490
  outcome: "ok"
4059
4491
  });
4060
- return { ok: true, steps: summary.lines };
4492
+ return { ok: true, steps: [...demoTabLegend(summary), ...summary.lines] };
4061
4493
  } catch (error) {
4062
4494
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
4063
4495
  }
@@ -4065,6 +4497,72 @@ function installBrowserAgent(ctx, options) {
4065
4497
  demoActive() {
4066
4498
  return activeDriver?.demonstrationActive() === true;
4067
4499
  },
4500
+ lastDemonstrationSteps() {
4501
+ return lastDemoSteps.length;
4502
+ },
4503
+ async demoRecipes(input) {
4504
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
4505
+ if (recipes === void 0) return { ok: false, error: "recipe store unavailable" };
4506
+ if (input.action === "list") {
4507
+ return { ok: true, recipes: recipes.list() };
4508
+ }
4509
+ if (input.action === "delete") {
4510
+ const id = input.id ?? "";
4511
+ const removed = recipes.remove(id);
4512
+ sessions.record({
4513
+ sessionId: "sidebar",
4514
+ tool: "browser_demo_recipe",
4515
+ summary: removed ? `Deleted demonstration recipe ${id}` : `Recipe ${id} not found`,
4516
+ outcome: removed ? "ok" : "error"
4517
+ });
4518
+ return removed ? { ok: true, recipes: recipes.list() } : { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4519
+ }
4520
+ if (input.action === "save") {
4521
+ if (options.demonstrate?.() !== true) {
4522
+ return { ok: false, error: "\u6F14\u793A\u5F55\u5236\u672A\u5F00\u542F\uFF1A\u8BBE\u7F6E \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent" };
4523
+ }
4524
+ if (lastDemoSteps.length === 0) {
4525
+ return { ok: false, error: "\u5148\u5F55\u5236\u4E00\u6B21\uFF0C\u518D\u4FDD\u5B58\u4E3A\u6D41\u7A0B", recipes: recipes.list() };
4526
+ }
4527
+ const saved = recipes.save({ name: input.name ?? "", steps: lastDemoSteps });
4528
+ if (!saved.ok) return { ok: false, error: saved.error, recipes: recipes.list() };
4529
+ sessions.record({
4530
+ sessionId: "sidebar",
4531
+ tool: "browser_demo_recipe",
4532
+ summary: `Saved demonstration recipe "${saved.recipe.name}" (${saved.recipe.steps} step(s))`,
4533
+ outcome: "ok"
4534
+ });
4535
+ return { ok: true, recipe: saved.recipe, recipes: recipes.list() };
4536
+ }
4537
+ const recipe = recipes.get(input.id ?? "");
4538
+ if (recipe === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4539
+ const driver = activeDriver;
4540
+ if (driver === null) return { ok: false, error: "Browser agent is not running", recipes: recipes.list() };
4541
+ const aligned = await alignToPreference().catch(() => ({ ok: true, error: void 0 }));
4542
+ if (!aligned.ok) return { ok: false, error: aligned.error ?? "Browser agent failed to start", recipes: recipes.list() };
4543
+ const outcome = await replayDemoSteps(driver, recipe.steps).catch((error) => ({
4544
+ status: "blocked",
4545
+ performed: 0,
4546
+ total: recipe.steps.length,
4547
+ lines: [],
4548
+ reason: error instanceof Error ? error.message : String(error),
4549
+ pending: [...recipe.steps]
4550
+ }));
4551
+ const ranAll = outcome.status === "done";
4552
+ sessions.record({
4553
+ sessionId: "sidebar",
4554
+ tool: "browser_demo_recipe",
4555
+ summary: `Ran demonstration recipe "${recipe.name}" (${outcome.performed}/${outcome.total}${ranAll ? "" : ", stopped"})`,
4556
+ outcome: ranAll ? "ok" : "error"
4557
+ });
4558
+ return {
4559
+ ok: true,
4560
+ recipes: recipes.list(),
4561
+ lines: [...outcome.lines],
4562
+ ...ranAll ? {} : { stoppedAt: outcome.performed + 1 },
4563
+ ...ranAll ? {} : { reason: outcome.reason }
4564
+ };
4565
+ },
4068
4566
  async selectTab(input) {
4069
4567
  if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
4070
4568
  await switchGate.catch(() => void 0);
@@ -4217,6 +4715,106 @@ function installBrowserAgent(ctx, options) {
4217
4715
  };
4218
4716
  }
4219
4717
 
4718
+ // src/host/browser-agent/demo-recipes.ts
4719
+ import { mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "node:fs";
4720
+ import { dirname } from "node:path";
4721
+ var MAX_RECIPES = 20;
4722
+ var MAX_RECIPE_NAME = 60;
4723
+ var MAX_RECIPE_STEPS = 200;
4724
+ var FILE_VERSION = 1;
4725
+ function metaOf(recipe) {
4726
+ return {
4727
+ id: recipe.id,
4728
+ name: recipe.name,
4729
+ createdAt: recipe.createdAt,
4730
+ updatedAt: recipe.updatedAt,
4731
+ steps: recipe.steps.length
4732
+ };
4733
+ }
4734
+ function isStep(value) {
4735
+ if (value === null || typeof value !== "object") return false;
4736
+ const kind = value.kind;
4737
+ return kind === "navigate" || kind === "click" || kind === "fill" || kind === "press";
4738
+ }
4739
+ function sanitizeRecipeSteps(raw) {
4740
+ if (!Array.isArray(raw)) return [];
4741
+ const steps = raw.filter(isStep).slice(0, MAX_RECIPE_STEPS);
4742
+ return sanitizeDemoSteps(steps).map((step) => {
4743
+ const { tabId: _volatileTabId, ...rest } = step;
4744
+ return rest;
4745
+ });
4746
+ }
4747
+ var DemoRecipeStore = class {
4748
+ constructor(filePath = null) {
4749
+ this.filePath = filePath;
4750
+ }
4751
+ filePath;
4752
+ memory = [];
4753
+ list() {
4754
+ return this.read().map(metaOf).sort((a, b) => b.updatedAt - a.updatedAt);
4755
+ }
4756
+ get(id) {
4757
+ return this.read().find((recipe) => recipe.id === id);
4758
+ }
4759
+ /** Save under `name`; the same name (case-insensitive) updates in place. */
4760
+ save(input) {
4761
+ const name2 = input.name.replace(/\s+/gu, " ").trim();
4762
+ if (name2 === "") return { ok: false, error: "\u6D41\u7A0B\u540D\u4E0D\u80FD\u4E3A\u7A7A" };
4763
+ if (name2.length > MAX_RECIPE_NAME) return { ok: false, error: `\u6D41\u7A0B\u540D\u6700\u957F ${MAX_RECIPE_NAME} \u4E2A\u5B57\u7B26` };
4764
+ const steps = sanitizeRecipeSteps(input.steps);
4765
+ if (steps.length === 0) return { ok: false, error: "\u8FD9\u6B21\u5F55\u5236\u6CA1\u6709\u53EF\u4FDD\u5B58\u7684\u6B65\u9AA4" };
4766
+ const now = input.now ?? Date.now();
4767
+ const recipes = this.read();
4768
+ const existing = recipes.find((recipe) => recipe.name.toLowerCase() === name2.toLowerCase());
4769
+ let saved;
4770
+ if (existing !== void 0) {
4771
+ saved = { ...existing, name: name2, steps, updatedAt: now };
4772
+ } else {
4773
+ if (recipes.length >= MAX_RECIPES) {
4774
+ return { ok: false, error: `\u6700\u591A\u4FDD\u5B58 ${MAX_RECIPES} \u4E2A\u6D41\u7A0B\uFF0C\u5148\u5220\u6389\u4E00\u4E2A` };
4775
+ }
4776
+ saved = { id: `r-${now.toString(36)}-${Math.random().toString(36).slice(2, 7)}`, name: name2, createdAt: now, updatedAt: now, steps };
4777
+ }
4778
+ const next = existing === void 0 ? [...recipes, saved] : recipes.map((recipe) => recipe.id === saved.id ? saved : recipe);
4779
+ this.write(next);
4780
+ return { ok: true, recipe: metaOf(saved) };
4781
+ }
4782
+ remove(id) {
4783
+ const recipes = this.read();
4784
+ const next = recipes.filter((recipe) => recipe.id !== id);
4785
+ if (next.length === recipes.length) return false;
4786
+ this.write(next);
4787
+ return true;
4788
+ }
4789
+ read() {
4790
+ if (this.filePath === null) return this.memory;
4791
+ try {
4792
+ const parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
4793
+ if (parsed.version !== FILE_VERSION || !Array.isArray(parsed.recipes)) return [];
4794
+ return parsed.recipes.filter((recipe) => {
4795
+ if (recipe === null || typeof recipe !== "object") return false;
4796
+ if (typeof recipe.id !== "string" || typeof recipe.name !== "string") return false;
4797
+ return typeof recipe.createdAt === "number" && typeof recipe.updatedAt === "number";
4798
+ }).map((recipe) => ({ ...recipe, steps: sanitizeRecipeSteps(recipe.steps) })).filter((recipe) => recipe.steps.length > 0).slice(0, MAX_RECIPES);
4799
+ } catch {
4800
+ return [];
4801
+ }
4802
+ }
4803
+ write(recipes) {
4804
+ if (this.filePath === null) {
4805
+ this.memory = [...recipes];
4806
+ return;
4807
+ }
4808
+ try {
4809
+ mkdirSync2(dirname(this.filePath), { recursive: true });
4810
+ const shape = { version: FILE_VERSION, recipes };
4811
+ writeFileSync(this.filePath, `${JSON.stringify(shape, null, 2)}
4812
+ `, "utf8");
4813
+ } catch {
4814
+ }
4815
+ }
4816
+ };
4817
+
4220
4818
  // src/errors.ts
4221
4819
  var MESSAGES = {
4222
4820
  MODEL_UNAVAILABLE: "No model is available for Agent Enhance",
@@ -7846,7 +8444,7 @@ async function deleteSessionNow(options) {
7846
8444
 
7847
8445
  // src/host/web-chat-bridge/import-session.ts
7848
8446
  import { randomUUID as randomUUID7 } from "node:crypto";
7849
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, statSync } from "node:fs";
8447
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, statSync } from "node:fs";
7850
8448
  import { resolve as resolve2 } from "node:path";
7851
8449
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
7852
8450
  import {
@@ -8807,7 +9405,7 @@ function ensureResolvableWorkspaceCwd(cwd) {
8807
9405
  const absolute = resolve2(cwd);
8808
9406
  try {
8809
9407
  if (!existsSync5(absolute)) {
8810
- mkdirSync2(absolute, { recursive: true });
9408
+ mkdirSync3(absolute, { recursive: true });
8811
9409
  }
8812
9410
  if (!statSync(absolute).isDirectory()) {
8813
9411
  throw new WebChatImportError(
@@ -9674,8 +10272,8 @@ async function fetchWebChatShareContent(shareId, signal) {
9674
10272
  }
9675
10273
 
9676
10274
  // src/host/web-chat-bridge/login-snapshot.ts
9677
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
9678
- import { dirname, join as join9 } from "node:path";
10275
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
10276
+ import { dirname as dirname2, join as join9 } from "node:path";
9679
10277
 
9680
10278
  // src/host/web-chat-bridge/login-snapshot-types.ts
9681
10279
  var WEB_CHAT_OFFICIAL_ORIGIN = "https://chat.deepseek.com";
@@ -9743,7 +10341,7 @@ function loadWebChatLoginSnapshot(pluginDataPackageRoot) {
9743
10341
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
9744
10342
  if (!existsSync6(path)) return null;
9745
10343
  try {
9746
- return parseSnapshot(readFileSync(path, "utf8"));
10344
+ return parseSnapshot(readFileSync2(path, "utf8"));
9747
10345
  } catch {
9748
10346
  return null;
9749
10347
  }
@@ -9768,9 +10366,9 @@ function saveWebChatLoginSnapshot(pluginDataPackageRoot, input, options) {
9768
10366
  savedAt: typeof input.savedAt === "string" && input.savedAt.trim() !== "" ? input.savedAt : (/* @__PURE__ */ new Date()).toISOString()
9769
10367
  };
9770
10368
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
9771
- mkdirSync3(dirname(path), { recursive: true });
10369
+ mkdirSync4(dirname2(path), { recursive: true });
9772
10370
  const tmp = `${path}.${process.pid}.tmp`;
9773
- writeFileSync(tmp, `${JSON.stringify(snapshot, null, 2)}
10371
+ writeFileSync2(tmp, `${JSON.stringify(snapshot, null, 2)}
9774
10372
  `, "utf8");
9775
10373
  renameSync(tmp, path);
9776
10374
  return snapshot;
@@ -10048,8 +10646,8 @@ function loadExtraRootPaths(store, primaryCwd) {
10048
10646
  }
10049
10647
 
10050
10648
  // src/host/extra-folders/store.ts
10051
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
10052
- import { dirname as dirname2, join as join11 } from "node:path";
10649
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "node:fs";
10650
+ import { dirname as dirname3, join as join11 } from "node:path";
10053
10651
  function emptyDoc(primaryCwd) {
10054
10652
  return {
10055
10653
  version: EXTRA_FOLDERS_VERSION,
@@ -10081,14 +10679,14 @@ function parseDoc(raw, primaryCwd) {
10081
10679
  }
10082
10680
  }
10083
10681
  function createExtraFoldersStore(rootDir) {
10084
- mkdirSync4(rootDir, { recursive: true });
10682
+ mkdirSync5(rootDir, { recursive: true });
10085
10683
  const fileOf = (primaryCwd) => join11(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
10086
10684
  return {
10087
10685
  rootDir,
10088
10686
  load(primaryCwd) {
10089
10687
  const file = fileOf(primaryCwd);
10090
10688
  try {
10091
- return parseDoc(readFileSync2(file, "utf8"), primaryCwd);
10689
+ return parseDoc(readFileSync3(file, "utf8"), primaryCwd);
10092
10690
  } catch (error) {
10093
10691
  const code = error !== null && typeof error === "object" ? String(Reflect.get(error, "code") ?? "") : "";
10094
10692
  if (code === "ENOENT") return emptyDoc(primaryCwd);
@@ -10102,9 +10700,9 @@ function createExtraFoldersStore(rootDir) {
10102
10700
  roots: [...roots]
10103
10701
  };
10104
10702
  const file = fileOf(primaryCwd);
10105
- mkdirSync4(dirname2(file), { recursive: true });
10703
+ mkdirSync5(dirname3(file), { recursive: true });
10106
10704
  const tmp = `${file}.${process.pid}.tmp`;
10107
- writeFileSync2(tmp, `${JSON.stringify(doc, null, 2)}
10705
+ writeFileSync3(tmp, `${JSON.stringify(doc, null, 2)}
10108
10706
  `, "utf8");
10109
10707
  renameSync2(tmp, file);
10110
10708
  return doc;
@@ -10292,7 +10890,7 @@ async function writeWorkspaceFileNow(options) {
10292
10890
  // src/host/file-edit/monaco.ts
10293
10891
  import { existsSync as existsSync7 } from "node:fs";
10294
10892
  import { promises as fsp2 } from "node:fs";
10295
- import { dirname as dirname3, extname, join as join12, resolve as resolve6, sep as sep5 } from "node:path";
10893
+ import { dirname as dirname4, extname, join as join12, resolve as resolve6, sep as sep5 } from "node:path";
10296
10894
  import { fileURLToPath } from "node:url";
10297
10895
 
10298
10896
  // src/shared/monaco-route.ts
@@ -10301,7 +10899,7 @@ var MONACO_ROUTE = "/api/agent-enhancer/monaco";
10301
10899
  // src/host/file-edit/monaco.ts
10302
10900
  var FILE_PATTERN = /^(?:vs\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/;
10303
10901
  function packageRootCandidates() {
10304
- const here = dirname3(fileURLToPath(import.meta.url));
10902
+ const here = dirname4(fileURLToPath(import.meta.url));
10305
10903
  return [
10306
10904
  resolve6(here, "..", "vendor", "monaco", "vs"),
10307
10905
  resolve6(here, "..", "..", "vendor", "monaco", "vs"),
@@ -10447,16 +11045,16 @@ function installMonacoRoute(ctx) {
10447
11045
  }
10448
11046
 
10449
11047
  // src/host/instructions-skills/io.ts
10450
- import { existsSync as existsSync17, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
11048
+ import { existsSync as existsSync17, readFileSync as readFileSync8, statSync as statSync5 } from "node:fs";
10451
11049
  import { basename as basename13, join as join26, resolve as resolve16, sep as sep7 } from "node:path";
10452
11050
 
10453
11051
  // src/host/instructions-skills/create.ts
10454
- import { existsSync as existsSync9, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
10455
- import { dirname as dirname5, join as join14, resolve as resolve8 } from "node:path";
11052
+ import { existsSync as existsSync9, mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "node:fs";
11053
+ import { dirname as dirname6, join as join14, resolve as resolve8 } from "node:path";
10456
11054
 
10457
11055
  // src/host/instructions-skills/paths.ts
10458
11056
  import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
10459
- import { basename as basename5, dirname as dirname4, join as join13, resolve as resolve7, sep as sep6 } from "node:path";
11057
+ import { basename as basename5, dirname as dirname5, join as join13, resolve as resolve7, sep as sep6 } from "node:path";
10460
11058
  import { homedir as homedir3 } from "node:os";
10461
11059
  var INSTRUCTION_CANDIDATES = [
10462
11060
  "AGENTS.md",
@@ -10481,7 +11079,7 @@ function findProjectRoot(cwd, markers = PROJECT_ROOT_MARKERS) {
10481
11079
  for (const marker of markers) {
10482
11080
  if (existsSync8(join13(current, marker))) return current;
10483
11081
  }
10484
- const parent = dirname4(current);
11082
+ const parent = dirname5(current);
10485
11083
  if (parent === current) return resolve7(cwd);
10486
11084
  current = parent;
10487
11085
  }
@@ -10495,7 +11093,7 @@ function projectChainDirs(projectRoot, cwd) {
10495
11093
  for (; ; ) {
10496
11094
  parts.push(current);
10497
11095
  if (samePath2(current, root)) break;
10498
- const parent = dirname4(current);
11096
+ const parent = dirname5(current);
10499
11097
  if (parent === current) break;
10500
11098
  current = parent;
10501
11099
  }
@@ -10579,8 +11177,8 @@ function createWorkspaceAgentsFile(projectRoot) {
10579
11177
  if (existsSync9(path)) {
10580
11178
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
10581
11179
  }
10582
- mkdirSync5(dirname5(path), { recursive: true });
10583
- writeFileSync3(path, AGENTS_STUB, "utf8");
11180
+ mkdirSync6(dirname6(path), { recursive: true });
11181
+ writeFileSync4(path, AGENTS_STUB, "utf8");
10584
11182
  return { path, created: true };
10585
11183
  }
10586
11184
  function createWorkspaceSkill(projectRoot, rawName) {
@@ -10593,14 +11191,14 @@ function createWorkspaceSkill(projectRoot, rawName) {
10593
11191
  if (existsSync9(path) || existsSync9(dir)) {
10594
11192
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
10595
11193
  }
10596
- mkdirSync5(dir, { recursive: true });
10597
- writeFileSync3(path, skillStubMarkdown(name2), "utf8");
11194
+ mkdirSync6(dir, { recursive: true });
11195
+ writeFileSync4(path, skillStubMarkdown(name2), "utf8");
10598
11196
  return { path, created: true, name: name2 };
10599
11197
  }
10600
11198
 
10601
11199
  // src/host/instructions-skills/discover.ts
10602
- import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
10603
- import { basename as basename9, dirname as dirname8, join as join19, resolve as resolve12 } from "node:path";
11200
+ import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "node:fs";
11201
+ import { basename as basename9, dirname as dirname9, join as join19, resolve as resolve12 } from "node:path";
10604
11202
 
10605
11203
  // src/host/instructions-skills/types.ts
10606
11204
  function defaultSkillInstallMeta() {
@@ -10677,19 +11275,19 @@ function removeQuietly(path) {
10677
11275
 
10678
11276
  // src/host/instructions-skills/uninstall.ts
10679
11277
  import { lstatSync as lstatSync3 } from "node:fs";
10680
- import { basename as basename8, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
11278
+ import { basename as basename8, dirname as dirname8, join as join18, resolve as resolve11 } from "node:path";
10681
11279
 
10682
11280
  // src/host/instructions-skills/install-ledger.ts
10683
- import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
10684
- import { dirname as dirname6, join as join16 } from "node:path";
11281
+ import { existsSync as existsSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync4, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
11282
+ import { dirname as dirname7, join as join16 } from "node:path";
10685
11283
  function ledgerPath(dataRoot) {
10686
11284
  return join16(dataRoot, "skills-install", "registry.json");
10687
11285
  }
10688
11286
  function writeLedger(dataRoot, ledger) {
10689
11287
  const path = ledgerPath(dataRoot);
10690
- mkdirSync6(dirname6(path), { recursive: true });
11288
+ mkdirSync7(dirname7(path), { recursive: true });
10691
11289
  const tmp = `${path}.${process.pid}.tmp`;
10692
- writeFileSync4(tmp, `${JSON.stringify(ledger, null, 2)}
11290
+ writeFileSync5(tmp, `${JSON.stringify(ledger, null, 2)}
10693
11291
  `, "utf8");
10694
11292
  renameSync4(tmp, path);
10695
11293
  }
@@ -10697,7 +11295,7 @@ function readInstallLedger(dataRoot) {
10697
11295
  const path = ledgerPath(dataRoot);
10698
11296
  if (!existsSync11(path)) return {};
10699
11297
  try {
10700
- const raw = readFileSync3(path, "utf8").trim();
11298
+ const raw = readFileSync4(path, "utf8").trim();
10701
11299
  if (raw === "") return {};
10702
11300
  return JSON.parse(raw);
10703
11301
  } catch {
@@ -10905,7 +11503,7 @@ function removePathRobust(target) {
10905
11503
  function skillEntryPath(skillMdOrBundlePath) {
10906
11504
  const absolute = resolve11(skillMdOrBundlePath);
10907
11505
  const base = basename8(absolute);
10908
- if (base.toLowerCase() === "skill.md") return dirname7(absolute);
11506
+ if (base.toLowerCase() === "skill.md") return dirname8(absolute);
10909
11507
  if (base.toLowerCase().endsWith(".md")) return absolute;
10910
11508
  return absolute;
10911
11509
  }
@@ -10924,7 +11522,7 @@ function managedSkillEntriesForName(root, name2) {
10924
11522
  const asFile = join18(root, `${name2}.md`);
10925
11523
  for (const entry of [asDir, asFile]) {
10926
11524
  if (!pathPresent2(entry)) continue;
10927
- if (!samePath2(dirname7(entry), root)) continue;
11525
+ if (!samePath2(dirname8(entry), root)) continue;
10928
11526
  if (!isInsideOrSame(root, entry)) continue;
10929
11527
  out.push(entry);
10930
11528
  }
@@ -10938,7 +11536,7 @@ function resolveManagedSkillRemovalTarget(path, name2, managedRoots) {
10938
11536
  const asFile = join18(root, `${name2}.md`);
10939
11537
  if (samePath2(entry, asDir) || samePath2(entry, asFile)) {
10940
11538
  if (!pathPresent2(entry)) return null;
10941
- if (!samePath2(dirname7(entry), root)) return null;
11539
+ if (!samePath2(dirname8(entry), root)) return null;
10942
11540
  if (!isInsideOrSame(root, entry)) return null;
10943
11541
  return entry;
10944
11542
  }
@@ -11067,7 +11665,7 @@ function discoverInstructionFiles(options) {
11067
11665
  }
11068
11666
  function descriptionFromSkillMd(path) {
11069
11667
  try {
11070
- const text3 = readFileSync4(path, "utf8");
11668
+ const text3 = readFileSync5(path, "utf8");
11071
11669
  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text3);
11072
11670
  if (match === null) return "";
11073
11671
  const block = match[1];
@@ -11118,7 +11716,7 @@ function dirnameLabel(root, projectRoot, env) {
11118
11716
  if (samePath2(root, join19(projectRoot, ".dsh", "skills"))) return "project-dsh";
11119
11717
  if (samePath2(root, join19(agentsHomeOf(env), "skills"))) return "shared";
11120
11718
  if (samePath2(root, join19(dshHomeOf(env), "skills"))) return "dsh-home";
11121
- const parent = basename9(dirname8(root)).toLowerCase();
11719
+ const parent = basename9(dirname9(root)).toLowerCase();
11122
11720
  const leaf = basename9(root).toLowerCase();
11123
11721
  if (parent === ".cursor" && leaf === "skills") return "cursor";
11124
11722
  if (parent === ".cursor" && leaf === "skills-cursor") return "cursor-builtin";
@@ -11334,14 +11932,14 @@ function parseGitSkillSource(raw) {
11334
11932
  import { execFile as execFile3, spawn } from "node:child_process";
11335
11933
  import { existsSync as existsSync15, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
11336
11934
  import { tmpdir as tmpdir3 } from "node:os";
11337
- import { basename as basename11, dirname as dirname10, join as join23, resolve as resolve14 } from "node:path";
11935
+ import { basename as basename11, dirname as dirname11, join as join23, resolve as resolve14 } from "node:path";
11338
11936
  import { promisify as promisify3 } from "node:util";
11339
11937
 
11340
11938
  // src/host/instructions-skills/github-archive.ts
11341
11939
  import { execFile as execFile2 } from "node:child_process";
11342
11940
  import {
11343
11941
  createWriteStream,
11344
- mkdirSync as mkdirSync7,
11942
+ mkdirSync as mkdirSync8,
11345
11943
  readdirSync as readdirSync4,
11346
11944
  renameSync as renameSync5,
11347
11945
  rmSync as rmSync3,
@@ -11392,7 +11990,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
11392
11990
  }
11393
11991
  async function extractZip(zipPath, destDir, signal) {
11394
11992
  signal.throwIfAborted();
11395
- mkdirSync7(destDir, { recursive: true });
11993
+ mkdirSync8(destDir, { recursive: true });
11396
11994
  try {
11397
11995
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
11398
11996
  windowsHide: true,
@@ -11450,10 +12048,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
11450
12048
  }
11451
12049
  async function fetchGithubRepoArchive(options) {
11452
12050
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
11453
- mkdirSync7(workDir, { recursive: true });
12051
+ mkdirSync8(workDir, { recursive: true });
11454
12052
  const zipPath = join20(workDir, "repo.zip");
11455
12053
  const extractDir = join20(workDir, "extract");
11456
- mkdirSync7(extractDir, { recursive: true });
12054
+ mkdirSync8(extractDir, { recursive: true });
11457
12055
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
11458
12056
  const candidates = archiveCandidates(owner, repo, defaultBranch);
11459
12057
  const errors = [];
@@ -11464,7 +12062,7 @@ async function fetchGithubRepoArchive(options) {
11464
12062
  try {
11465
12063
  rmSync3(zipPath, { force: true });
11466
12064
  rmSync3(extractDir, { recursive: true, force: true });
11467
- mkdirSync7(extractDir, { recursive: true });
12065
+ mkdirSync8(extractDir, { recursive: true });
11468
12066
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
11469
12067
  if (!downloadStarted) {
11470
12068
  onStage?.("downloading", detail);
@@ -11508,16 +12106,16 @@ import {
11508
12106
  cpSync,
11509
12107
  existsSync as existsSync14,
11510
12108
  lstatSync as lstatSync4,
11511
- mkdirSync as mkdirSync8,
12109
+ mkdirSync as mkdirSync9,
11512
12110
  readdirSync as readdirSync5,
11513
- readFileSync as readFileSync5,
12111
+ readFileSync as readFileSync6,
11514
12112
  renameSync as renameSync6,
11515
12113
  symlinkSync
11516
12114
  } from "node:fs";
11517
- import { basename as basename10, dirname as dirname9, join as join21, resolve as resolve13 } from "node:path";
12115
+ import { basename as basename10, dirname as dirname10, join as join21, resolve as resolve13 } from "node:path";
11518
12116
  function frontmatterBlock(path) {
11519
12117
  try {
11520
- const text3 = readFileSync5(path, "utf8");
12118
+ const text3 = readFileSync6(path, "utf8");
11521
12119
  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text3);
11522
12120
  return match?.[1] ?? null;
11523
12121
  } catch {
@@ -11583,7 +12181,7 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
11583
12181
  throw new AuxiliaryError("FILE_NOT_FOUND", `Path not found in repository: ${subpath ?? "."}`);
11584
12182
  }
11585
12183
  if (base.toLowerCase().endsWith("skill.md") && existsSync14(base)) {
11586
- const dir = dirname9(base);
12184
+ const dir = dirname10(base);
11587
12185
  const name2 = directoryBundleName(dir, basename10(dir));
11588
12186
  if (!isKebabCaseName(name2)) {
11589
12187
  throw new AuxiliaryError("FILE_DENIED", `Skill directory name must be kebab-case: ${name2}`);
@@ -11657,7 +12255,7 @@ function copySkillTree(source, dest) {
11657
12255
  }
11658
12256
  }
11659
12257
  function copySkillTreeAtomic(source, dest, kind) {
11660
- mkdirSync8(dirname9(dest), { recursive: true });
12258
+ mkdirSync9(dirname10(dest), { recursive: true });
11661
12259
  if (kind === "file") {
11662
12260
  if (destinationPresent(dest)) removeDestination(dest);
11663
12261
  copySkillTree(source, dest);
@@ -11685,7 +12283,7 @@ function copySkillTreeAtomic(source, dest, kind) {
11685
12283
  }
11686
12284
  }
11687
12285
  function linkOrCopy(source, dest, mode, kind) {
11688
- mkdirSync8(dirname9(dest), { recursive: true });
12286
+ mkdirSync9(dirname10(dest), { recursive: true });
11689
12287
  if (mode === "copy") {
11690
12288
  copySkillTreeAtomic(source, dest, kind);
11691
12289
  return "copy";
@@ -11723,7 +12321,7 @@ function installBundle(options) {
11723
12321
 
11724
12322
  // src/host/instructions-skills/content-revision.ts
11725
12323
  import { createHash as createHash7 } from "node:crypto";
11726
- import { readdirSync as readdirSync6, readFileSync as readFileSync6 } from "node:fs";
12324
+ import { readdirSync as readdirSync6, readFileSync as readFileSync7 } from "node:fs";
11727
12325
  import { join as join22, relative as relative3 } from "node:path";
11728
12326
  function listRelativeFiles(dir, root) {
11729
12327
  const entries = [];
@@ -11742,7 +12340,7 @@ function contentRevisionOfDir(dir) {
11742
12340
  const paths = listRelativeFiles(dir, dir).sort();
11743
12341
  const aggregate = createHash7("sha256");
11744
12342
  for (const relPath of paths) {
11745
- const contents = readFileSync6(join22(dir, relPath));
12343
+ const contents = readFileSync7(join22(dir, relPath));
11746
12344
  const fileDigest = createHash7("sha256").update(`${relPath}\0`).update(contents).digest();
11747
12345
  aggregate.update(fileDigest);
11748
12346
  }
@@ -12160,7 +12758,7 @@ async function checkGithubSkillUpdate(record2, options) {
12160
12758
 
12161
12759
  // src/host/instructions-skills/zip-install.ts
12162
12760
  import { execFile as execFile4 } from "node:child_process";
12163
- import { existsSync as existsSync16, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
12761
+ import { existsSync as existsSync16, mkdirSync as mkdirSync10, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
12164
12762
  import { tmpdir as tmpdir5 } from "node:os";
12165
12763
  import { basename as basename12, join as join25, resolve as resolve15 } from "node:path";
12166
12764
  import { promisify as promisify4 } from "node:util";
@@ -12175,7 +12773,7 @@ function tempWorkDir3(prefix) {
12175
12773
  }
12176
12774
  async function extractZipArchive(zipPath, destDir, signal) {
12177
12775
  signal.throwIfAborted();
12178
- mkdirSync9(destDir, { recursive: true });
12776
+ mkdirSync10(destDir, { recursive: true });
12179
12777
  try {
12180
12778
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
12181
12779
  windowsHide: true,
@@ -12620,7 +13218,7 @@ async function readSkillDocumentNow(options) {
12620
13218
  options.signal.throwIfAborted();
12621
13219
  let text3;
12622
13220
  try {
12623
- text3 = readFileSync7(absolutePath2, "utf8");
13221
+ text3 = readFileSync8(absolutePath2, "utf8");
12624
13222
  } catch {
12625
13223
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
12626
13224
  }
@@ -12759,7 +13357,7 @@ function parseMcpJsonText(jsonText) {
12759
13357
  }
12760
13358
 
12761
13359
  // src/host/mcp-connectors/install-git.ts
12762
- import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
13360
+ import { existsSync as existsSync18, mkdirSync as mkdirSync11, readFileSync as readFileSync9, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
12763
13361
  import { join as join28 } from "node:path";
12764
13362
 
12765
13363
  // src/host/mcp-connectors/paths.ts
@@ -12802,7 +13400,7 @@ function inferStdioFromPackageJson(installDir, override) {
12802
13400
  };
12803
13401
  }
12804
13402
  try {
12805
- const pkg = JSON.parse(readFileSync8(pkgPath, "utf8"));
13403
+ const pkg = JSON.parse(readFileSync9(pkgPath, "utf8"));
12806
13404
  if (isRecord4(pkg)) {
12807
13405
  const bin = pkg.bin;
12808
13406
  if (typeof bin === "string" && bin.trim() !== "") {
@@ -12857,11 +13455,11 @@ async function installMcpServerFromGit(options) {
12857
13455
  }
12858
13456
  removePathRobust(installDir);
12859
13457
  }
12860
- mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
13458
+ mkdirSync11(join28(options.rootDir, "mcp-servers"), { recursive: true });
12861
13459
  const staging = `${installDir}.staging.${process.pid}`;
12862
13460
  try {
12863
13461
  if (existsSync18(staging)) removePathRobust(staging);
12864
- mkdirSync10(staging, { recursive: true });
13462
+ mkdirSync11(staging, { recursive: true });
12865
13463
  if (parsed.github === null) {
12866
13464
  throw new AuxiliaryError(
12867
13465
  "FILE_EDIT_FAILED",
@@ -12883,7 +13481,7 @@ async function installMcpServerFromGit(options) {
12883
13481
  }
12884
13482
  contentRoot = nested;
12885
13483
  }
12886
- mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
13484
+ mkdirSync11(join28(options.rootDir, "mcp-servers"), { recursive: true });
12887
13485
  if (contentRoot !== repoDir) {
12888
13486
  const nestedStaging = `${installDir}.nested.${process.pid}`;
12889
13487
  renameSync7(contentRoot, nestedStaging);
@@ -13149,8 +13747,8 @@ async function probeMcpConnectorNow(host, request, signal) {
13149
13747
  }
13150
13748
 
13151
13749
  // src/host/mcp-connectors/store.ts
13152
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
13153
- import { dirname as dirname11 } from "node:path";
13750
+ import { mkdirSync as mkdirSync12, readFileSync as readFileSync10, renameSync as renameSync8, writeFileSync as writeFileSync6 } from "node:fs";
13751
+ import { dirname as dirname12 } from "node:path";
13154
13752
 
13155
13753
  // src/host/mcp-connectors/types.ts
13156
13754
  var MCP_CONNECTORS_VERSION = 1;
@@ -13232,13 +13830,13 @@ function parseDoc2(raw) {
13232
13830
  }
13233
13831
  }
13234
13832
  function createMcpConnectorsStore(rootDir) {
13235
- mkdirSync11(rootDir, { recursive: true });
13833
+ mkdirSync12(rootDir, { recursive: true });
13236
13834
  const file = mcpConnectorsLedgerPath(rootDir);
13237
13835
  return {
13238
13836
  rootDir,
13239
13837
  load() {
13240
13838
  try {
13241
- return parseDoc2(readFileSync9(file, "utf8"));
13839
+ return parseDoc2(readFileSync10(file, "utf8"));
13242
13840
  } catch (error) {
13243
13841
  const code = error !== null && typeof error === "object" ? String(Reflect.get(error, "code") ?? "") : "";
13244
13842
  if (code !== "ENOENT") {
@@ -13251,9 +13849,9 @@ function createMcpConnectorsStore(rootDir) {
13251
13849
  version: MCP_CONNECTORS_VERSION,
13252
13850
  connectors: [...connectors]
13253
13851
  };
13254
- mkdirSync11(dirname11(file), { recursive: true });
13852
+ mkdirSync12(dirname12(file), { recursive: true });
13255
13853
  const tmp = `${file}.${process.pid}.tmp`;
13256
- writeFileSync5(tmp, `${JSON.stringify(doc, null, 2)}
13854
+ writeFileSync6(tmp, `${JSON.stringify(doc, null, 2)}
13257
13855
  `, "utf8");
13258
13856
  renameSync8(tmp, file);
13259
13857
  return doc;
@@ -16163,7 +16761,9 @@ var browserAgentPendingSchema = z4.strictObject({
16163
16761
  tool: z4.string().min(1),
16164
16762
  summary: z4.string().min(1),
16165
16763
  url: z4.string().optional(),
16166
- origin: z4.string().optional()
16764
+ origin: z4.string().optional(),
16765
+ /** A crop of the target control exists; fetch it with browserAgentThumbnail. */
16766
+ hasThumbnail: z4.boolean().optional()
16167
16767
  });
16168
16768
  var browserAgentTabConflictSchema = z4.strictObject({
16169
16769
  sessionId: z4.string().min(1),
@@ -16229,7 +16829,9 @@ var browserAgentSnapshotSchema = z4.strictObject({
16229
16829
  /** Demonstration recorder: switch state and whether it is recording now. */
16230
16830
  demo: z4.strictObject({
16231
16831
  enabled: z4.boolean(),
16232
- recording: z4.boolean()
16832
+ recording: z4.boolean(),
16833
+ /** Steps from the last finished recording, whoever stopped it. */
16834
+ lastSteps: z4.number().int()
16233
16835
  }),
16234
16836
  tabConflict: browserAgentTabConflictSchema.nullable(),
16235
16837
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
@@ -16262,6 +16864,55 @@ var browserAgentDemoResultCodec = codec(
16262
16864
  "dsh-agent-enhancer#BrowserAgentDemoResult",
16263
16865
  browserAgentDemoResultSchema
16264
16866
  );
16867
+ var browserAgentThumbnailRequestSchema = z4.strictObject({
16868
+ id: z4.string().min(1)
16869
+ });
16870
+ var browserAgentThumbnailRequestCodec = codec(
16871
+ "dsh-agent-enhancer#BrowserAgentThumbnailRequest",
16872
+ browserAgentThumbnailRequestSchema
16873
+ );
16874
+ var browserAgentThumbnailResultSchema = z4.strictObject({
16875
+ ok: z4.boolean(),
16876
+ mime: z4.string().optional(),
16877
+ base64: z4.string().optional(),
16878
+ error: z4.string().optional()
16879
+ });
16880
+ var browserAgentThumbnailResultCodec = codec(
16881
+ "dsh-agent-enhancer#BrowserAgentThumbnailResult",
16882
+ browserAgentThumbnailResultSchema
16883
+ );
16884
+ var demoRecipeMetaSchema = z4.strictObject({
16885
+ id: z4.string().min(1),
16886
+ name: z4.string().min(1),
16887
+ createdAt: z4.number(),
16888
+ updatedAt: z4.number(),
16889
+ steps: z4.number().int()
16890
+ });
16891
+ var browserAgentDemoRecipesRequestSchema = z4.discriminatedUnion("action", [
16892
+ z4.strictObject({ action: z4.literal("list") }),
16893
+ z4.strictObject({ action: z4.literal("save"), name: z4.string() }),
16894
+ z4.strictObject({ action: z4.literal("run"), id: z4.string().min(1) }),
16895
+ z4.strictObject({ action: z4.literal("delete"), id: z4.string().min(1) })
16896
+ ]);
16897
+ var browserAgentDemoRecipesRequestCodec = codec(
16898
+ "dsh-agent-enhancer#BrowserAgentDemoRecipesRequest",
16899
+ browserAgentDemoRecipesRequestSchema
16900
+ );
16901
+ var browserAgentDemoRecipesResultSchema = z4.strictObject({
16902
+ ok: z4.boolean(),
16903
+ recipes: z4.array(demoRecipeMetaSchema).optional(),
16904
+ recipe: demoRecipeMetaSchema.optional(),
16905
+ /** Replay lines when running a recipe (`1. ok …`). */
16906
+ lines: z4.array(z4.string()).optional(),
16907
+ /** 1-based step where a replay stopped. */
16908
+ stoppedAt: z4.number().int().optional(),
16909
+ reason: z4.string().optional(),
16910
+ error: z4.string().optional()
16911
+ });
16912
+ var browserAgentDemoRecipesResultCodec = codec(
16913
+ "dsh-agent-enhancer#BrowserAgentDemoRecipesResult",
16914
+ browserAgentDemoRecipesResultSchema
16915
+ );
16265
16916
  var browserAgentResolveRequestSchema = z4.strictObject({
16266
16917
  id: z4.string().min(1),
16267
16918
  decision: browserAgentApprovalDecisionSchema
@@ -17156,6 +17807,30 @@ var remoteInfo = createTypertRemoteInfo({
17156
17807
  }],
17157
17808
  result: browserAgentSelectTabResultCodec
17158
17809
  },
17810
+ "agentEnhancer/browserAgentDemoRecipes": {
17811
+ service: "agentEnhancer",
17812
+ implementation: "browserAgentDemoRecipes",
17813
+ invocation: { kind: "direct" },
17814
+ parameters: [{
17815
+ name: "request",
17816
+ source: "json",
17817
+ codec: browserAgentDemoRecipesRequestCodec,
17818
+ strictCodec: browserAgentDemoRecipesRequestCodec
17819
+ }],
17820
+ result: browserAgentDemoRecipesResultCodec
17821
+ },
17822
+ "agentEnhancer/browserAgentThumbnail": {
17823
+ service: "agentEnhancer",
17824
+ implementation: "browserAgentThumbnail",
17825
+ invocation: { kind: "direct" },
17826
+ parameters: [{
17827
+ name: "request",
17828
+ source: "json",
17829
+ codec: browserAgentThumbnailRequestCodec,
17830
+ strictCodec: browserAgentThumbnailRequestCodec
17831
+ }],
17832
+ result: browserAgentThumbnailResultCodec
17833
+ },
17159
17834
  "agentEnhancer/browserAgentDemo": {
17160
17835
  service: "agentEnhancer",
17161
17836
  implementation: "browserAgentDemo",
@@ -17983,11 +18658,13 @@ var AgentEnhancerService = class extends TypertRemoteService {
17983
18658
  tool: pending.tool,
17984
18659
  summary: pending.summary,
17985
18660
  ...pending.url === void 0 ? {} : { url: pending.url },
17986
- ...pending.origin === void 0 ? {} : { origin: pending.origin }
18661
+ ...pending.origin === void 0 ? {} : { origin: pending.origin },
18662
+ hasThumbnail: pending.thumbnail !== void 0
17987
18663
  },
17988
18664
  demo: {
17989
18665
  enabled: settings.demonstrate,
17990
- recording: this.browserAgent?.demoActive() === true
18666
+ recording: this.browserAgent?.demoActive() === true,
18667
+ lastSteps: this.browserAgent?.lastDemonstrationSteps() ?? 0
17991
18668
  },
17992
18669
  diagnosis: diag ?? {
17993
18670
  code: settings.enabled ? "idle" : "disabled",
@@ -18696,6 +19373,31 @@ var AgentEnhancerService = class extends TypertRemoteService {
18696
19373
  snapshot: await this.browserSnapshotNow()
18697
19374
  };
18698
19375
  }
19376
+ async browserAgentThumbnail(request) {
19377
+ this.assertOwner();
19378
+ const thumb = this.browserAgent?.approval.thumbnailFor(request.id) ?? null;
19379
+ if (thumb === null) return { ok: false, error: "no preview for this approval" };
19380
+ return { ok: true, mime: thumb.mime, base64: thumb.base64 };
19381
+ }
19382
+ async browserAgentDemoRecipes(request) {
19383
+ this.assertOwner();
19384
+ const runtime = this.browserAgent;
19385
+ if (runtime === null) return { ok: false, error: "runtime unavailable" };
19386
+ const result = await runtime.demoRecipes({
19387
+ action: request.action,
19388
+ ..."name" in request ? { name: request.name } : {},
19389
+ ..."id" in request ? { id: request.id } : {}
19390
+ });
19391
+ return {
19392
+ ok: result.ok,
19393
+ ...result.recipes === void 0 ? {} : { recipes: result.recipes.map((recipe) => ({ ...recipe })) },
19394
+ ...result.recipe === void 0 ? {} : { recipe: { ...result.recipe } },
19395
+ ...result.lines === void 0 ? {} : { lines: [...result.lines] },
19396
+ ...result.stoppedAt === void 0 ? {} : { stoppedAt: result.stoppedAt },
19397
+ ...result.reason === void 0 ? {} : { reason: result.reason },
19398
+ ...result.error === void 0 ? {} : { error: result.error }
19399
+ };
19400
+ }
18699
19401
  async browserAgentDemo(request) {
18700
19402
  this.assertOwner();
18701
19403
  if (request.action === "start") {
@@ -18733,7 +19435,7 @@ function resolveCheckpointRoot(dshHome2) {
18733
19435
  const next = join30(nextPkg, "checkpoint");
18734
19436
  const prev = join30(base, LEGACY_PACKAGE_NAME, "checkpoint");
18735
19437
  if (!existsSync20(next) && existsSync20(prev)) {
18736
- mkdirSync12(nextPkg, { recursive: true });
19438
+ mkdirSync13(nextPkg, { recursive: true });
18737
19439
  renameSync9(prev, next);
18738
19440
  const prevPkg = join30(base, LEGACY_PACKAGE_NAME);
18739
19441
  try {
@@ -18902,6 +19604,7 @@ function apply(ctx, config) {
18902
19604
  debugTools: () => settings().browserAgentDebugTools,
18903
19605
  demonstrate: () => settings().browserAgentDemonstrate,
18904
19606
  idleClose: () => settings().browserAgentIdleClose,
19607
+ recipes: new DemoRecipeStore(join30(pluginDataPackageRoot, "demo-recipes.json")),
18905
19608
  profileRoot: pluginDataPackageRoot,
18906
19609
  softPause: softPauseGate,
18907
19610
  softPauseEnabled: () => settings().softPauseEnabled,