dsh-agent-enhancer 0.3.20 → 0.3.22

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 (35) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/lib/client/browser-agent/tab.d.ts.map +1 -1
  4. package/lib/client/dsh/settings-features.d.ts +1 -0
  5. package/lib/client/dsh/settings-features.d.ts.map +1 -1
  6. package/lib/client/dsh/settings.d.ts.map +1 -1
  7. package/lib/client/locales.d.ts +35 -7
  8. package/lib/client/locales.d.ts.map +1 -1
  9. package/lib/client.js +214 -64
  10. package/lib/client.js.map +1 -1
  11. package/lib/config.d.ts +2 -0
  12. package/lib/config.d.ts.map +1 -1
  13. package/lib/host/browser-agent/demo-heal.d.ts +146 -0
  14. package/lib/host/browser-agent/demo-heal.d.ts.map +1 -0
  15. package/lib/host/browser-agent/demo-recipes.d.ts +92 -2
  16. package/lib/host/browser-agent/demo-recipes.d.ts.map +1 -1
  17. package/lib/host/browser-agent/demo-values.d.ts +50 -0
  18. package/lib/host/browser-agent/demo-values.d.ts.map +1 -0
  19. package/lib/host/browser-agent/demo.d.ts +8 -0
  20. package/lib/host/browser-agent/demo.d.ts.map +1 -1
  21. package/lib/host/browser-agent/driver.d.ts +10 -0
  22. package/lib/host/browser-agent/driver.d.ts.map +1 -1
  23. package/lib/host/browser-agent/install.d.ts +14 -1
  24. package/lib/host/browser-agent/install.d.ts.map +1 -1
  25. package/lib/host/browser-agent/playwright-driver.d.ts +11 -0
  26. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  27. package/lib/host/browser-agent/tools.d.ts +7 -0
  28. package/lib/host/browser-agent/tools.d.ts.map +1 -1
  29. package/lib/host/index.d.ts +4 -0
  30. package/lib/host/index.d.ts.map +1 -1
  31. package/lib/host/rpc.d.ts +110 -1
  32. package/lib/host/rpc.d.ts.map +1 -1
  33. package/lib/index.js +985 -53
  34. package/lib/index.js.map +4 -4
  35. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -92,6 +92,7 @@ var DEFAULT_SETTINGS = {
92
92
  browserAgentBrowser: "auto",
93
93
  browserAgentDebugTools: false,
94
94
  browserAgentDemonstrate: false,
95
+ browserAgentAutoHeal: false,
95
96
  browserAgentIdleClose: "10m",
96
97
  webChatBridgeEnabled: true,
97
98
  instructionsSkillsEnabled: true,
@@ -140,6 +141,7 @@ function resolveSettings(value) {
140
141
  browserAgentBrowser: resolveBrowserAgentBrowser(value?.browserAgentBrowser),
141
142
  browserAgentDebugTools: value?.browserAgentDebugTools === true,
142
143
  browserAgentDemonstrate: value?.browserAgentDemonstrate === true,
144
+ browserAgentAutoHeal: value?.browserAgentAutoHeal === true,
143
145
  browserAgentIdleClose: resolveBrowserAgentIdleClose(value?.browserAgentIdleClose),
144
146
  webChatBridgeEnabled: value?.webChatBridgeEnabled ?? true,
145
147
  instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
@@ -1132,6 +1134,31 @@ function sanitizeDemoSteps(steps) {
1132
1134
  return { ...step, value: "***", masked: true };
1133
1135
  });
1134
1136
  }
1137
+ function describeDemoStepHuman(step, variables = []) {
1138
+ const withLabels = (text3) => text3.replace(
1139
+ /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu,
1140
+ (match, name2) => {
1141
+ const variable = variables.find((item) => item.name === name2);
1142
+ return variable === void 0 ? match : `\u300C${variable.label}\u300D`;
1143
+ }
1144
+ );
1145
+ const short = (text3) => text3.length > 60 ? `${text3.slice(0, 60)}\u2026` : text3;
1146
+ switch (step.kind) {
1147
+ case "navigate":
1148
+ return `\u6253\u5F00 ${short(step.url)}`;
1149
+ case "click":
1150
+ return `\u70B9\u51FB\u300C${step.name}\u300D`;
1151
+ case "fill":
1152
+ if (step.masked) return `\u5728\u300C${step.name}\u300D\u586B\u5BC6\u7801\uFF08\u6BCF\u6B21\u95EE\u4F60\uFF09`;
1153
+ return `\u5728\u300C${step.name}\u300D\u586B ${short(withLabels(step.value))}`;
1154
+ case "press":
1155
+ return `\u6309 ${step.key}`;
1156
+ default: {
1157
+ const exhaustive = step;
1158
+ return JSON.stringify(exhaustive);
1159
+ }
1160
+ }
1161
+ }
1135
1162
  function describeDemoStep(step) {
1136
1163
  switch (step.kind) {
1137
1164
  case "navigate":
@@ -2010,6 +2037,56 @@ var PlaywrightDriver = class {
2010
2037
  const ref = Number(raw);
2011
2038
  return Number.isFinite(ref) ? ref : null;
2012
2039
  }
2040
+ /**
2041
+ * Role, accessible name and a readable CSS path for a ref, so a repair can
2042
+ * record how the control was found this time. Best-effort: a stale ref or a
2043
+ * detached node yields an empty selector rather than failing the tool call.
2044
+ */
2045
+ async refInfo(ref) {
2046
+ const page = this.page;
2047
+ if (page === null || page.isClosed()) return null;
2048
+ const record2 = this.tabs.ref(this.tabIdFor(page), ref);
2049
+ if (record2 === void 0) return null;
2050
+ const selector = await page.evaluate(({ wanted, attr }) => {
2051
+ const element = document.querySelector(`[${attr}="${wanted}"]`);
2052
+ if (element === null) return "";
2053
+ const escaped = (value) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : value.replace(/[^a-zA-Z0-9_-]/gu, "\\$&");
2054
+ const quote = (value) => `"${value.replace(/"/gu, '\\"')}"`;
2055
+ if (element.id !== "") return `#${escaped(element.id)}`;
2056
+ const parts = [];
2057
+ let cursor = element;
2058
+ for (let depth = 0; depth < 6 && cursor !== null; depth += 1) {
2059
+ const node = cursor;
2060
+ const tag = node.tagName.toLowerCase();
2061
+ const testId = node.getAttribute("data-testid");
2062
+ if (testId !== null && testId !== "") {
2063
+ parts.unshift(`${tag}[data-testid=${quote(testId)}]`);
2064
+ break;
2065
+ }
2066
+ const name2 = node.getAttribute("name");
2067
+ if (name2 !== null && name2 !== "" && /^(input|select|textarea|button|form)$/u.test(tag)) {
2068
+ parts.unshift(`${tag}[name=${quote(name2)}]`);
2069
+ break;
2070
+ }
2071
+ let part = tag;
2072
+ const parent = node.parentElement;
2073
+ if (parent !== null) {
2074
+ const sameTag = Array.from(parent.children).filter((child) => child.tagName === node.tagName);
2075
+ if (sameTag.length > 1) part += `:nth-of-type(${sameTag.indexOf(node) + 1})`;
2076
+ }
2077
+ parts.unshift(part);
2078
+ if (node === document.body) break;
2079
+ cursor = parent;
2080
+ }
2081
+ return parts.join(" > ").slice(0, 240);
2082
+ }, { wanted: String(ref), attr: PLAYWRIGHT_REF_ATTR }).catch(() => "");
2083
+ return {
2084
+ role: record2.role,
2085
+ name: record2.name,
2086
+ selector,
2087
+ href: record2.href
2088
+ };
2089
+ }
2013
2090
  async press(key) {
2014
2091
  const page = await this.requirePage();
2015
2092
  await page.keyboard.press(key);
@@ -2740,6 +2817,146 @@ function classify(input) {
2740
2817
  };
2741
2818
  }
2742
2819
 
2820
+ // src/host/browser-agent/demo-values.ts
2821
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
2822
+ var LOOSE_DATE = /^(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})日?$/;
2823
+ var EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2824
+ var SEARCH_FIELD = /搜索|查找|关键词|关键字|查询|search|query|filter|keyword|^q$/iu;
2825
+ var pad = (value) => String(value).padStart(2, "0");
2826
+ function isoDate(date) {
2827
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
2828
+ }
2829
+ function startOfDay(date) {
2830
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate());
2831
+ }
2832
+ function addDays(date, days) {
2833
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
2834
+ }
2835
+ function weekStart(date) {
2836
+ const offset = (date.getDay() + 6) % 7;
2837
+ return addDays(date, -offset);
2838
+ }
2839
+ function monthStart(date, offsetMonths) {
2840
+ return new Date(date.getFullYear(), date.getMonth() + offsetMonths, 1);
2841
+ }
2842
+ function quarterStart(date, offsetQuarters) {
2843
+ const quarter = Math.floor(date.getMonth() / 3) + offsetQuarters;
2844
+ return new Date(date.getFullYear(), quarter * 3, 1);
2845
+ }
2846
+ var WEEKDAY = {
2847
+ \u4E00: 0,
2848
+ \u4E8C: 1,
2849
+ \u4E09: 2,
2850
+ \u56DB: 3,
2851
+ \u4E94: 4,
2852
+ \u516D: 5,
2853
+ \u65E5: 6,
2854
+ \u5929: 6
2855
+ };
2856
+ var EXACT = {
2857
+ \u4ECA\u5929: (now) => now,
2858
+ \u4ECA\u65E5: (now) => now,
2859
+ today: (now) => now,
2860
+ \u6628\u5929: (now) => addDays(now, -1),
2861
+ \u6628\u65E5: (now) => addDays(now, -1),
2862
+ yesterday: (now) => addDays(now, -1),
2863
+ \u524D\u5929: (now) => addDays(now, -2),
2864
+ \u660E\u5929: (now) => addDays(now, 1),
2865
+ tomorrow: (now) => addDays(now, 1),
2866
+ \u540E\u5929: (now) => addDays(now, 2),
2867
+ \u672C\u5468: (now) => weekStart(now),
2868
+ \u8FD9\u5468: (now) => weekStart(now),
2869
+ \u672C\u661F\u671F: (now) => weekStart(now),
2870
+ thisweek: (now) => weekStart(now),
2871
+ \u4E0A\u5468: (now) => addDays(weekStart(now), -7),
2872
+ lastweek: (now) => addDays(weekStart(now), -7),
2873
+ \u4E0B\u5468: (now) => addDays(weekStart(now), 7),
2874
+ nextweek: (now) => addDays(weekStart(now), 7),
2875
+ \u672C\u6708: (now) => monthStart(now, 0),
2876
+ \u8FD9\u4E2A\u6708: (now) => monthStart(now, 0),
2877
+ thismonth: (now) => monthStart(now, 0),
2878
+ \u4E0A\u6708: (now) => monthStart(now, -1),
2879
+ \u4E0A\u4E2A\u6708: (now) => monthStart(now, -1),
2880
+ lastmonth: (now) => monthStart(now, -1),
2881
+ \u4E0B\u6708: (now) => monthStart(now, 1),
2882
+ \u4E0B\u4E2A\u6708: (now) => monthStart(now, 1),
2883
+ nextmonth: (now) => monthStart(now, 1),
2884
+ \u672C\u5B63\u5EA6: (now) => quarterStart(now, 0),
2885
+ \u8FD9\u5B63\u5EA6: (now) => quarterStart(now, 0),
2886
+ thisquarter: (now) => quarterStart(now, 0),
2887
+ \u4E0A\u5B63\u5EA6: (now) => quarterStart(now, -1),
2888
+ lastquarter: (now) => quarterStart(now, -1),
2889
+ \u4E0B\u5B63\u5EA6: (now) => quarterStart(now, 1),
2890
+ nextquarter: (now) => quarterStart(now, 1),
2891
+ \u4ECA\u5E74: (now) => new Date(now.getFullYear(), 0, 1),
2892
+ \u672C\u5E74: (now) => new Date(now.getFullYear(), 0, 1),
2893
+ thisyear: (now) => new Date(now.getFullYear(), 0, 1),
2894
+ \u53BB\u5E74: (now) => new Date(now.getFullYear() - 1, 0, 1),
2895
+ lastyear: (now) => new Date(now.getFullYear() - 1, 0, 1),
2896
+ \u660E\u5E74: (now) => new Date(now.getFullYear() + 1, 0, 1),
2897
+ nextyear: (now) => new Date(now.getFullYear() + 1, 0, 1)
2898
+ };
2899
+ var WEEKDAY_PHRASE = /^(上|下|本|这)?(?:周|星期|礼拜)([一二三四五六日天])$/u;
2900
+ function resolveDatePhrase(raw, now = /* @__PURE__ */ new Date()) {
2901
+ const text3 = raw.trim();
2902
+ if (text3 === "") return null;
2903
+ const day = startOfDay(now);
2904
+ const exact = EXACT[text3.toLowerCase()];
2905
+ if (exact !== void 0) return { iso: isoDate(exact(day)), phrase: text3 };
2906
+ const weekday = WEEKDAY_PHRASE.exec(text3);
2907
+ if (weekday !== null) {
2908
+ const scope = weekday[1];
2909
+ const index = WEEKDAY[weekday[2]];
2910
+ if (index === void 0) return null;
2911
+ const base = scope === "\u4E0A" ? addDays(weekStart(day), -7) : scope === "\u4E0B" ? addDays(weekStart(day), 7) : weekStart(day);
2912
+ return { iso: isoDate(addDays(base, index)), phrase: text3 };
2913
+ }
2914
+ const loose = LOOSE_DATE.exec(text3);
2915
+ if (loose !== null) {
2916
+ const month = Number(loose[2]);
2917
+ const date = Number(loose[3]);
2918
+ if (month < 1 || month > 12 || date < 1 || date > 31) return null;
2919
+ return { iso: `${loose[1]}-${pad(month)}-${pad(date)}`, phrase: text3 };
2920
+ }
2921
+ return null;
2922
+ }
2923
+ function looksLikeDateValue(value) {
2924
+ const text3 = value.trim();
2925
+ return ISO_DATE.test(text3) || LOOSE_DATE.test(text3);
2926
+ }
2927
+ function resolveVariableValue(value, dateVariable, now = /* @__PURE__ */ new Date()) {
2928
+ if (!dateVariable) return { value };
2929
+ const parsed = resolveDatePhrase(value, now);
2930
+ return parsed === null ? { value } : { value: parsed.iso, resolvedFrom: parsed.phrase };
2931
+ }
2932
+ function isDateVariable(variable) {
2933
+ if (variable.default !== void 0 && looksLikeDateValue(variable.default)) return true;
2934
+ const text3 = `${variable.label ?? ""} ${variable.name}`;
2935
+ return /日期|时间|开始|结束|截止|起止|date|from|to|start|end|until|since/iu.test(text3);
2936
+ }
2937
+ function suggestRecipeVariables(steps) {
2938
+ const seen = /* @__PURE__ */ new Set();
2939
+ const suggestions = [];
2940
+ steps.forEach((step, index) => {
2941
+ if (suggestions.length >= 3) return;
2942
+ if (step.kind !== "fill" || step.masked) return;
2943
+ const value = step.value.trim();
2944
+ if (value === "") return;
2945
+ if (/\$\{[A-Za-z_][A-Za-z0-9_]*\}/u.test(value)) return;
2946
+ const label = step.name.trim();
2947
+ let kind = null;
2948
+ if (looksLikeDateValue(value) || resolveDatePhrase(value) !== null) kind = "date";
2949
+ else if (EMAIL.test(value)) kind = "email";
2950
+ else if (SEARCH_FIELD.test(label) && value.length <= 40) kind = "search";
2951
+ if (kind === null) return;
2952
+ const key = `${label}\0${value}`;
2953
+ if (seen.has(key)) return;
2954
+ seen.add(key);
2955
+ suggestions.push({ index, label: label === "" ? kind : label, value: value.slice(0, 60) });
2956
+ });
2957
+ return suggestions;
2958
+ }
2959
+
2743
2960
  // src/host/browser-agent/demo-replay.ts
2744
2961
  function normalizeControlName(raw) {
2745
2962
  return raw.replace(/[\u200b-\u200d\ufeff]/gu, "").replace(/\s+/gu, " ").trim().toLowerCase();
@@ -2945,10 +3162,257 @@ async function replayDemoSteps(driver, steps, options = {}) {
2945
3162
  // src/host/browser-agent/demo-recipes.ts
2946
3163
  import { mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "node:fs";
2947
3164
  import { dirname } from "node:path";
3165
+
3166
+ // src/host/browser-agent/demo-heal.ts
3167
+ var REPAIR_WINDOW_MS = 10 * 6e4;
3168
+ var MAX_OBSERVED = 30;
3169
+ var MAX_INSERTED = 8;
3170
+ function stepFromObservation(action) {
3171
+ switch (action.kind) {
3172
+ case "navigate":
3173
+ return action.url === void 0 || action.url === "" ? null : { kind: "navigate", at: action.at, url: action.url };
3174
+ case "click":
3175
+ return action.name === void 0 || action.name === "" ? null : {
3176
+ kind: "click",
3177
+ at: action.at,
3178
+ role: action.role ?? "button",
3179
+ name: action.name,
3180
+ selector: action.selector ?? ""
3181
+ };
3182
+ case "fill":
3183
+ return action.name === void 0 || action.name === "" || (action.value ?? "") === "" ? null : {
3184
+ kind: "fill",
3185
+ at: action.at,
3186
+ role: action.role ?? "textbox",
3187
+ name: action.name,
3188
+ selector: action.selector ?? "",
3189
+ field: action.field ?? action.name,
3190
+ value: action.value ?? "",
3191
+ masked: false
3192
+ };
3193
+ case "press":
3194
+ return action.key === void 0 || action.key === "" ? null : { kind: "press", at: action.at, key: action.key, selector: action.selector ?? "" };
3195
+ default: {
3196
+ const exhaustive = action.kind;
3197
+ return exhaustive;
3198
+ }
3199
+ }
3200
+ }
3201
+ function retarget(step, action) {
3202
+ if (step.kind !== action.kind) return null;
3203
+ const site = {
3204
+ ...step.tabId === void 0 ? {} : { tabId: step.tabId },
3205
+ ...step.tabUrl === void 0 ? {} : { tabUrl: step.tabUrl }
3206
+ };
3207
+ switch (step.kind) {
3208
+ case "navigate":
3209
+ return { ...step, url: action.url ?? step.url };
3210
+ case "click":
3211
+ return {
3212
+ kind: "click",
3213
+ at: step.at,
3214
+ role: action.role ?? step.role,
3215
+ name: action.name ?? step.name,
3216
+ selector: action.selector ?? step.selector,
3217
+ ...site
3218
+ };
3219
+ case "fill":
3220
+ return {
3221
+ kind: "fill",
3222
+ at: step.at,
3223
+ role: action.role ?? step.role,
3224
+ name: action.name ?? step.name,
3225
+ selector: action.selector ?? step.selector,
3226
+ field: action.field ?? step.field,
3227
+ value: step.value,
3228
+ masked: step.masked,
3229
+ ...step.checked === void 0 ? {} : { checked: step.checked },
3230
+ ...site
3231
+ };
3232
+ case "press":
3233
+ return {
3234
+ kind: "press",
3235
+ at: step.at,
3236
+ key: step.key,
3237
+ selector: action.selector ?? step.selector,
3238
+ ...site
3239
+ };
3240
+ default: {
3241
+ const exhaustive = step;
3242
+ return exhaustive;
3243
+ }
3244
+ }
3245
+ }
3246
+ function pickObserved(step, observed) {
3247
+ const compatible = [];
3248
+ observed.forEach((action, index) => {
3249
+ if (action.kind !== step.kind) return;
3250
+ if (step.kind !== "navigate" && (action.name ?? "") === "") return;
3251
+ if (step.kind === "fill" && (action.value ?? "") === "") return;
3252
+ compatible.push({ action, index });
3253
+ });
3254
+ if (compatible.length === 0) return -1;
3255
+ if (step.kind === "navigate") return compatible[0].index;
3256
+ const wanted = step.kind === "press" ? "" : normalizeControlName(step.name);
3257
+ if (wanted !== "") {
3258
+ const similar = compatible.find(({ action }) => {
3259
+ const candidate = normalizeControlName(action.name ?? "");
3260
+ if (candidate === "") return false;
3261
+ if (candidate.length < 2 || wanted.length < 2) return candidate === wanted;
3262
+ return candidate.includes(wanted) || wanted.includes(candidate);
3263
+ });
3264
+ if (similar !== void 0) return similar.index;
3265
+ }
3266
+ return compatible[0].index;
3267
+ }
3268
+ function buildHealProposal(input) {
3269
+ const step = input.steps[input.failedIndex];
3270
+ if (step === void 0) return null;
3271
+ if (step.kind === "fill" && step.masked) return null;
3272
+ const matchAt = pickObserved(step, input.observed);
3273
+ if (matchAt < 0) return null;
3274
+ const action = input.observed[matchAt];
3275
+ const replacement = retarget(step, action);
3276
+ if (replacement === null) return null;
3277
+ const unchanged = step.kind === "navigate" ? replacement.kind === "navigate" && step.url === replacement.url : step.kind === "press" ? replacement.kind === "press" && step.selector === replacement.selector : "name" in replacement && "name" in step && normalizeControlName(step.name) === normalizeControlName(replacement.name) && step.role === replacement.role;
3278
+ if (unchanged) return null;
3279
+ const inserted = [];
3280
+ for (const entry of input.observed.slice(0, matchAt)) {
3281
+ if (inserted.length >= MAX_INSERTED) break;
3282
+ const built = stepFromObservation(entry);
3283
+ if (built !== null) inserted.push(built);
3284
+ }
3285
+ const sanitizedInserted = sanitizeDemoSteps(inserted);
3286
+ if (sanitizedInserted.some((entry) => entry.kind === "fill" && entry.masked)) return null;
3287
+ const sanitizedReplacement = sanitizeDemoSteps([replacement])[0] ?? replacement;
3288
+ if (sanitizedReplacement.kind === "fill" && sanitizedReplacement.masked) return null;
3289
+ return {
3290
+ id: input.id ?? `h-${input.now.toString(36)}`,
3291
+ at: input.now,
3292
+ failedAt: input.failedIndex + 1,
3293
+ reason: input.reason.slice(0, 500),
3294
+ inserted: sanitizedInserted,
3295
+ replacement: sanitizedReplacement
3296
+ };
3297
+ }
3298
+ function sameIdentity(a, b) {
3299
+ if (a.kind !== b.kind) return false;
3300
+ if (a.kind === "navigate" && b.kind === "navigate") return a.url === b.url;
3301
+ if (a.kind === "press" && b.kind === "press") return a.key === b.key;
3302
+ if ("name" in a && "name" in b) {
3303
+ return normalizeControlName(a.name) === normalizeControlName(b.name) && a.role === b.role;
3304
+ }
3305
+ return false;
3306
+ }
3307
+ function applyHealProposal(steps, proposal) {
3308
+ const at = proposal.failedAt - 1;
3309
+ if (at < 0 || at >= steps.length) return [...steps];
3310
+ return [
3311
+ ...steps.slice(0, at),
3312
+ ...proposal.inserted,
3313
+ proposal.replacement,
3314
+ ...steps.slice(at + 1)
3315
+ ];
3316
+ }
3317
+ function describeHealProposal(proposal) {
3318
+ const lines = [
3319
+ `step ${proposal.failedAt} now uses ${describeDemoStep(proposal.replacement)}`
3320
+ ];
3321
+ if (proposal.inserted.length > 0) {
3322
+ lines.push(`+${proposal.inserted.length} step(s) before it: ${proposal.inserted.map(describeDemoStep).join("; ")}`);
3323
+ }
3324
+ return lines;
3325
+ }
3326
+ var AUTO_HEAL_BUDGET = 3;
3327
+ var AUTO_HEAL_WINDOW_MS = 24 * 60 * 6e4;
3328
+ function sameOrigin(a, b) {
3329
+ if (a === void 0 || b === void 0) return false;
3330
+ try {
3331
+ return new URL(a).origin === new URL(b).origin;
3332
+ } catch {
3333
+ return false;
3334
+ }
3335
+ }
3336
+ function createRepairHooks(input) {
3337
+ const clock = input.now ?? Date.now;
3338
+ return {
3339
+ active: () => input.tracker.active,
3340
+ begin: (target) => {
3341
+ input.tracker.begin(target);
3342
+ },
3343
+ observe: (action) => {
3344
+ input.tracker.observe(action);
3345
+ },
3346
+ commit: () => {
3347
+ const pending = input.tracker.take();
3348
+ if (pending === null || input.store === void 0) return null;
3349
+ const recipe = input.store.get(pending.target.recipeId);
3350
+ if (recipe === void 0) return null;
3351
+ const current = recipe.steps[pending.target.index];
3352
+ if (current === void 0 || !sameIdentity(current, pending.target.step)) return null;
3353
+ const now = clock();
3354
+ const proposal = buildHealProposal({
3355
+ steps: recipe.steps,
3356
+ failedIndex: pending.target.index,
3357
+ reason: pending.target.reason,
3358
+ observed: pending.observed,
3359
+ now
3360
+ });
3361
+ if (proposal === null) return null;
3362
+ if (!input.store.recordHeal({ id: recipe.id, proposal }).ok) return null;
3363
+ let autoApplied = false;
3364
+ if (input.autoApply?.() === true) {
3365
+ const recorded = recipe.steps.find((step) => step.tabUrl !== void 0)?.tabUrl;
3366
+ const recent = recipe.autoHeals.filter((at) => now - at < AUTO_HEAL_WINDOW_MS);
3367
+ if (sameOrigin(recorded, pending.target.tabUrl) && recent.length < AUTO_HEAL_BUDGET) {
3368
+ autoApplied = input.store.resolveHeal({ id: recipe.id, accept: true, auto: true, now }).ok;
3369
+ }
3370
+ }
3371
+ return {
3372
+ recipeId: recipe.id,
3373
+ recipeName: recipe.name,
3374
+ failedAt: proposal.failedAt,
3375
+ lines: describeHealProposal(proposal),
3376
+ autoApplied
3377
+ };
3378
+ }
3379
+ };
3380
+ }
3381
+ var DemoRepairTracker = class {
3382
+ pending = null;
3383
+ begin(target) {
3384
+ this.pending = {
3385
+ target: { ...target, at: target.at ?? Date.now() },
3386
+ observed: []
3387
+ };
3388
+ }
3389
+ observe(action) {
3390
+ const pending = this.pending;
3391
+ if (pending === null) return;
3392
+ if (action.at - pending.target.at > REPAIR_WINDOW_MS) return;
3393
+ if (pending.target.tabId !== void 0 && action.tabId !== void 0 && pending.target.tabId !== action.tabId) return;
3394
+ if (pending.observed.length >= MAX_OBSERVED) return;
3395
+ pending.observed.push(action);
3396
+ }
3397
+ /** Hand back the target and what happened, and stop tracking. */
3398
+ take() {
3399
+ const pending = this.pending;
3400
+ this.pending = null;
3401
+ return pending === null ? null : { target: pending.target, observed: [...pending.observed] };
3402
+ }
3403
+ get active() {
3404
+ return this.pending !== null;
3405
+ }
3406
+ };
3407
+
3408
+ // src/host/browser-agent/demo-recipes.ts
2948
3409
  var MAX_RECIPES = 20;
2949
3410
  var MAX_RECIPE_NAME = 60;
2950
3411
  var MAX_RECIPE_STEPS = 200;
2951
- var FILE_VERSION = 1;
3412
+ var MAX_HISTORY = 5;
3413
+ var MAX_VARIABLE_LABEL = 60;
3414
+ var MAX_AUTO_HEALS = 3;
3415
+ var FILE_VERSION = 2;
2952
3416
  function metaOf(recipe) {
2953
3417
  return {
2954
3418
  id: recipe.id,
@@ -2956,9 +3420,19 @@ function metaOf(recipe) {
2956
3420
  createdAt: recipe.createdAt,
2957
3421
  updatedAt: recipe.updatedAt,
2958
3422
  steps: recipe.steps.length,
2959
- variables: recipe.variables
3423
+ variables: recipe.variables,
3424
+ rev: recipe.rev,
3425
+ history: recipe.history.length,
3426
+ autoHeals: recipe.autoHeals.length,
3427
+ ...recipe.pendingHeal === void 0 ? {} : { pendingHeal: recipe.pendingHeal }
2960
3428
  };
2961
3429
  }
3430
+ function nextVersion(recipe, source, now) {
3431
+ return [
3432
+ ...recipe.history,
3433
+ { rev: recipe.rev, at: now, source, steps: recipe.steps, variables: recipe.variables }
3434
+ ].slice(-MAX_HISTORY);
3435
+ }
2962
3436
  var VAR_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
2963
3437
  var VAR_TOKEN = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
2964
3438
  function applyRecipeVars(steps, values) {
@@ -2975,8 +3449,41 @@ function applyRecipeVars(steps, values) {
2975
3449
  return step;
2976
3450
  });
2977
3451
  }
2978
- function missingRecipeVars(recipe, values) {
2979
- return recipe.variables.filter((variable) => (values[variable.name] ?? "").trim() === "").map((variable) => variable.name);
3452
+ function matchRecipeVarValues(recipe, provided) {
3453
+ const byKey = /* @__PURE__ */ new Map();
3454
+ for (const variable of recipe.variables) {
3455
+ byKey.set(variable.name.trim().toLowerCase(), variable);
3456
+ byKey.set(variable.label.trim().toLowerCase(), variable);
3457
+ }
3458
+ const values = {};
3459
+ const unknown = [];
3460
+ for (const [key, raw] of Object.entries(provided)) {
3461
+ const variable = byKey.get(key.trim().toLowerCase());
3462
+ if (variable === void 0) {
3463
+ unknown.push(key);
3464
+ continue;
3465
+ }
3466
+ values[variable.name] = raw;
3467
+ }
3468
+ return { values, unknown };
3469
+ }
3470
+ function prepareRecipeValues(recipe, provided, now = /* @__PURE__ */ new Date()) {
3471
+ const matched = matchRecipeVarValues(recipe, provided);
3472
+ const values = {};
3473
+ for (const variable of recipe.variables) values[variable.name] = variable.default;
3474
+ Object.assign(values, matched.values);
3475
+ const resolved = [];
3476
+ for (const variable of recipe.variables) {
3477
+ const raw = values[variable.name] ?? "";
3478
+ if (raw.trim() === "") continue;
3479
+ if (!isDateVariable(variable)) continue;
3480
+ const result = resolveVariableValue(raw, true, now);
3481
+ if (result.resolvedFrom === void 0) continue;
3482
+ values[variable.name] = result.value;
3483
+ resolved.push({ label: variable.label, from: result.resolvedFrom, to: result.value });
3484
+ }
3485
+ const missing = recipe.variables.filter((variable) => (values[variable.name] ?? "").trim() === "");
3486
+ return { values, missing, resolved, unknown: matched.unknown };
2980
3487
  }
2981
3488
  function sanitizeVariables(raw) {
2982
3489
  if (!Array.isArray(raw)) return [];
@@ -2984,7 +3491,58 @@ function sanitizeVariables(raw) {
2984
3491
  if (value === null || typeof value !== "object") return false;
2985
3492
  const name2 = value.name;
2986
3493
  return typeof name2 === "string" && VAR_NAME.test(name2);
2987
- }).map((variable) => ({ name: variable.name, default: String(variable.default ?? "").slice(0, 500) }));
3494
+ }).map((variable) => ({
3495
+ name: variable.name,
3496
+ // Files written before labels existed fall back to the id.
3497
+ label: typeof variable.label === "string" && variable.label.trim() !== "" ? variable.label.trim().slice(0, MAX_VARIABLE_LABEL) : variable.name,
3498
+ default: String(variable.default ?? "").slice(0, 500)
3499
+ }));
3500
+ }
3501
+ function sanitizeHistory(raw) {
3502
+ if (!Array.isArray(raw)) return [];
3503
+ const versions = [];
3504
+ for (const value of raw) {
3505
+ if (value === null || typeof value !== "object") continue;
3506
+ const entry = value;
3507
+ const steps = sanitizeRecipeSteps(entry.steps);
3508
+ if (steps.length === 0) continue;
3509
+ versions.push({
3510
+ rev: Number.isFinite(entry.rev) && (entry.rev ?? 0) > 0 ? Number(entry.rev) : 1,
3511
+ at: Number.isFinite(entry.at) ? Number(entry.at) : 0,
3512
+ source: entry.source === "parameterize" || entry.source === "heal" || entry.source === "rollback" ? entry.source : "save",
3513
+ steps,
3514
+ variables: sanitizeVariables(entry.variables)
3515
+ });
3516
+ }
3517
+ return versions.slice(-MAX_HISTORY);
3518
+ }
3519
+ function sanitizeTimestamps(raw) {
3520
+ if (!Array.isArray(raw)) return [];
3521
+ return raw.filter((value) => typeof value === "number" && Number.isFinite(value) && value > 0).slice(-MAX_AUTO_HEALS * 4);
3522
+ }
3523
+ function sanitizeProposal(raw) {
3524
+ if (raw === null || typeof raw !== "object") return void 0;
3525
+ const entry = raw;
3526
+ if (typeof entry.id !== "string" || entry.id === "") return void 0;
3527
+ const failedAt = Number(entry.failedAt);
3528
+ if (!Number.isInteger(failedAt) || failedAt < 1) return void 0;
3529
+ const replacement = sanitizeRecipeSteps(entry.replacement === void 0 ? [] : [entry.replacement])[0];
3530
+ if (replacement === void 0) return void 0;
3531
+ return {
3532
+ id: entry.id,
3533
+ at: Number.isFinite(entry.at) ? Number(entry.at) : 0,
3534
+ failedAt,
3535
+ reason: typeof entry.reason === "string" ? entry.reason.slice(0, 500) : "",
3536
+ inserted: sanitizeRecipeSteps(entry.inserted ?? []),
3537
+ replacement
3538
+ };
3539
+ }
3540
+ function nextVariableName(variables) {
3541
+ for (let index = 1; index <= 99; index += 1) {
3542
+ const candidate = `v${index}`;
3543
+ if (!variables.some((variable) => variable.name === candidate)) return candidate;
3544
+ }
3545
+ return `v${Date.now().toString(36)}`;
2988
3546
  }
2989
3547
  function isStep(value) {
2990
3548
  if (value === null || typeof value !== "object") return false;
@@ -3023,7 +3581,15 @@ var DemoRecipeStore = class {
3023
3581
  const existing = recipes.find((recipe) => recipe.name.toLowerCase() === name2.toLowerCase());
3024
3582
  let saved;
3025
3583
  if (existing !== void 0) {
3026
- saved = { ...existing, name: name2, steps, updatedAt: now };
3584
+ const { pendingHeal: _answered, ...rest } = existing;
3585
+ saved = {
3586
+ ...rest,
3587
+ name: name2,
3588
+ steps,
3589
+ updatedAt: now,
3590
+ rev: existing.rev + 1,
3591
+ history: nextVersion(existing, "save", now)
3592
+ };
3027
3593
  } else {
3028
3594
  if (recipes.length >= MAX_RECIPES) {
3029
3595
  return { ok: false, error: `\u6700\u591A\u4FDD\u5B58 ${MAX_RECIPES} \u4E2A\u6D41\u7A0B\uFF0C\u5148\u5220\u6389\u4E00\u4E2A` };
@@ -3034,7 +3600,10 @@ var DemoRecipeStore = class {
3034
3600
  createdAt: now,
3035
3601
  updatedAt: now,
3036
3602
  steps,
3037
- variables: []
3603
+ variables: [],
3604
+ rev: 1,
3605
+ history: [],
3606
+ autoHeals: []
3038
3607
  };
3039
3608
  }
3040
3609
  const next = existing === void 0 ? [...recipes, saved] : recipes.map((recipe) => recipe.id === saved.id ? saved : recipe);
@@ -3067,10 +3636,6 @@ var DemoRecipeStore = class {
3067
3636
  * value as the default so the flow still runs unchanged.
3068
3637
  */
3069
3638
  parameterize(input) {
3070
- const name2 = input.name.trim();
3071
- if (!VAR_NAME.test(name2)) {
3072
- return { ok: false, error: "\u53D8\u91CF\u540D\u53EA\u80FD\u7528\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u6570\u5B57\u5F00\u5934" };
3073
- }
3074
3639
  const recipes = this.read();
3075
3640
  const current = recipes.find((recipe) => recipe.id === input.id);
3076
3641
  if (current === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728" };
@@ -3081,37 +3646,123 @@ var DemoRecipeStore = class {
3081
3646
  if (new RegExp(VAR_TOKEN.source).test(step.value)) {
3082
3647
  return { ok: false, error: "\u8FD9\u4E00\u6B65\u5DF2\u7ECF\u662F\u53D8\u91CF\u4E86" };
3083
3648
  }
3084
- if (current.variables.some((variable) => variable.name === name2)) {
3649
+ const explicitName = (input.name ?? "").trim();
3650
+ if (explicitName !== "" && !VAR_NAME.test(explicitName)) {
3651
+ return { ok: false, error: "\u53D8\u91CF\u540D\u53EA\u80FD\u7528\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u6570\u5B57\u5F00\u5934" };
3652
+ }
3653
+ if (explicitName !== "" && current.variables.some((variable) => variable.name === explicitName)) {
3085
3654
  return { ok: false, error: "\u53D8\u91CF\u540D\u5DF2\u5B58\u5728" };
3086
3655
  }
3656
+ const name2 = explicitName !== "" ? explicitName : nextVariableName(current.variables);
3657
+ const label = (input.label ?? step.name ?? "").trim().slice(0, MAX_VARIABLE_LABEL) || `\u53D8\u91CF ${current.variables.length + 1}`;
3087
3658
  const token = "${" + name2 + "}";
3088
3659
  const steps = current.steps.map(
3089
3660
  (entry, index) => index === input.index && entry.kind === "fill" ? { ...entry, value: token } : entry
3090
3661
  );
3091
- const variables = [...current.variables, { name: name2, default: step.value.slice(0, 500) }];
3092
- const next = { ...current, steps, variables, updatedAt: input.now ?? Date.now() };
3662
+ const variables = [...current.variables, { name: name2, label, default: step.value.slice(0, 500) }];
3663
+ const now = input.now ?? Date.now();
3664
+ const { pendingHeal: _stale, ...rest } = current;
3665
+ const next = {
3666
+ ...rest,
3667
+ steps,
3668
+ variables,
3669
+ updatedAt: now,
3670
+ rev: current.rev + 1,
3671
+ history: nextVersion(current, "parameterize", now)
3672
+ };
3673
+ this.write(recipes.map((recipe) => recipe.id === current.id ? next : recipe));
3674
+ return { ok: true, recipe: metaOf(next) };
3675
+ }
3676
+ /** Store a repair for the user to accept; it never touches the steps by itself. */
3677
+ recordHeal(input) {
3678
+ const recipes = this.read();
3679
+ const current = recipes.find((recipe) => recipe.id === input.id);
3680
+ if (current === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728" };
3681
+ const next = { ...current, pendingHeal: input.proposal };
3682
+ this.write(recipes.map((recipe) => recipe.id === current.id ? next : recipe));
3683
+ return { ok: true, recipe: metaOf(next) };
3684
+ }
3685
+ /**
3686
+ * Accept or drop a pending repair. Accepting is the only path that rewrites
3687
+ * the flow, and it keeps the previous content one click away.
3688
+ */
3689
+ resolveHeal(input) {
3690
+ const now = input.now ?? Date.now();
3691
+ const recipes = this.read();
3692
+ const current = recipes.find((recipe) => recipe.id === input.id);
3693
+ if (current === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728" };
3694
+ const proposal = current.pendingHeal;
3695
+ if (proposal === void 0) return { ok: false, error: "\u8FD9\u4E2A\u6D41\u7A0B\u6CA1\u6709\u5F85\u786E\u8BA4\u7684\u4FEE\u590D" };
3696
+ const { pendingHeal: _resolved, ...rest } = current;
3697
+ if (!input.accept) {
3698
+ this.write(recipes.map((recipe) => recipe.id === current.id ? rest : recipe));
3699
+ return { ok: true, recipe: metaOf(rest) };
3700
+ }
3701
+ const steps = sanitizeRecipeSteps(applyHealProposal(current.steps, proposal));
3702
+ const next = {
3703
+ ...rest,
3704
+ steps,
3705
+ updatedAt: now,
3706
+ rev: current.rev + 1,
3707
+ history: nextVersion(current, "heal", now),
3708
+ autoHeals: input.auto === true ? [...current.autoHeals, now].slice(-MAX_AUTO_HEALS) : current.autoHeals
3709
+ };
3710
+ this.write(recipes.map((recipe) => recipe.id === current.id ? next : recipe));
3711
+ return { ok: true, recipe: metaOf(next) };
3712
+ }
3713
+ /** Restore the newest past version; the safety net for a wrong repair. */
3714
+ rollback(input) {
3715
+ const now = input.now ?? Date.now();
3716
+ const recipes = this.read();
3717
+ const current = recipes.find((recipe) => recipe.id === input.id);
3718
+ if (current === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728" };
3719
+ const previous = current.history[current.history.length - 1];
3720
+ if (previous === void 0) return { ok: false, error: "\u6CA1\u6709\u53EF\u64A4\u9500\u7684\u7248\u672C" };
3721
+ const { pendingHeal: _stale, ...rest } = current;
3722
+ const next = {
3723
+ ...rest,
3724
+ steps: previous.steps,
3725
+ variables: previous.variables,
3726
+ updatedAt: now,
3727
+ rev: current.rev + 1,
3728
+ history: current.history.slice(0, -1)
3729
+ };
3093
3730
  this.write(recipes.map((recipe) => recipe.id === current.id ? next : recipe));
3094
3731
  return { ok: true, recipe: metaOf(next) };
3095
3732
  }
3733
+ revisionTick = 0;
3734
+ /** Bumped on every write; the sidebar polls this instead of the whole list. */
3735
+ revision() {
3736
+ return this.revisionTick;
3737
+ }
3096
3738
  read() {
3097
3739
  if (this.filePath === null) return this.memory;
3098
3740
  try {
3099
3741
  const parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
3100
- if (parsed.version !== FILE_VERSION || !Array.isArray(parsed.recipes)) return [];
3742
+ if (parsed.version !== 1 && parsed.version !== FILE_VERSION || !Array.isArray(parsed.recipes)) return [];
3101
3743
  return parsed.recipes.filter((recipe) => {
3102
3744
  if (recipe === null || typeof recipe !== "object") return false;
3103
3745
  if (typeof recipe.id !== "string" || typeof recipe.name !== "string") return false;
3104
3746
  return typeof recipe.createdAt === "number" && typeof recipe.updatedAt === "number";
3105
- }).map((recipe) => ({
3106
- ...recipe,
3107
- steps: sanitizeRecipeSteps(recipe.steps),
3108
- variables: sanitizeVariables(recipe.variables)
3109
- })).filter((recipe) => recipe.steps.length > 0).slice(0, MAX_RECIPES);
3747
+ }).map((recipe) => {
3748
+ const { pendingHeal: rawProposal, ...rest } = recipe;
3749
+ const proposal = sanitizeProposal(rawProposal);
3750
+ return {
3751
+ ...rest,
3752
+ steps: sanitizeRecipeSteps(recipe.steps),
3753
+ variables: sanitizeVariables(recipe.variables),
3754
+ rev: Number.isFinite(recipe.rev) && recipe.rev > 0 ? recipe.rev : 1,
3755
+ history: sanitizeHistory(recipe.history),
3756
+ autoHeals: sanitizeTimestamps(recipe.autoHeals),
3757
+ ...proposal === void 0 ? {} : { pendingHeal: proposal }
3758
+ };
3759
+ }).filter((recipe) => recipe.steps.length > 0).slice(0, MAX_RECIPES);
3110
3760
  } catch {
3111
3761
  return [];
3112
3762
  }
3113
3763
  }
3114
3764
  write(recipes) {
3765
+ this.revisionTick += 1;
3115
3766
  if (this.filePath === null) {
3116
3767
  this.memory = [...recipes];
3117
3768
  return;
@@ -3238,6 +3889,26 @@ function driverOf(options) {
3238
3889
  const value = options.driver;
3239
3890
  return typeof value === "function" ? value() : value;
3240
3891
  }
3892
+ async function captureRefEvidence(options, ref) {
3893
+ if (options.repair?.active() !== true) return null;
3894
+ const driver = driverOf(options);
3895
+ if (typeof driver.refInfo !== "function") return null;
3896
+ const info = await driver.refInfo(ref).catch(() => null);
3897
+ if (info === null) return null;
3898
+ return { role: info.role, name: info.name, selector: info.selector };
3899
+ }
3900
+ function recordRepair(options, evidence, kind, extra = {}) {
3901
+ if (options.repair?.active() !== true) return;
3902
+ options.repair.observe({
3903
+ kind,
3904
+ at: Date.now(),
3905
+ ...evidence === null ? {} : evidence,
3906
+ ...evidence === null || kind !== "fill" ? {} : { field: evidence.name },
3907
+ ...extra.value === void 0 ? {} : { value: extra.value },
3908
+ ...extra.url === void 0 ? {} : { url: extra.url },
3909
+ ...extra.tabId === void 0 ? {} : { tabId: extra.tabId }
3910
+ });
3911
+ }
3241
3912
  function pickEnum(value, allowed, field) {
3242
3913
  if (value === void 0 || value === null || value === "") return void 0;
3243
3914
  const text3 = String(value).trim().toLowerCase();
@@ -3661,6 +4332,15 @@ function registerBrowserTools(ctx, options) {
3661
4332
  outcome: "ok"
3662
4333
  });
3663
4334
  options.onMutation?.({ sessionId, tool: "browser_navigate", url: result.url });
4335
+ if (options.repair?.active() === true) {
4336
+ const tabId = options.sessions.tabOf(sessionId);
4337
+ options.repair.observe({
4338
+ kind: "navigate",
4339
+ at: Date.now(),
4340
+ url: result.url,
4341
+ ...tabId === void 0 ? {} : { tabId }
4342
+ });
4343
+ }
3664
4344
  return [
3665
4345
  newTab ? "opened_new_tab" : "navigated",
3666
4346
  `url: ${result.url}`,
@@ -3706,6 +4386,7 @@ function registerBrowserTools(ctx, options) {
3706
4386
  url = void 0;
3707
4387
  }
3708
4388
  requireFreshRef(sessionId, ref, "browser_click");
4389
+ const repairEvidence = await captureRefEvidence(options, ref);
3709
4390
  if (options.sessions.isDeadClickRef(sessionId, ref)) {
3710
4391
  throw new Error(
3711
4392
  `click_blocked: ref ${ref} already failed with no navigation. Do NOT browser_click it again. browser_navigate to a content URL, or browser_snapshot and use a ref that lists href=.`
@@ -3744,6 +4425,10 @@ function registerBrowserTools(ctx, options) {
3744
4425
  warning = navigated ? "Click was a no-op; host auto-navigated to a name-matched document link." : "Host tried name-matched auto-navigate after dead click but pathname still unchanged.";
3745
4426
  }
3746
4427
  }
4428
+ recordRepair(options, repairEvidence, "click", {
4429
+ url: result.url,
4430
+ tabId: options.sessions.tabOf(sessionId)
4431
+ });
3747
4432
  options.sessions.clearLastRefs(sessionId);
3748
4433
  if (!navigated) {
3749
4434
  options.sessions.markDeadClickRef(sessionId, ref);
@@ -3827,6 +4512,7 @@ function registerBrowserTools(ctx, options) {
3827
4512
  url = void 0;
3828
4513
  }
3829
4514
  requireFreshRef(sessionId, ref, "browser_type");
4515
+ const repairEvidence = await captureRefEvidence(options, ref);
3830
4516
  await requireMutation(exec, "browser_type", `Type into ref ${ref}: ${maskTypeSummary(text3)}`, url, ref);
3831
4517
  try {
3832
4518
  const result = await runBridge(() => driverOf(options).type(ref, text3));
@@ -3840,6 +4526,11 @@ function registerBrowserTools(ctx, options) {
3840
4526
  outcome: "ok"
3841
4527
  });
3842
4528
  options.onMutation?.({ sessionId, tool: "browser_type", url: result.url });
4529
+ recordRepair(options, repairEvidence, "fill", {
4530
+ value: text3,
4531
+ url: result.url,
4532
+ tabId: options.sessions.tabOf(sessionId)
4533
+ });
3843
4534
  return `typed into ref ${ref}
3844
4535
  url: ${result.url}
3845
4536
  title: ${result.title}
@@ -4333,21 +5024,29 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4333
5024
  )));
4334
5025
  disposers.push(ctx.tools.register(textTool(
4335
5026
  "browser_demo_recipes",
4336
- 'List or run a flow the user saved from a demonstration (right sidebar \u2192 \u6F14\u793A\u5F55\u5236 \u2192 \u4FDD\u5B58\u4E3A\u6D41\u7A0B). Use it when the user names a saved flow ("\u8DD1\u4E00\u4E0B\u300C\u5468\u62A5\u5BFC\u51FA\u300D\u6D41\u7A0B") or asks which flows exist. Running replays the recorded steps in the dedicated browser; it asks for approval once and stops at a masked secret or a control that is gone, exactly like browser_demonstrate replay.',
5027
+ 'List, run, or repair a flow the user saved from a demonstration (right sidebar \u2192 \u6F14\u793A\u5F55\u5236 \u2192 \u4FDD\u5B58\u4E3A\u6D41\u7A0B). Use it when the user names a saved flow ("\u8DD1\u4E00\u4E0B\u300C\u5468\u62A5\u5BFC\u51FA\u300D\u6D41\u7A0B") or asks which flows exist. Running replays the recorded steps in the dedicated browser; it asks for approval once and stops at a masked secret or a control that is gone, exactly like browser_demonstrate replay. When it stops because a control changed, finish the remaining steps yourself, then call action=heal so the user can keep the fix. A flow that still needs a value says which ones by their label: ask the user one short question ("\u8FD9\u6B21\u5F00\u59CB\u65E5\u671F\u7528\u54EA\u5929\uFF1F") and run again with vars. Do not ask for values the recording already fixed.',
4337
5028
  {
4338
5029
  action: {
4339
5030
  type: "string",
4340
5031
  required: true,
4341
- description: '"list" to show saved flows, "run" to replay one.'
5032
+ description: '"list" to show saved flows, "run" to replay one, "heal" to offer the fix you just worked out.'
4342
5033
  },
4343
5034
  name: {
4344
5035
  type: "string",
4345
5036
  description: "Flow name for action=run. Case-insensitive; a unique part of the name is enough."
4346
5037
  },
5038
+ id: {
5039
+ type: "string",
5040
+ description: "Flow id for action=heal; omit to use the flow that just stopped."
5041
+ },
5042
+ accept: {
5043
+ type: "boolean",
5044
+ description: "action=heal: apply the repair to the saved flow now (the user asked to remember it). Default false: offer it in the sidebar."
5045
+ },
4347
5046
  vars: {
4348
5047
  type: "object",
4349
5048
  additionalProperties: true,
4350
- description: `Values for the flow's variables, e.g. {"from":"2026-11-01"}. Saved defaults are used for anything omitted.`
5049
+ description: `Values for the flow's variables, keyed by the label the user sees ('{"\u5F00\u59CB\u65E5\u671F":"2026-11-01"}') or by id. Dates may be relative: \u4ECA\u5929 / \u4E0A\u5468 / \u4E0A\u6708 / \u4E0A\u5B63\u5EA6 / 2026-11-01. Saved defaults are used for anything omitted.`
4351
5050
  }
4352
5051
  },
4353
5052
  async (args, exec) => {
@@ -4358,16 +5057,76 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4358
5057
  const action = String(args.action ?? "").trim().toLowerCase();
4359
5058
  const rows = store.list();
4360
5059
  if (action === "list") {
4361
- if (rows.length === 0) {
5060
+ options.repair?.commit();
5061
+ const afterCommit = store.list();
5062
+ if (afterCommit.length === 0) {
4362
5063
  return "saved flows: 0\nAction: none yet \u2014 the user can record a demonstration and save it in the sidebar, then retry.";
4363
5064
  }
4364
5065
  return [
4365
- `saved flows: ${rows.length}`,
4366
- ...rows.map((row) => `- ${row.name} (${row.steps} step(s)${row.variables.length === 0 ? "" : `; vars: ${row.variables.map((variable) => variable.name).join(", ")}`})`),
5066
+ `saved flows: ${afterCommit.length}`,
5067
+ ...afterCommit.map((row) => {
5068
+ const vars = row.variables.length === 0 ? "" : `; vars: ${row.variables.map((variable) => variable.name).join(", ")}`;
5069
+ const heal = row.pendingHeal === void 0 ? "" : `; repair waiting: step ${row.pendingHeal.failedAt}`;
5070
+ const auto = row.autoHeals === 0 ? "" : `; auto-adapted ${row.autoHeals}x`;
5071
+ return `- ${row.name} (${row.steps} step(s)${vars}${heal}${auto})`;
5072
+ }),
4367
5073
  'Action: run one with browser_demo_recipes { action: "run", name: "<name>" }.'
4368
5074
  ].join("\n");
4369
5075
  }
4370
- if (action !== "run") throw new Error('action must be "list" or "run"');
5076
+ if (action === "heal") {
5077
+ const committed = options.repair?.commit() ?? null;
5078
+ const id = String(args.id ?? committed?.recipeId ?? "").trim();
5079
+ if (id === "") {
5080
+ return "nothing to remember: no saved flow stopped recently, so there is no repair to store.";
5081
+ }
5082
+ if (committed?.autoApplied === true) {
5083
+ options.sessions.record({
5084
+ sessionId: sessionIdOf(exec),
5085
+ tool: "browser_demo_recipe",
5086
+ summary: `Auto-adapted saved flow "${committed.recipeName}"`,
5087
+ outcome: "ok"
5088
+ });
5089
+ return [
5090
+ `saved flow: ${committed.recipeName} \u2014 repair applied automatically (\u81EA\u52A8\u9002\u5E94 is on)`,
5091
+ ...committed.lines.map((line) => `- ${line}`),
5092
+ "Action: tell the user the flow was updated without asking, and that \u64A4\u9500\u4E0A\u6B21\u4FEE\u6539 in the sidebar restores the previous version."
5093
+ ].join("\n");
5094
+ }
5095
+ if (args.accept !== true) {
5096
+ const row = store.list().find((candidate) => candidate.id === id);
5097
+ const proposal = row?.pendingHeal;
5098
+ if (committed === null && proposal === void 0) {
5099
+ return `nothing to remember: no repair for "${row?.name ?? id}" \u2014 the flow either ran clean or the difference was not a moved control.`;
5100
+ }
5101
+ options.sessions.record({
5102
+ sessionId: sessionIdOf(exec),
5103
+ tool: "browser_demo_recipe",
5104
+ summary: `Offered a repair for saved flow "${row?.name ?? id}"`,
5105
+ outcome: "ok"
5106
+ });
5107
+ return [
5108
+ `saved flow: ${row?.name ?? id} \u2014 repair offered`,
5109
+ ...committed === null ? [] : committed.lines.map((line) => `- ${line}`),
5110
+ "Action: tell the user you worked around a changed control and that they can accept the fix in the sidebar (\u6F14\u793A\u5F55\u5236 \u2192 this flow). Do not claim the flow itself was updated."
5111
+ ].join("\n");
5112
+ }
5113
+ const resolved = store.resolveHeal({ id, accept: true });
5114
+ if (!resolved.ok) {
5115
+ return `nothing to remember: ${resolved.error}`;
5116
+ }
5117
+ options.sessions.record({
5118
+ sessionId: sessionIdOf(exec),
5119
+ tool: "browser_demo_recipe",
5120
+ summary: `Applied a repair for saved flow "${resolved.recipe.name}"`,
5121
+ outcome: "ok"
5122
+ });
5123
+ return [
5124
+ `saved flow: ${resolved.recipe.name} \u2014 repair applied`,
5125
+ ...committed === null ? [] : committed.lines.map((line) => `- ${line}`),
5126
+ "Action: the flow now uses the control you found. Tell the user it should work next time, and that the previous version can be restored in the sidebar."
5127
+ ].join("\n");
5128
+ }
5129
+ if (action !== "run") throw new Error('action must be "list", "run" or "heal"');
4371
5130
  const wanted = String(args.name ?? "").trim();
4372
5131
  if (wanted === "") throw new Error("name is required for action=run");
4373
5132
  const exact = rows.find((row) => row.name.toLowerCase() === wanted.toLowerCase());
@@ -4378,15 +5137,18 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4378
5137
  }
4379
5138
  const recipe = store.get(meta.id);
4380
5139
  if (recipe === void 0) throw new Error("The saved flow disappeared; list again.");
5140
+ options.repair?.commit();
4381
5141
  const provided = args.vars !== null && typeof args.vars === "object" ? Object.fromEntries(Object.entries(args.vars).filter(([, value]) => typeof value === "string").map(([key, value]) => [key, String(value)])) : {};
4382
- const defaults = {};
4383
- for (const variable of recipe.variables) defaults[variable.name] = variable.default;
4384
- const values = { ...defaults, ...provided };
4385
- const missing = missingRecipeVars(recipe, values);
4386
- if (missing.length > 0) {
4387
- throw new Error(`Flow "${recipe.name}" still needs: ${missing.join(", ")}. Pass vars, or save defaults in the sidebar.`);
5142
+ const prepared = prepareRecipeValues(recipe, provided);
5143
+ if (prepared.missing.length > 0) {
5144
+ const wanted2 = prepared.missing.map((variable) => variable.label).join("\u3001");
5145
+ const example = JSON.stringify(Object.fromEntries(prepared.missing.map((variable) => [variable.label, "\u2026"])));
5146
+ throw new Error(
5147
+ `Flow "${recipe.name}" still needs ${wanted2}. Ask the user for ${prepared.missing.length === 1 ? "it" : "them"} in one short question, then run again with vars: ${example}. Dates may be relative: \u4ECA\u5929 / \u4E0A\u5468 / \u672C\u6708 / \u4E0A\u5B63\u5EA6 / 2026-11-01.`
5148
+ );
4388
5149
  }
4389
- const replaySteps = applyRecipeVars(recipe.steps, values);
5150
+ const replaySteps = applyRecipeVars(recipe.steps, prepared.values);
5151
+ const resolvedNote = prepared.resolved.length === 0 ? [] : [`resolved: ${prepared.resolved.map((item) => `${item.label} ${item.from} \u2192 ${item.to}`).join("; ")}`];
4390
5152
  const sessionId = sessionIdOf(exec);
4391
5153
  await ensureConnected();
4392
5154
  await ensureSessionTab(sessionId);
@@ -4399,6 +5161,22 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4399
5161
  );
4400
5162
  const outcome = await replayDemoSteps(driverOf(options), replaySteps);
4401
5163
  const ranAll = outcome.status === "done";
5164
+ if (!ranAll) {
5165
+ const failedStep = recipe.steps[outcome.performed];
5166
+ const isSecret = /masked|secret field/i.test(outcome.reason) || failedStep !== void 0 && failedStep.kind === "fill" && failedStep.masked;
5167
+ if (!isSecret && failedStep !== void 0 && options.repair !== void 0) {
5168
+ const tabId = options.sessions.tabOf(sessionId);
5169
+ options.repair.begin({
5170
+ recipeId: recipe.id,
5171
+ recipeName: recipe.name,
5172
+ index: outcome.performed,
5173
+ step: failedStep,
5174
+ reason: outcome.reason,
5175
+ ...tabId === void 0 ? {} : { tabId },
5176
+ ...outcome.url === void 0 ? {} : { tabUrl: outcome.url }
5177
+ });
5178
+ }
5179
+ }
4402
5180
  options.sessions.record({
4403
5181
  sessionId,
4404
5182
  tool: "browser_demo_recipes",
@@ -4408,6 +5186,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4408
5186
  if (ranAll) {
4409
5187
  return [
4410
5188
  `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
5189
+ ...resolvedNote,
4411
5190
  ...outcome.lines,
4412
5191
  `url: ${outcome.url}`,
4413
5192
  "Action: the flow ran to the end. Report what changed on screen; browser_snapshot if you need the new page."
@@ -4419,10 +5198,11 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4419
5198
  });
4420
5199
  return [
4421
5200
  `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
5201
+ ...resolvedNote,
4422
5202
  ...outcome.lines,
4423
5203
  `stopped at step ${outcome.performed + 1}: ${outcome.reason}`,
4424
5204
  ...pending,
4425
- "Action: the replay stopped; the page is whatever the last ok step left behind. Continue with browser_snapshot + click/type, or browser_ask_user for a secret. Do not claim the flow finished."
5205
+ 'Action: the replay stopped; the page is whatever the last ok step left behind. Continue with browser_snapshot + click/type, or browser_ask_user for a secret. Do not claim the flow finished. If a control had moved and you worked around it, finish the job and then call browser_demo_recipes { action: "heal" } so the user can keep that fix.'
4426
5206
  ].join("\n");
4427
5207
  }
4428
5208
  )));
@@ -4514,6 +5294,12 @@ function installBrowserAgent(ctx, options) {
4514
5294
  const tabScope = new TabScopeStore();
4515
5295
  const recipes = options.recipes;
4516
5296
  let lastDemoSteps = [];
5297
+ const repairTracker = new DemoRepairTracker();
5298
+ const repairHooks = createRepairHooks({
5299
+ tracker: repairTracker,
5300
+ ...recipes === void 0 ? {} : { store: recipes },
5301
+ ...options.autoHeal === void 0 ? {} : { autoApply: options.autoHeal }
5302
+ });
4517
5303
  let availabilityCache = null;
4518
5304
  const browserAvailability = () => {
4519
5305
  if (availabilityCache !== null) return availabilityCache;
@@ -4637,6 +5423,7 @@ function installBrowserAgent(ctx, options) {
4637
5423
  lastDemoSteps = steps;
4638
5424
  },
4639
5425
  ...recipes === void 0 ? {} : { recipes },
5426
+ repair: repairHooks,
4640
5427
  diagnosis: diagnoseNow,
4641
5428
  // Gate on settings only — `active` flips false during driver align and
4642
5429
  // must not make browser_* look "disabled" mid-turn.
@@ -4852,12 +5639,39 @@ function installBrowserAgent(ctx, options) {
4852
5639
  lastDemonstrationSteps() {
4853
5640
  return lastDemoSteps.length;
4854
5641
  },
5642
+ recipesRevision() {
5643
+ return recipes?.revision() ?? 0;
5644
+ },
4855
5645
  async demoRecipes(input) {
4856
5646
  if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
4857
5647
  if (recipes === void 0) return { ok: false, error: "recipe store unavailable" };
5648
+ repairHooks.commit();
4858
5649
  if (input.action === "list") {
4859
5650
  return { ok: true, recipes: recipes.list() };
4860
5651
  }
5652
+ if (input.action === "save") {
5653
+ if (options.demonstrate?.() !== true) {
5654
+ return { ok: false, error: "\u6F14\u793A\u5F55\u5236\u672A\u5F00\u542F\uFF1A\u8BBE\u7F6E \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent" };
5655
+ }
5656
+ if (lastDemoSteps.length === 0) {
5657
+ return { ok: false, error: "\u5148\u5F55\u5236\u4E00\u6B21\uFF0C\u518D\u4FDD\u5B58\u4E3A\u6D41\u7A0B", recipes: recipes.list() };
5658
+ }
5659
+ const saved = recipes.save({ name: input.name ?? "", steps: lastDemoSteps });
5660
+ if (!saved.ok) return { ok: false, error: saved.error, recipes: recipes.list() };
5661
+ sessions.record({
5662
+ sessionId: "sidebar",
5663
+ tool: "browser_demo_recipe",
5664
+ summary: `Saved demonstration recipe "${saved.recipe.name}" (${saved.recipe.steps} step(s))`,
5665
+ outcome: "ok"
5666
+ });
5667
+ return {
5668
+ ok: true,
5669
+ recipe: saved.recipe,
5670
+ recipes: recipes.list(),
5671
+ // Offered, never applied: the user decides what becomes a variable.
5672
+ suggestions: suggestRecipeVariables(lastDemoSteps)
5673
+ };
5674
+ }
4861
5675
  if (input.action === "delete") {
4862
5676
  const id = input.id ?? "";
4863
5677
  const removed = recipes.remove(id);
@@ -4879,7 +5693,7 @@ function installBrowserAgent(ctx, options) {
4879
5693
  steps: recipe2.steps.map((step, index) => ({
4880
5694
  index,
4881
5695
  kind: step.kind,
4882
- label: describeDemoStep(step),
5696
+ label: describeDemoStepHuman(step, recipe2.variables),
4883
5697
  canParameterize: step.kind === "fill" && !step.masked && !/\$\{[A-Za-z_][A-Za-z0-9_]*\}/.test(step.value)
4884
5698
  }))
4885
5699
  };
@@ -4888,7 +5702,8 @@ function installBrowserAgent(ctx, options) {
4888
5702
  const result = recipes.parameterize({
4889
5703
  id: input.id ?? "",
4890
5704
  index: input.index ?? -1,
4891
- name: input.name ?? ""
5705
+ ...input.name === void 0 ? {} : { name: input.name },
5706
+ ...input.label === void 0 ? {} : { label: input.label }
4892
5707
  });
4893
5708
  if (!result.ok) return { ok: false, error: result.error, recipes: recipes.list() };
4894
5709
  sessions.record({
@@ -4910,20 +5725,45 @@ function installBrowserAgent(ctx, options) {
4910
5725
  });
4911
5726
  return { ok: true, recipe: renamed.recipe, recipes: recipes.list() };
4912
5727
  }
5728
+ if (input.action === "heal") {
5729
+ const resolved = recipes.resolveHeal({ id: input.id ?? "", accept: input.accept === true });
5730
+ if (!resolved.ok) return { ok: false, error: resolved.error, recipes: recipes.list() };
5731
+ sessions.record({
5732
+ sessionId: "sidebar",
5733
+ tool: "browser_demo_recipe",
5734
+ summary: `${input.accept === true ? "Applied" : "Dismissed"} a repair for "${resolved.recipe.name}"`,
5735
+ outcome: "ok"
5736
+ });
5737
+ return {
5738
+ ok: true,
5739
+ healed: input.accept === true,
5740
+ recipe: resolved.recipe,
5741
+ recipes: recipes.list()
5742
+ };
5743
+ }
5744
+ if (input.action === "rollback") {
5745
+ const restored = recipes.rollback({ id: input.id ?? "" });
5746
+ if (!restored.ok) return { ok: false, error: restored.error, recipes: recipes.list() };
5747
+ sessions.record({
5748
+ sessionId: "sidebar",
5749
+ tool: "browser_demo_recipe",
5750
+ summary: `Restored the previous version of "${restored.recipe.name}"`,
5751
+ outcome: "ok"
5752
+ });
5753
+ return { ok: true, recipe: restored.recipe, recipes: recipes.list() };
5754
+ }
4913
5755
  const recipe = recipes.get(input.id ?? "");
4914
5756
  if (recipe === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4915
- const defaults = {};
4916
- for (const variable of recipe.variables) defaults[variable.name] = variable.default;
4917
- const values = { ...defaults, ...input.vars ?? {} };
4918
- const missing = missingRecipeVars(recipe, values);
4919
- if (missing.length > 0) {
5757
+ repairHooks.commit();
5758
+ const prepared = prepareRecipeValues(recipe, input.vars ?? {});
5759
+ if (prepared.missing.length > 0) {
4920
5760
  return {
4921
5761
  ok: false,
4922
- error: `\u7F3A\u5C11\u53D8\u91CF\uFF1A${missing.join("\u3001")}`,
5762
+ error: `\u8FD8\u7F3A\u5C11\uFF1A${prepared.missing.map((variable) => variable.label).join("\u3001")}`,
4923
5763
  recipes: recipes.list()
4924
5764
  };
4925
5765
  }
4926
- const steps = applyRecipeVars(recipe.steps, values);
5766
+ const steps = applyRecipeVars(recipe.steps, prepared.values);
4927
5767
  const driver = activeDriver;
4928
5768
  if (driver === null) return { ok: false, error: "Browser agent is not running", recipes: recipes.list() };
4929
5769
  const aligned = await alignToPreference().catch(() => ({ ok: true, error: void 0 }));
@@ -4937,6 +5777,21 @@ function installBrowserAgent(ctx, options) {
4937
5777
  pending: [...steps]
4938
5778
  }));
4939
5779
  const ranAll = outcome.status === "done";
5780
+ if (!ranAll) {
5781
+ const failedStep = recipe.steps[outcome.performed];
5782
+ const isSecret = /masked|secret field/i.test(outcome.reason) || failedStep !== void 0 && failedStep.kind === "fill" && failedStep.masked;
5783
+ if (!isSecret && failedStep !== void 0) {
5784
+ const stopUrl = "url" in outcome ? outcome.url : void 0;
5785
+ repairTracker.begin({
5786
+ recipeId: recipe.id,
5787
+ recipeName: recipe.name,
5788
+ index: outcome.performed,
5789
+ step: failedStep,
5790
+ reason: outcome.reason,
5791
+ ...stopUrl === void 0 ? {} : { tabUrl: stopUrl }
5792
+ });
5793
+ }
5794
+ }
4940
5795
  sessions.record({
4941
5796
  sessionId: "sidebar",
4942
5797
  tool: "browser_demo_recipe",
@@ -4946,7 +5801,10 @@ function installBrowserAgent(ctx, options) {
4946
5801
  return {
4947
5802
  ok: true,
4948
5803
  recipes: recipes.list(),
4949
- lines: [...outcome.lines],
5804
+ lines: [
5805
+ ...prepared.resolved.length === 0 ? [] : [`resolved: ${prepared.resolved.map((item) => `${item.label} ${item.from} \u2192 ${item.to}`).join("; ")}`],
5806
+ ...outcome.lines
5807
+ ],
4950
5808
  ...ranAll ? {} : { stoppedAt: outcome.performed + 1 },
4951
5809
  ...ranAll ? {} : { reason: outcome.reason }
4952
5810
  };
@@ -17119,7 +17977,9 @@ var browserAgentSnapshotSchema = z4.strictObject({
17119
17977
  enabled: z4.boolean(),
17120
17978
  recording: z4.boolean(),
17121
17979
  /** Steps from the last finished recording, whoever stopped it. */
17122
- lastSteps: z4.number().int()
17980
+ lastSteps: z4.number().int(),
17981
+ /** Bumped when a saved flow changes; the panel re-reads the list on change. */
17982
+ recipesVersion: z4.number().int()
17123
17983
  }),
17124
17984
  tabConflict: browserAgentTabConflictSchema.nullable(),
17125
17985
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
@@ -17170,8 +18030,29 @@ var browserAgentThumbnailResultCodec = codec(
17170
18030
  browserAgentThumbnailResultSchema
17171
18031
  );
17172
18032
  var demoRecipeVariableSchema = z4.strictObject({
18033
+ /** Token id, e.g. `v1`; not shown to the user. */
17173
18034
  name: z4.string().min(1),
17174
- default: z4.string()
18035
+ /** What the panel shows: 「开始日期」. */
18036
+ label: z4.string().min(1),
18037
+ default: z4.string(),
18038
+ /** Render a date picker for date-shaped values. */
18039
+ kind: z4.enum(["text", "date"])
18040
+ });
18041
+ var demoRecipeSuggestionSchema = z4.strictObject({
18042
+ index: z4.number().int(),
18043
+ label: z4.string(),
18044
+ value: z4.string()
18045
+ });
18046
+ var demoRecipeHealSchema = z4.strictObject({
18047
+ id: z4.string().min(1),
18048
+ /** 1-based step the replay stopped at. */
18049
+ failedAt: z4.number().int().min(1),
18050
+ kind: z4.enum(["navigate", "click", "fill", "press"]),
18051
+ /** The control's name (URL for navigate, key for press). */
18052
+ label: z4.string(),
18053
+ /** Steps the agent had to add before it (a cookie banner…). */
18054
+ inserted: z4.number().int().min(0),
18055
+ reason: z4.string()
17175
18056
  });
17176
18057
  var demoRecipeMetaSchema = z4.strictObject({
17177
18058
  id: z4.string().min(1),
@@ -17179,7 +18060,13 @@ var demoRecipeMetaSchema = z4.strictObject({
17179
18060
  createdAt: z4.number(),
17180
18061
  updatedAt: z4.number(),
17181
18062
  steps: z4.number().int(),
17182
- variables: z4.array(demoRecipeVariableSchema)
18063
+ variables: z4.array(demoRecipeVariableSchema),
18064
+ /** Content revision; grows with every accepted change. */
18065
+ rev: z4.number().int(),
18066
+ /** How many previous versions can be restored. */
18067
+ history: z4.number().int(),
18068
+ /** A repair worked out by the agent, waiting for the user. */
18069
+ pendingHeal: demoRecipeHealSchema.optional()
17183
18070
  });
17184
18071
  var demoRecipeStepSchema = z4.strictObject({
17185
18072
  index: z4.number().int(),
@@ -17199,7 +18086,16 @@ var browserAgentDemoRecipesRequestSchema = z4.discriminatedUnion("action", [
17199
18086
  z4.strictObject({ action: z4.literal("delete"), id: z4.string().min(1) }),
17200
18087
  z4.strictObject({ action: z4.literal("steps"), id: z4.string().min(1) }),
17201
18088
  z4.strictObject({ action: z4.literal("rename"), id: z4.string().min(1), name: z4.string() }),
17202
- z4.strictObject({ action: z4.literal("parameterize"), id: z4.string().min(1), index: z4.number().int().min(0), name: z4.string() })
18089
+ z4.strictObject({
18090
+ action: z4.literal("parameterize"),
18091
+ id: z4.string().min(1),
18092
+ index: z4.number().int().min(0),
18093
+ /** Display name; the token id is generated when omitted. */
18094
+ label: z4.string().optional(),
18095
+ name: z4.string().optional()
18096
+ }),
18097
+ z4.strictObject({ action: z4.literal("heal"), id: z4.string().min(1), accept: z4.boolean() }),
18098
+ z4.strictObject({ action: z4.literal("rollback"), id: z4.string().min(1) })
17203
18099
  ]);
17204
18100
  var browserAgentDemoRecipesRequestCodec = codec(
17205
18101
  "dsh-agent-enhancer#BrowserAgentDemoRecipesRequest",
@@ -17213,6 +18109,10 @@ var browserAgentDemoRecipesResultSchema = z4.strictObject({
17213
18109
  lines: z4.array(z4.string()).optional(),
17214
18110
  /** Step metadata for action=steps (index + what the row can do). */
17215
18111
  steps: z4.array(demoRecipeStepSchema).optional(),
18112
+ /** True when a repair was applied (action=heal with accept). */
18113
+ healed: z4.boolean().optional(),
18114
+ /** Values worth turning into variables (action=save). */
18115
+ suggestions: z4.array(demoRecipeSuggestionSchema).optional(),
17216
18116
  /** 1-based step where a replay stopped. */
17217
18117
  stoppedAt: z4.number().int().optional(),
17218
18118
  reason: z4.string().optional(),
@@ -18843,6 +19743,8 @@ var Config = z5.object({
18843
19743
  browserAgentDebugTools: z5.boolean().default(false).volatile(),
18844
19744
  /** "Show me" recorder; observes user actions in the bound tab, default off. */
18845
19745
  browserAgentDemonstrate: z5.boolean().default(false).volatile(),
19746
+ /** Keep a repair automatically when the site changed (locator only). Default off. */
19747
+ browserAgentAutoHeal: z5.boolean().default(false).volatile(),
18846
19748
  /** Close idle agent tabs after ~10 min; coerced via resolveBrowserAgentIdleClose. */
18847
19749
  browserAgentIdleClose: z5.union([z5.boolean(), z5.string()]).default("10m").volatile(),
18848
19750
  /** Default off; embeds official web chat + import to work. */
@@ -18973,7 +19875,8 @@ var AgentEnhancerService = class extends TypertRemoteService {
18973
19875
  demo: {
18974
19876
  enabled: settings.demonstrate,
18975
19877
  recording: this.browserAgent?.demoActive() === true,
18976
- lastSteps: this.browserAgent?.lastDemonstrationSteps() ?? 0
19878
+ lastSteps: this.browserAgent?.lastDemonstrationSteps() ?? 0,
19879
+ recipesVersion: this.browserAgent?.recipesRevision() ?? 0
18977
19880
  },
18978
19881
  diagnosis: diag ?? {
18979
19882
  code: settings.enabled ? "idle" : "disabled",
@@ -19697,17 +20600,42 @@ var AgentEnhancerService = class extends TypertRemoteService {
19697
20600
  ..."name" in request ? { name: request.name } : {},
19698
20601
  ..."id" in request ? { id: request.id } : {},
19699
20602
  ..."index" in request ? { index: request.index } : {},
20603
+ ..."label" in request && request.label !== void 0 ? { label: request.label } : {},
20604
+ ..."accept" in request && request.accept !== void 0 ? { accept: request.accept } : {},
19700
20605
  ..."vars" in request && request.vars !== void 0 ? { vars: request.vars } : {}
19701
20606
  });
19702
20607
  const meta = (recipe) => ({
19703
- ...recipe,
19704
- variables: recipe.variables.map((variable) => ({ ...variable }))
20608
+ id: recipe.id,
20609
+ name: recipe.name,
20610
+ createdAt: recipe.createdAt,
20611
+ updatedAt: recipe.updatedAt,
20612
+ steps: recipe.steps,
20613
+ variables: recipe.variables.map((variable) => ({
20614
+ name: variable.name,
20615
+ label: variable.label,
20616
+ default: variable.default,
20617
+ kind: isDateVariable(variable) ? "date" : "text"
20618
+ })),
20619
+ rev: recipe.rev,
20620
+ history: recipe.history,
20621
+ ...recipe.pendingHeal === void 0 ? {} : {
20622
+ pendingHeal: {
20623
+ id: recipe.pendingHeal.id,
20624
+ failedAt: recipe.pendingHeal.failedAt,
20625
+ kind: recipe.pendingHeal.replacement.kind,
20626
+ label: recipe.pendingHeal.replacement.kind === "navigate" ? recipe.pendingHeal.replacement.url : recipe.pendingHeal.replacement.kind === "press" ? recipe.pendingHeal.replacement.key : recipe.pendingHeal.replacement.name,
20627
+ inserted: recipe.pendingHeal.inserted.length,
20628
+ reason: recipe.pendingHeal.reason
20629
+ }
20630
+ }
19705
20631
  });
19706
20632
  return {
19707
20633
  ok: result.ok,
19708
20634
  ...result.recipes === void 0 ? {} : { recipes: result.recipes.map(meta) },
19709
20635
  ...result.recipe === void 0 ? {} : { recipe: meta(result.recipe) },
19710
20636
  ...result.lines === void 0 ? {} : { lines: [...result.lines] },
20637
+ ...result.healed === void 0 ? {} : { healed: result.healed },
20638
+ ...result.suggestions === void 0 ? {} : { suggestions: result.suggestions.map((item) => ({ ...item })) },
19711
20639
  ...result.steps === void 0 ? {} : { steps: result.steps.map((step) => ({ ...step })) },
19712
20640
  ...result.stoppedAt === void 0 ? {} : { stoppedAt: result.stoppedAt },
19713
20641
  ...result.reason === void 0 ? {} : { reason: result.reason },
@@ -19829,6 +20757,7 @@ function readSettings(config) {
19829
20757
  browserAgentBrowser: hostBrowserPreference(config.browserAgentBrowser.get()),
19830
20758
  browserAgentDebugTools: config.browserAgentDebugTools.get(),
19831
20759
  browserAgentDemonstrate: config.browserAgentDemonstrate.get(),
20760
+ browserAgentAutoHeal: config.browserAgentAutoHeal.get(),
19832
20761
  browserAgentIdleClose: resolveBrowserAgentIdleClose(config.browserAgentIdleClose.get()),
19833
20762
  webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
19834
20763
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
@@ -19912,13 +20841,15 @@ function apply(ctx, config) {
19912
20841
  const browserAgentLive = {
19913
20842
  enabled: settings().browserAgentEnabled,
19914
20843
  browser: settings().browserAgentBrowser,
19915
- demonstrate: settings().browserAgentDemonstrate
20844
+ demonstrate: settings().browserAgentDemonstrate,
20845
+ autoHeal: settings().browserAgentAutoHeal
19916
20846
  };
19917
20847
  const browserAgent = installBrowserAgent(ctx, {
19918
20848
  enabled: () => browserAgentLive.enabled,
19919
20849
  browserPreference: () => browserAgentLive.browser,
19920
20850
  debugTools: () => settings().browserAgentDebugTools,
19921
20851
  demonstrate: () => settings().browserAgentDemonstrate,
20852
+ autoHeal: () => settings().browserAgentAutoHeal,
19922
20853
  idleClose: () => settings().browserAgentIdleClose,
19923
20854
  recipes: new DemoRecipeStore(join30(pluginDataPackageRoot, "demo-recipes.json")),
19924
20855
  profileRoot: pluginDataPackageRoot,
@@ -19988,6 +20919,7 @@ function apply(ctx, config) {
19988
20919
  browserAgentLive.enabled = cfg.browserAgentEnabled.get();
19989
20920
  browserAgentLive.browser = hostBrowserPreference(cfg.browserAgentBrowser.get());
19990
20921
  browserAgentLive.demonstrate = cfg.browserAgentDemonstrate.get();
20922
+ browserAgentLive.autoHeal = cfg.browserAgentAutoHeal.get();
19991
20923
  browserAgent.refresh();
19992
20924
  if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
19993
20925
  void browserAgent.alignToPreference().catch((error) => {