dsh-agent-enhancer 0.3.21 → 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.
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":
@@ -2790,6 +2817,146 @@ function classify(input) {
2790
2817
  };
2791
2818
  }
2792
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
+
2793
2960
  // src/host/browser-agent/demo-replay.ts
2794
2961
  function normalizeControlName(raw) {
2795
2962
  return raw.replace(/[\u200b-\u200d\ufeff]/gu, "").replace(/\s+/gu, " ").trim().toLowerCase();
@@ -3156,6 +3323,16 @@ function describeHealProposal(proposal) {
3156
3323
  }
3157
3324
  return lines;
3158
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
+ }
3159
3336
  function createRepairHooks(input) {
3160
3337
  const clock = input.now ?? Date.now;
3161
3338
  return {
@@ -3173,20 +3350,30 @@ function createRepairHooks(input) {
3173
3350
  if (recipe === void 0) return null;
3174
3351
  const current = recipe.steps[pending.target.index];
3175
3352
  if (current === void 0 || !sameIdentity(current, pending.target.step)) return null;
3353
+ const now = clock();
3176
3354
  const proposal = buildHealProposal({
3177
3355
  steps: recipe.steps,
3178
3356
  failedIndex: pending.target.index,
3179
3357
  reason: pending.target.reason,
3180
3358
  observed: pending.observed,
3181
- now: clock()
3359
+ now
3182
3360
  });
3183
3361
  if (proposal === null) return null;
3184
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
+ }
3185
3371
  return {
3186
3372
  recipeId: recipe.id,
3187
3373
  recipeName: recipe.name,
3188
3374
  failedAt: proposal.failedAt,
3189
- lines: describeHealProposal(proposal)
3375
+ lines: describeHealProposal(proposal),
3376
+ autoApplied
3190
3377
  };
3191
3378
  }
3192
3379
  };
@@ -3223,6 +3410,8 @@ var MAX_RECIPES = 20;
3223
3410
  var MAX_RECIPE_NAME = 60;
3224
3411
  var MAX_RECIPE_STEPS = 200;
3225
3412
  var MAX_HISTORY = 5;
3413
+ var MAX_VARIABLE_LABEL = 60;
3414
+ var MAX_AUTO_HEALS = 3;
3226
3415
  var FILE_VERSION = 2;
3227
3416
  function metaOf(recipe) {
3228
3417
  return {
@@ -3234,6 +3423,7 @@ function metaOf(recipe) {
3234
3423
  variables: recipe.variables,
3235
3424
  rev: recipe.rev,
3236
3425
  history: recipe.history.length,
3426
+ autoHeals: recipe.autoHeals.length,
3237
3427
  ...recipe.pendingHeal === void 0 ? {} : { pendingHeal: recipe.pendingHeal }
3238
3428
  };
3239
3429
  }
@@ -3259,8 +3449,41 @@ function applyRecipeVars(steps, values) {
3259
3449
  return step;
3260
3450
  });
3261
3451
  }
3262
- function missingRecipeVars(recipe, values) {
3263
- 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 };
3264
3487
  }
3265
3488
  function sanitizeVariables(raw) {
3266
3489
  if (!Array.isArray(raw)) return [];
@@ -3268,7 +3491,12 @@ function sanitizeVariables(raw) {
3268
3491
  if (value === null || typeof value !== "object") return false;
3269
3492
  const name2 = value.name;
3270
3493
  return typeof name2 === "string" && VAR_NAME.test(name2);
3271
- }).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
+ }));
3272
3500
  }
3273
3501
  function sanitizeHistory(raw) {
3274
3502
  if (!Array.isArray(raw)) return [];
@@ -3288,6 +3516,10 @@ function sanitizeHistory(raw) {
3288
3516
  }
3289
3517
  return versions.slice(-MAX_HISTORY);
3290
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
+ }
3291
3523
  function sanitizeProposal(raw) {
3292
3524
  if (raw === null || typeof raw !== "object") return void 0;
3293
3525
  const entry = raw;
@@ -3305,6 +3537,13 @@ function sanitizeProposal(raw) {
3305
3537
  replacement
3306
3538
  };
3307
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)}`;
3546
+ }
3308
3547
  function isStep(value) {
3309
3548
  if (value === null || typeof value !== "object") return false;
3310
3549
  const kind = value.kind;
@@ -3363,7 +3602,8 @@ var DemoRecipeStore = class {
3363
3602
  steps,
3364
3603
  variables: [],
3365
3604
  rev: 1,
3366
- history: []
3605
+ history: [],
3606
+ autoHeals: []
3367
3607
  };
3368
3608
  }
3369
3609
  const next = existing === void 0 ? [...recipes, saved] : recipes.map((recipe) => recipe.id === saved.id ? saved : recipe);
@@ -3396,10 +3636,6 @@ var DemoRecipeStore = class {
3396
3636
  * value as the default so the flow still runs unchanged.
3397
3637
  */
3398
3638
  parameterize(input) {
3399
- const name2 = input.name.trim();
3400
- if (!VAR_NAME.test(name2)) {
3401
- 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" };
3402
- }
3403
3639
  const recipes = this.read();
3404
3640
  const current = recipes.find((recipe) => recipe.id === input.id);
3405
3641
  if (current === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728" };
@@ -3410,14 +3646,20 @@ var DemoRecipeStore = class {
3410
3646
  if (new RegExp(VAR_TOKEN.source).test(step.value)) {
3411
3647
  return { ok: false, error: "\u8FD9\u4E00\u6B65\u5DF2\u7ECF\u662F\u53D8\u91CF\u4E86" };
3412
3648
  }
3413
- 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)) {
3414
3654
  return { ok: false, error: "\u53D8\u91CF\u540D\u5DF2\u5B58\u5728" };
3415
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}`;
3416
3658
  const token = "${" + name2 + "}";
3417
3659
  const steps = current.steps.map(
3418
3660
  (entry, index) => index === input.index && entry.kind === "fill" ? { ...entry, value: token } : entry
3419
3661
  );
3420
- const variables = [...current.variables, { name: name2, default: step.value.slice(0, 500) }];
3662
+ const variables = [...current.variables, { name: name2, label, default: step.value.slice(0, 500) }];
3421
3663
  const now = input.now ?? Date.now();
3422
3664
  const { pendingHeal: _stale, ...rest } = current;
3423
3665
  const next = {
@@ -3462,7 +3704,8 @@ var DemoRecipeStore = class {
3462
3704
  steps,
3463
3705
  updatedAt: now,
3464
3706
  rev: current.rev + 1,
3465
- history: nextVersion(current, "heal", now)
3707
+ history: nextVersion(current, "heal", now),
3708
+ autoHeals: input.auto === true ? [...current.autoHeals, now].slice(-MAX_AUTO_HEALS) : current.autoHeals
3466
3709
  };
3467
3710
  this.write(recipes.map((recipe) => recipe.id === current.id ? next : recipe));
3468
3711
  return { ok: true, recipe: metaOf(next) };
@@ -3510,6 +3753,7 @@ var DemoRecipeStore = class {
3510
3753
  variables: sanitizeVariables(recipe.variables),
3511
3754
  rev: Number.isFinite(recipe.rev) && recipe.rev > 0 ? recipe.rev : 1,
3512
3755
  history: sanitizeHistory(recipe.history),
3756
+ autoHeals: sanitizeTimestamps(recipe.autoHeals),
3513
3757
  ...proposal === void 0 ? {} : { pendingHeal: proposal }
3514
3758
  };
3515
3759
  }).filter((recipe) => recipe.steps.length > 0).slice(0, MAX_RECIPES);
@@ -4780,7 +5024,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4780
5024
  )));
4781
5025
  disposers.push(ctx.tools.register(textTool(
4782
5026
  "browser_demo_recipes",
4783
- '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.',
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.',
4784
5028
  {
4785
5029
  action: {
4786
5030
  type: "string",
@@ -4802,7 +5046,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4802
5046
  vars: {
4803
5047
  type: "object",
4804
5048
  additionalProperties: true,
4805
- 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.`
4806
5050
  }
4807
5051
  },
4808
5052
  async (args, exec) => {
@@ -4823,7 +5067,8 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4823
5067
  ...afterCommit.map((row) => {
4824
5068
  const vars = row.variables.length === 0 ? "" : `; vars: ${row.variables.map((variable) => variable.name).join(", ")}`;
4825
5069
  const heal = row.pendingHeal === void 0 ? "" : `; repair waiting: step ${row.pendingHeal.failedAt}`;
4826
- return `- ${row.name} (${row.steps} step(s)${vars}${heal})`;
5070
+ const auto = row.autoHeals === 0 ? "" : `; auto-adapted ${row.autoHeals}x`;
5071
+ return `- ${row.name} (${row.steps} step(s)${vars}${heal}${auto})`;
4827
5072
  }),
4828
5073
  'Action: run one with browser_demo_recipes { action: "run", name: "<name>" }.'
4829
5074
  ].join("\n");
@@ -4834,6 +5079,19 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4834
5079
  if (id === "") {
4835
5080
  return "nothing to remember: no saved flow stopped recently, so there is no repair to store.";
4836
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
+ }
4837
5095
  if (args.accept !== true) {
4838
5096
  const row = store.list().find((candidate) => candidate.id === id);
4839
5097
  const proposal = row?.pendingHeal;
@@ -4881,14 +5139,16 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4881
5139
  if (recipe === void 0) throw new Error("The saved flow disappeared; list again.");
4882
5140
  options.repair?.commit();
4883
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)])) : {};
4884
- const defaults = {};
4885
- for (const variable of recipe.variables) defaults[variable.name] = variable.default;
4886
- const values = { ...defaults, ...provided };
4887
- const missing = missingRecipeVars(recipe, values);
4888
- if (missing.length > 0) {
4889
- 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
+ );
4890
5149
  }
4891
- 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("; ")}`];
4892
5152
  const sessionId = sessionIdOf(exec);
4893
5153
  await ensureConnected();
4894
5154
  await ensureSessionTab(sessionId);
@@ -4926,6 +5186,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4926
5186
  if (ranAll) {
4927
5187
  return [
4928
5188
  `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
5189
+ ...resolvedNote,
4929
5190
  ...outcome.lines,
4930
5191
  `url: ${outcome.url}`,
4931
5192
  "Action: the flow ran to the end. Report what changed on screen; browser_snapshot if you need the new page."
@@ -4937,6 +5198,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4937
5198
  });
4938
5199
  return [
4939
5200
  `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
5201
+ ...resolvedNote,
4940
5202
  ...outcome.lines,
4941
5203
  `stopped at step ${outcome.performed + 1}: ${outcome.reason}`,
4942
5204
  ...pending,
@@ -5035,7 +5297,8 @@ function installBrowserAgent(ctx, options) {
5035
5297
  const repairTracker = new DemoRepairTracker();
5036
5298
  const repairHooks = createRepairHooks({
5037
5299
  tracker: repairTracker,
5038
- ...recipes === void 0 ? {} : { store: recipes }
5300
+ ...recipes === void 0 ? {} : { store: recipes },
5301
+ ...options.autoHeal === void 0 ? {} : { autoApply: options.autoHeal }
5039
5302
  });
5040
5303
  let availabilityCache = null;
5041
5304
  const browserAvailability = () => {
@@ -5386,6 +5649,29 @@ function installBrowserAgent(ctx, options) {
5386
5649
  if (input.action === "list") {
5387
5650
  return { ok: true, recipes: recipes.list() };
5388
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
+ }
5389
5675
  if (input.action === "delete") {
5390
5676
  const id = input.id ?? "";
5391
5677
  const removed = recipes.remove(id);
@@ -5407,7 +5693,7 @@ function installBrowserAgent(ctx, options) {
5407
5693
  steps: recipe2.steps.map((step, index) => ({
5408
5694
  index,
5409
5695
  kind: step.kind,
5410
- label: describeDemoStep(step),
5696
+ label: describeDemoStepHuman(step, recipe2.variables),
5411
5697
  canParameterize: step.kind === "fill" && !step.masked && !/\$\{[A-Za-z_][A-Za-z0-9_]*\}/.test(step.value)
5412
5698
  }))
5413
5699
  };
@@ -5416,7 +5702,8 @@ function installBrowserAgent(ctx, options) {
5416
5702
  const result = recipes.parameterize({
5417
5703
  id: input.id ?? "",
5418
5704
  index: input.index ?? -1,
5419
- name: input.name ?? ""
5705
+ ...input.name === void 0 ? {} : { name: input.name },
5706
+ ...input.label === void 0 ? {} : { label: input.label }
5420
5707
  });
5421
5708
  if (!result.ok) return { ok: false, error: result.error, recipes: recipes.list() };
5422
5709
  sessions.record({
@@ -5468,18 +5755,15 @@ function installBrowserAgent(ctx, options) {
5468
5755
  const recipe = recipes.get(input.id ?? "");
5469
5756
  if (recipe === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
5470
5757
  repairHooks.commit();
5471
- const defaults = {};
5472
- for (const variable of recipe.variables) defaults[variable.name] = variable.default;
5473
- const values = { ...defaults, ...input.vars ?? {} };
5474
- const missing = missingRecipeVars(recipe, values);
5475
- if (missing.length > 0) {
5758
+ const prepared = prepareRecipeValues(recipe, input.vars ?? {});
5759
+ if (prepared.missing.length > 0) {
5476
5760
  return {
5477
5761
  ok: false,
5478
- error: `\u7F3A\u5C11\u53D8\u91CF\uFF1A${missing.join("\u3001")}`,
5762
+ error: `\u8FD8\u7F3A\u5C11\uFF1A${prepared.missing.map((variable) => variable.label).join("\u3001")}`,
5479
5763
  recipes: recipes.list()
5480
5764
  };
5481
5765
  }
5482
- const steps = applyRecipeVars(recipe.steps, values);
5766
+ const steps = applyRecipeVars(recipe.steps, prepared.values);
5483
5767
  const driver = activeDriver;
5484
5768
  if (driver === null) return { ok: false, error: "Browser agent is not running", recipes: recipes.list() };
5485
5769
  const aligned = await alignToPreference().catch(() => ({ ok: true, error: void 0 }));
@@ -5497,12 +5781,14 @@ function installBrowserAgent(ctx, options) {
5497
5781
  const failedStep = recipe.steps[outcome.performed];
5498
5782
  const isSecret = /masked|secret field/i.test(outcome.reason) || failedStep !== void 0 && failedStep.kind === "fill" && failedStep.masked;
5499
5783
  if (!isSecret && failedStep !== void 0) {
5784
+ const stopUrl = "url" in outcome ? outcome.url : void 0;
5500
5785
  repairTracker.begin({
5501
5786
  recipeId: recipe.id,
5502
5787
  recipeName: recipe.name,
5503
5788
  index: outcome.performed,
5504
5789
  step: failedStep,
5505
- reason: outcome.reason
5790
+ reason: outcome.reason,
5791
+ ...stopUrl === void 0 ? {} : { tabUrl: stopUrl }
5506
5792
  });
5507
5793
  }
5508
5794
  }
@@ -5515,7 +5801,10 @@ function installBrowserAgent(ctx, options) {
5515
5801
  return {
5516
5802
  ok: true,
5517
5803
  recipes: recipes.list(),
5518
- 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
+ ],
5519
5808
  ...ranAll ? {} : { stoppedAt: outcome.performed + 1 },
5520
5809
  ...ranAll ? {} : { reason: outcome.reason }
5521
5810
  };
@@ -17741,8 +18030,18 @@ var browserAgentThumbnailResultCodec = codec(
17741
18030
  browserAgentThumbnailResultSchema
17742
18031
  );
17743
18032
  var demoRecipeVariableSchema = z4.strictObject({
18033
+ /** Token id, e.g. `v1`; not shown to the user. */
17744
18034
  name: z4.string().min(1),
17745
- 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()
17746
18045
  });
17747
18046
  var demoRecipeHealSchema = z4.strictObject({
17748
18047
  id: z4.string().min(1),
@@ -17787,7 +18086,14 @@ var browserAgentDemoRecipesRequestSchema = z4.discriminatedUnion("action", [
17787
18086
  z4.strictObject({ action: z4.literal("delete"), id: z4.string().min(1) }),
17788
18087
  z4.strictObject({ action: z4.literal("steps"), id: z4.string().min(1) }),
17789
18088
  z4.strictObject({ action: z4.literal("rename"), id: z4.string().min(1), name: z4.string() }),
17790
- 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
+ }),
17791
18097
  z4.strictObject({ action: z4.literal("heal"), id: z4.string().min(1), accept: z4.boolean() }),
17792
18098
  z4.strictObject({ action: z4.literal("rollback"), id: z4.string().min(1) })
17793
18099
  ]);
@@ -17805,6 +18111,8 @@ var browserAgentDemoRecipesResultSchema = z4.strictObject({
17805
18111
  steps: z4.array(demoRecipeStepSchema).optional(),
17806
18112
  /** True when a repair was applied (action=heal with accept). */
17807
18113
  healed: z4.boolean().optional(),
18114
+ /** Values worth turning into variables (action=save). */
18115
+ suggestions: z4.array(demoRecipeSuggestionSchema).optional(),
17808
18116
  /** 1-based step where a replay stopped. */
17809
18117
  stoppedAt: z4.number().int().optional(),
17810
18118
  reason: z4.string().optional(),
@@ -19435,6 +19743,8 @@ var Config = z5.object({
19435
19743
  browserAgentDebugTools: z5.boolean().default(false).volatile(),
19436
19744
  /** "Show me" recorder; observes user actions in the bound tab, default off. */
19437
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(),
19438
19748
  /** Close idle agent tabs after ~10 min; coerced via resolveBrowserAgentIdleClose. */
19439
19749
  browserAgentIdleClose: z5.union([z5.boolean(), z5.string()]).default("10m").volatile(),
19440
19750
  /** Default off; embeds official web chat + import to work. */
@@ -20290,6 +20600,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
20290
20600
  ..."name" in request ? { name: request.name } : {},
20291
20601
  ..."id" in request ? { id: request.id } : {},
20292
20602
  ..."index" in request ? { index: request.index } : {},
20603
+ ..."label" in request && request.label !== void 0 ? { label: request.label } : {},
20293
20604
  ..."accept" in request && request.accept !== void 0 ? { accept: request.accept } : {},
20294
20605
  ..."vars" in request && request.vars !== void 0 ? { vars: request.vars } : {}
20295
20606
  });
@@ -20299,7 +20610,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
20299
20610
  createdAt: recipe.createdAt,
20300
20611
  updatedAt: recipe.updatedAt,
20301
20612
  steps: recipe.steps,
20302
- variables: recipe.variables.map((variable) => ({ ...variable })),
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
+ })),
20303
20619
  rev: recipe.rev,
20304
20620
  history: recipe.history,
20305
20621
  ...recipe.pendingHeal === void 0 ? {} : {
@@ -20319,6 +20635,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
20319
20635
  ...result.recipe === void 0 ? {} : { recipe: meta(result.recipe) },
20320
20636
  ...result.lines === void 0 ? {} : { lines: [...result.lines] },
20321
20637
  ...result.healed === void 0 ? {} : { healed: result.healed },
20638
+ ...result.suggestions === void 0 ? {} : { suggestions: result.suggestions.map((item) => ({ ...item })) },
20322
20639
  ...result.steps === void 0 ? {} : { steps: result.steps.map((step) => ({ ...step })) },
20323
20640
  ...result.stoppedAt === void 0 ? {} : { stoppedAt: result.stoppedAt },
20324
20641
  ...result.reason === void 0 ? {} : { reason: result.reason },
@@ -20440,6 +20757,7 @@ function readSettings(config) {
20440
20757
  browserAgentBrowser: hostBrowserPreference(config.browserAgentBrowser.get()),
20441
20758
  browserAgentDebugTools: config.browserAgentDebugTools.get(),
20442
20759
  browserAgentDemonstrate: config.browserAgentDemonstrate.get(),
20760
+ browserAgentAutoHeal: config.browserAgentAutoHeal.get(),
20443
20761
  browserAgentIdleClose: resolveBrowserAgentIdleClose(config.browserAgentIdleClose.get()),
20444
20762
  webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
20445
20763
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
@@ -20523,13 +20841,15 @@ function apply(ctx, config) {
20523
20841
  const browserAgentLive = {
20524
20842
  enabled: settings().browserAgentEnabled,
20525
20843
  browser: settings().browserAgentBrowser,
20526
- demonstrate: settings().browserAgentDemonstrate
20844
+ demonstrate: settings().browserAgentDemonstrate,
20845
+ autoHeal: settings().browserAgentAutoHeal
20527
20846
  };
20528
20847
  const browserAgent = installBrowserAgent(ctx, {
20529
20848
  enabled: () => browserAgentLive.enabled,
20530
20849
  browserPreference: () => browserAgentLive.browser,
20531
20850
  debugTools: () => settings().browserAgentDebugTools,
20532
20851
  demonstrate: () => settings().browserAgentDemonstrate,
20852
+ autoHeal: () => settings().browserAgentAutoHeal,
20533
20853
  idleClose: () => settings().browserAgentIdleClose,
20534
20854
  recipes: new DemoRecipeStore(join30(pluginDataPackageRoot, "demo-recipes.json")),
20535
20855
  profileRoot: pluginDataPackageRoot,
@@ -20599,6 +20919,7 @@ function apply(ctx, config) {
20599
20919
  browserAgentLive.enabled = cfg.browserAgentEnabled.get();
20600
20920
  browserAgentLive.browser = hostBrowserPreference(cfg.browserAgentBrowser.get());
20601
20921
  browserAgentLive.demonstrate = cfg.browserAgentDemonstrate.get();
20922
+ browserAgentLive.autoHeal = cfg.browserAgentAutoHeal.get();
20602
20923
  browserAgent.refresh();
20603
20924
  if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
20604
20925
  void browserAgent.alignToPreference().catch((error) => {