dsh-agent-enhancer 0.3.19 → 0.3.20

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
@@ -1995,6 +1995,21 @@ var PlaywrightDriver = class {
1995
1995
  tabId: this.tabIdFor(page)
1996
1996
  };
1997
1997
  }
1998
+ async resolveRefBySelector(selector) {
1999
+ const page = await this.requirePage();
2000
+ const raw = await page.evaluate(({ sel, attr }) => {
2001
+ try {
2002
+ const el = document.querySelector(sel);
2003
+ if (el === null) return null;
2004
+ return el.getAttribute(attr);
2005
+ } catch {
2006
+ return null;
2007
+ }
2008
+ }, { sel: selector, attr: PLAYWRIGHT_REF_ATTR }).catch(() => null);
2009
+ if (raw === null) return null;
2010
+ const ref = Number(raw);
2011
+ return Number.isFinite(ref) ? ref : null;
2012
+ }
1998
2013
  async press(key) {
1999
2014
  const page = await this.requirePage();
2000
2015
  await page.keyboard.press(key);
@@ -2729,26 +2744,49 @@ function classify(input) {
2729
2744
  function normalizeControlName(raw) {
2730
2745
  return raw.replace(/[\u200b-\u200d\ufeff]/gu, "").replace(/\s+/gu, " ").trim().toLowerCase();
2731
2746
  }
2732
- function matchDemoControl(nodes, role, name2) {
2747
+ function matchDemoControls(nodes, role, name2) {
2733
2748
  const wanted = normalizeControlName(name2);
2734
- if (wanted === "") return void 0;
2749
+ if (wanted === "") return [];
2735
2750
  const sameRole = nodes.filter((node) => node.role === role);
2736
- const exact = sameRole.find((node) => normalizeControlName(node.name) === wanted);
2737
- if (exact !== void 0) return exact;
2738
- const exactAnyRole = nodes.find((node) => normalizeControlName(node.name) === wanted);
2739
- if (exactAnyRole !== void 0) return exactAnyRole;
2740
- const partial = sameRole.filter((node) => {
2751
+ const exact = sameRole.filter((node) => normalizeControlName(node.name) === wanted);
2752
+ if (exact.length > 0) return exact;
2753
+ const exactAnyRole = nodes.filter((node) => normalizeControlName(node.name) === wanted);
2754
+ if (exactAnyRole.length > 0) return exactAnyRole;
2755
+ return sameRole.filter((node) => {
2741
2756
  const candidate = normalizeControlName(node.name);
2742
2757
  return candidate.includes(wanted) || wanted.includes(candidate);
2743
2758
  });
2744
- return partial.length === 1 ? partial[0] : void 0;
2759
+ }
2760
+ var CONTROL_ATTEMPTS = 3;
2761
+ var CONTROL_RETRY_MS = 600;
2762
+ var pause = (ms) => new Promise((resolve17) => {
2763
+ setTimeout(resolve17, ms);
2764
+ });
2765
+ async function locateControl(driver, selector, role, name2, retryDelayMs) {
2766
+ let lastUrl = "";
2767
+ for (let attempt = 0; attempt < CONTROL_ATTEMPTS; attempt += 1) {
2768
+ const snapshot = await driver.snapshot();
2769
+ lastUrl = snapshot.url;
2770
+ const candidates = matchDemoControls(snapshot.nodes, role, name2);
2771
+ if (candidates.length === 1) return { node: candidates[0] };
2772
+ if (candidates.length > 1) {
2773
+ const ref = typeof driver.resolveRefBySelector === "function" && (selector ?? "").trim() !== "" ? await driver.resolveRefBySelector(selector).catch(() => null) : null;
2774
+ const hit = ref === null ? void 0 : candidates.find((node) => node.ref === ref);
2775
+ if (hit !== void 0) return { node: hit };
2776
+ return {
2777
+ reason: `${candidates.length} controls match ${role} ${JSON.stringify(name2)} on ${snapshot.url}; the recorded selector does not identify one`
2778
+ };
2779
+ }
2780
+ if (attempt < CONTROL_ATTEMPTS - 1) await pause(retryDelayMs);
2781
+ }
2782
+ return { reason: `no control matching ${role} ${JSON.stringify(name2)} on ${lastUrl}` };
2745
2783
  }
2746
2784
  function replayObstacle(step) {
2747
2785
  if (step.kind !== "fill") return null;
2748
2786
  if (step.masked) return `secret field ${JSON.stringify(step.name)} was masked; type it yourself`;
2749
2787
  return null;
2750
2788
  }
2751
- async function performStep(driver, step) {
2789
+ async function performStep(driver, step, retryDelayMs = CONTROL_RETRY_MS) {
2752
2790
  switch (step.kind) {
2753
2791
  case "navigate": {
2754
2792
  const current = (await driver.snapshot()).url;
@@ -2757,26 +2795,19 @@ async function performStep(driver, step) {
2757
2795
  return { ok: true, url: result.url };
2758
2796
  }
2759
2797
  case "click": {
2760
- const snapshot = await driver.snapshot();
2761
- const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2762
- if (node === void 0) {
2763
- return {
2764
- ok: false,
2765
- reason: `no control matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2766
- };
2798
+ const located = await locateControl(driver, step.selector, step.role, step.name, retryDelayMs);
2799
+ if (located.node === void 0) {
2800
+ return { ok: false, reason: located.reason ?? "control not found" };
2767
2801
  }
2768
- const result = await driver.click(node.ref);
2802
+ const result = await driver.click(located.node.ref);
2769
2803
  return { ok: true, url: result.url };
2770
2804
  }
2771
2805
  case "fill": {
2772
- const snapshot = await driver.snapshot();
2773
- const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2774
- if (node === void 0) {
2775
- return {
2776
- ok: false,
2777
- reason: `no field matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2778
- };
2806
+ const located = await locateControl(driver, step.selector, step.role, step.name, retryDelayMs);
2807
+ if (located.node === void 0) {
2808
+ return { ok: false, reason: located.reason ?? "field not found" };
2779
2809
  }
2810
+ const node = located.node;
2780
2811
  if (step.role === "combobox") {
2781
2812
  const result2 = await driver.select(node.ref, step.value);
2782
2813
  return { ok: true, url: result2.url };
@@ -2808,7 +2839,8 @@ function samePage(a, b) {
2808
2839
  return a === b;
2809
2840
  }
2810
2841
  }
2811
- async function replayDemoSteps(driver, steps) {
2842
+ async function replayDemoSteps(driver, steps, options = {}) {
2843
+ const retryDelayMs = options.retryDelayMs ?? CONTROL_RETRY_MS;
2812
2844
  const lines = [];
2813
2845
  let currentTab;
2814
2846
  let url;
@@ -2883,7 +2915,7 @@ async function replayDemoSteps(driver, steps) {
2883
2915
  ...url === void 0 ? {} : { url }
2884
2916
  };
2885
2917
  }
2886
- const outcome = await performStep(driver, step).catch((error) => ({
2918
+ const outcome = await performStep(driver, step, retryDelayMs).catch((error) => ({
2887
2919
  ok: false,
2888
2920
  reason: error instanceof Error ? error.message : String(error)
2889
2921
  }));
@@ -2910,6 +2942,190 @@ async function replayDemoSteps(driver, steps) {
2910
2942
  };
2911
2943
  }
2912
2944
 
2945
+ // src/host/browser-agent/demo-recipes.ts
2946
+ import { mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "node:fs";
2947
+ import { dirname } from "node:path";
2948
+ var MAX_RECIPES = 20;
2949
+ var MAX_RECIPE_NAME = 60;
2950
+ var MAX_RECIPE_STEPS = 200;
2951
+ var FILE_VERSION = 1;
2952
+ function metaOf(recipe) {
2953
+ return {
2954
+ id: recipe.id,
2955
+ name: recipe.name,
2956
+ createdAt: recipe.createdAt,
2957
+ updatedAt: recipe.updatedAt,
2958
+ steps: recipe.steps.length,
2959
+ variables: recipe.variables
2960
+ };
2961
+ }
2962
+ var VAR_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
2963
+ var VAR_TOKEN = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
2964
+ function applyRecipeVars(steps, values) {
2965
+ const fill = (text3) => text3.replace(VAR_TOKEN, (match, name2) => values[name2] ?? match);
2966
+ return steps.map((step) => {
2967
+ if (step.kind === "navigate") {
2968
+ const url = fill(step.url);
2969
+ return url === step.url ? step : { ...step, url };
2970
+ }
2971
+ if (step.kind === "fill") {
2972
+ const value = fill(step.value);
2973
+ return value === step.value ? step : { ...step, value };
2974
+ }
2975
+ return step;
2976
+ });
2977
+ }
2978
+ function missingRecipeVars(recipe, values) {
2979
+ return recipe.variables.filter((variable) => (values[variable.name] ?? "").trim() === "").map((variable) => variable.name);
2980
+ }
2981
+ function sanitizeVariables(raw) {
2982
+ if (!Array.isArray(raw)) return [];
2983
+ return raw.filter((value) => {
2984
+ if (value === null || typeof value !== "object") return false;
2985
+ const name2 = value.name;
2986
+ return typeof name2 === "string" && VAR_NAME.test(name2);
2987
+ }).map((variable) => ({ name: variable.name, default: String(variable.default ?? "").slice(0, 500) }));
2988
+ }
2989
+ function isStep(value) {
2990
+ if (value === null || typeof value !== "object") return false;
2991
+ const kind = value.kind;
2992
+ return kind === "navigate" || kind === "click" || kind === "fill" || kind === "press";
2993
+ }
2994
+ function sanitizeRecipeSteps(raw) {
2995
+ if (!Array.isArray(raw)) return [];
2996
+ const steps = raw.filter(isStep).slice(0, MAX_RECIPE_STEPS);
2997
+ return sanitizeDemoSteps(steps).map((step) => {
2998
+ const { tabId: _volatileTabId, ...rest } = step;
2999
+ return rest;
3000
+ });
3001
+ }
3002
+ var DemoRecipeStore = class {
3003
+ constructor(filePath = null) {
3004
+ this.filePath = filePath;
3005
+ }
3006
+ filePath;
3007
+ memory = [];
3008
+ list() {
3009
+ return this.read().map(metaOf).sort((a, b) => b.updatedAt - a.updatedAt);
3010
+ }
3011
+ get(id) {
3012
+ return this.read().find((recipe) => recipe.id === id);
3013
+ }
3014
+ /** Save under `name`; the same name (case-insensitive) updates in place. */
3015
+ save(input) {
3016
+ const name2 = input.name.replace(/\s+/gu, " ").trim();
3017
+ if (name2 === "") return { ok: false, error: "\u6D41\u7A0B\u540D\u4E0D\u80FD\u4E3A\u7A7A" };
3018
+ if (name2.length > MAX_RECIPE_NAME) return { ok: false, error: `\u6D41\u7A0B\u540D\u6700\u957F ${MAX_RECIPE_NAME} \u4E2A\u5B57\u7B26` };
3019
+ const steps = sanitizeRecipeSteps(input.steps);
3020
+ if (steps.length === 0) return { ok: false, error: "\u8FD9\u6B21\u5F55\u5236\u6CA1\u6709\u53EF\u4FDD\u5B58\u7684\u6B65\u9AA4" };
3021
+ const now = input.now ?? Date.now();
3022
+ const recipes = this.read();
3023
+ const existing = recipes.find((recipe) => recipe.name.toLowerCase() === name2.toLowerCase());
3024
+ let saved;
3025
+ if (existing !== void 0) {
3026
+ saved = { ...existing, name: name2, steps, updatedAt: now };
3027
+ } else {
3028
+ if (recipes.length >= MAX_RECIPES) {
3029
+ return { ok: false, error: `\u6700\u591A\u4FDD\u5B58 ${MAX_RECIPES} \u4E2A\u6D41\u7A0B\uFF0C\u5148\u5220\u6389\u4E00\u4E2A` };
3030
+ }
3031
+ saved = {
3032
+ id: `r-${now.toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
3033
+ name: name2,
3034
+ createdAt: now,
3035
+ updatedAt: now,
3036
+ steps,
3037
+ variables: []
3038
+ };
3039
+ }
3040
+ const next = existing === void 0 ? [...recipes, saved] : recipes.map((recipe) => recipe.id === saved.id ? saved : recipe);
3041
+ this.write(next);
3042
+ return { ok: true, recipe: metaOf(saved) };
3043
+ }
3044
+ remove(id) {
3045
+ const recipes = this.read();
3046
+ const next = recipes.filter((recipe) => recipe.id !== id);
3047
+ if (next.length === recipes.length) return false;
3048
+ this.write(next);
3049
+ return true;
3050
+ }
3051
+ /** Rename without touching the steps; the new name must stay unique. */
3052
+ rename(input) {
3053
+ const name2 = input.name.replace(/\s+/gu, " ").trim();
3054
+ if (name2 === "") return { ok: false, error: "\u6D41\u7A0B\u540D\u4E0D\u80FD\u4E3A\u7A7A" };
3055
+ if (name2.length > MAX_RECIPE_NAME) return { ok: false, error: `\u6D41\u7A0B\u540D\u6700\u957F ${MAX_RECIPE_NAME} \u4E2A\u5B57\u7B26` };
3056
+ const recipes = this.read();
3057
+ const current = recipes.find((recipe) => recipe.id === input.id);
3058
+ if (current === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728" };
3059
+ const clash = recipes.find((recipe) => recipe.id !== current.id && recipe.name.toLowerCase() === name2.toLowerCase());
3060
+ if (clash !== void 0) return { ok: false, error: `\u5DF2\u7ECF\u6709\u53EB\u300C${clash.name}\u300D\u7684\u6D41\u7A0B` };
3061
+ const renamed = { ...current, name: name2, updatedAt: input.now ?? Date.now() };
3062
+ this.write(recipes.map((recipe) => recipe.id === current.id ? renamed : recipe));
3063
+ return { ok: true, recipe: metaOf(renamed) };
3064
+ }
3065
+ /**
3066
+ * Turn one fill step's literal into a `${name}` token, remembering the old
3067
+ * value as the default so the flow still runs unchanged.
3068
+ */
3069
+ 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
+ const recipes = this.read();
3075
+ const current = recipes.find((recipe) => recipe.id === input.id);
3076
+ if (current === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728" };
3077
+ const step = current.steps[input.index];
3078
+ if (step === void 0) return { ok: false, error: "\u6B65\u9AA4\u4E0D\u5B58\u5728" };
3079
+ if (step.kind !== "fill") return { ok: false, error: "\u53EA\u6709\u586B\u5199\u7C7B\u6B65\u9AA4\u53EF\u4EE5\u53D8\u6210\u53D8\u91CF" };
3080
+ if (step.masked) return { ok: false, error: "\u5BC6\u7801\u7C7B\u5B57\u6BB5\u4E0D\u80FD\u53D8\u6210\u53D8\u91CF" };
3081
+ if (new RegExp(VAR_TOKEN.source).test(step.value)) {
3082
+ return { ok: false, error: "\u8FD9\u4E00\u6B65\u5DF2\u7ECF\u662F\u53D8\u91CF\u4E86" };
3083
+ }
3084
+ if (current.variables.some((variable) => variable.name === name2)) {
3085
+ return { ok: false, error: "\u53D8\u91CF\u540D\u5DF2\u5B58\u5728" };
3086
+ }
3087
+ const token = "${" + name2 + "}";
3088
+ const steps = current.steps.map(
3089
+ (entry, index) => index === input.index && entry.kind === "fill" ? { ...entry, value: token } : entry
3090
+ );
3091
+ const variables = [...current.variables, { name: name2, default: step.value.slice(0, 500) }];
3092
+ const next = { ...current, steps, variables, updatedAt: input.now ?? Date.now() };
3093
+ this.write(recipes.map((recipe) => recipe.id === current.id ? next : recipe));
3094
+ return { ok: true, recipe: metaOf(next) };
3095
+ }
3096
+ read() {
3097
+ if (this.filePath === null) return this.memory;
3098
+ try {
3099
+ const parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
3100
+ if (parsed.version !== FILE_VERSION || !Array.isArray(parsed.recipes)) return [];
3101
+ return parsed.recipes.filter((recipe) => {
3102
+ if (recipe === null || typeof recipe !== "object") return false;
3103
+ if (typeof recipe.id !== "string" || typeof recipe.name !== "string") return false;
3104
+ 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);
3110
+ } catch {
3111
+ return [];
3112
+ }
3113
+ }
3114
+ write(recipes) {
3115
+ if (this.filePath === null) {
3116
+ this.memory = [...recipes];
3117
+ return;
3118
+ }
3119
+ try {
3120
+ mkdirSync2(dirname(this.filePath), { recursive: true });
3121
+ const shape = { version: FILE_VERSION, recipes };
3122
+ writeFileSync(this.filePath, `${JSON.stringify(shape, null, 2)}
3123
+ `, "utf8");
3124
+ } catch {
3125
+ }
3126
+ }
3127
+ };
3128
+
2913
3129
  // src/host/browser-agent/tools.ts
2914
3130
  import { defineTool } from "@deepseek-ai/dsh-tools";
2915
3131
  var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
@@ -4127,6 +4343,11 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4127
4343
  name: {
4128
4344
  type: "string",
4129
4345
  description: "Flow name for action=run. Case-insensitive; a unique part of the name is enough."
4346
+ },
4347
+ vars: {
4348
+ type: "object",
4349
+ additionalProperties: true,
4350
+ description: `Values for the flow's variables, e.g. {"from":"2026-11-01"}. Saved defaults are used for anything omitted.`
4130
4351
  }
4131
4352
  },
4132
4353
  async (args, exec) => {
@@ -4142,7 +4363,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4142
4363
  }
4143
4364
  return [
4144
4365
  `saved flows: ${rows.length}`,
4145
- ...rows.map((row) => `- ${row.name} (${row.steps} step(s))`),
4366
+ ...rows.map((row) => `- ${row.name} (${row.steps} step(s)${row.variables.length === 0 ? "" : `; vars: ${row.variables.map((variable) => variable.name).join(", ")}`})`),
4146
4367
  'Action: run one with browser_demo_recipes { action: "run", name: "<name>" }.'
4147
4368
  ].join("\n");
4148
4369
  }
@@ -4157,6 +4378,15 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4157
4378
  }
4158
4379
  const recipe = store.get(meta.id);
4159
4380
  if (recipe === void 0) throw new Error("The saved flow disappeared; list again.");
4381
+ 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.`);
4388
+ }
4389
+ const replaySteps = applyRecipeVars(recipe.steps, values);
4160
4390
  const sessionId = sessionIdOf(exec);
4161
4391
  await ensureConnected();
4162
4392
  await ensureSessionTab(sessionId);
@@ -4167,7 +4397,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4167
4397
  `\u8FD0\u884C\u5DF2\u4FDD\u5B58\u6D41\u7A0B\u300C${recipe.name}\u300D\uFF08${recipe.steps.length} \u6B65\uFF09`,
4168
4398
  firstUrl
4169
4399
  );
4170
- const outcome = await replayDemoSteps(driverOf(options), recipe.steps);
4400
+ const outcome = await replayDemoSteps(driverOf(options), replaySteps);
4171
4401
  const ranAll = outcome.status === "done";
4172
4402
  options.sessions.record({
4173
4403
  sessionId,
@@ -4639,36 +4869,72 @@ function installBrowserAgent(ctx, options) {
4639
4869
  });
4640
4870
  return removed ? { ok: true, recipes: recipes.list() } : { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4641
4871
  }
4642
- if (input.action === "save") {
4643
- if (options.demonstrate?.() !== true) {
4644
- return { ok: false, error: "\u6F14\u793A\u5F55\u5236\u672A\u5F00\u542F\uFF1A\u8BBE\u7F6E \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent" };
4645
- }
4646
- if (lastDemoSteps.length === 0) {
4647
- return { ok: false, error: "\u5148\u5F55\u5236\u4E00\u6B21\uFF0C\u518D\u4FDD\u5B58\u4E3A\u6D41\u7A0B", recipes: recipes.list() };
4648
- }
4649
- const saved = recipes.save({ name: input.name ?? "", steps: lastDemoSteps });
4650
- if (!saved.ok) return { ok: false, error: saved.error, recipes: recipes.list() };
4872
+ if (input.action === "steps") {
4873
+ const recipe2 = recipes.get(input.id ?? "");
4874
+ if (recipe2 === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4875
+ return {
4876
+ ok: true,
4877
+ recipes: recipes.list(),
4878
+ lines: recipe2.steps.map((step, index) => `${index + 1}. ${describeDemoStep(step)}`),
4879
+ steps: recipe2.steps.map((step, index) => ({
4880
+ index,
4881
+ kind: step.kind,
4882
+ label: describeDemoStep(step),
4883
+ canParameterize: step.kind === "fill" && !step.masked && !/\$\{[A-Za-z_][A-Za-z0-9_]*\}/.test(step.value)
4884
+ }))
4885
+ };
4886
+ }
4887
+ if (input.action === "parameterize") {
4888
+ const result = recipes.parameterize({
4889
+ id: input.id ?? "",
4890
+ index: input.index ?? -1,
4891
+ name: input.name ?? ""
4892
+ });
4893
+ if (!result.ok) return { ok: false, error: result.error, recipes: recipes.list() };
4651
4894
  sessions.record({
4652
4895
  sessionId: "sidebar",
4653
4896
  tool: "browser_demo_recipe",
4654
- summary: `Saved demonstration recipe "${saved.recipe.name}" (${saved.recipe.steps} step(s))`,
4897
+ summary: `Parameterized demonstration recipe "${result.recipe.name}"`,
4655
4898
  outcome: "ok"
4656
4899
  });
4657
- return { ok: true, recipe: saved.recipe, recipes: recipes.list() };
4900
+ return { ok: true, recipe: result.recipe, recipes: recipes.list() };
4901
+ }
4902
+ if (input.action === "rename") {
4903
+ const renamed = recipes.rename({ id: input.id ?? "", name: input.name ?? "" });
4904
+ if (!renamed.ok) return { ok: false, error: renamed.error, recipes: recipes.list() };
4905
+ sessions.record({
4906
+ sessionId: "sidebar",
4907
+ tool: "browser_demo_recipe",
4908
+ summary: `Renamed demonstration recipe to "${renamed.recipe.name}"`,
4909
+ outcome: "ok"
4910
+ });
4911
+ return { ok: true, recipe: renamed.recipe, recipes: recipes.list() };
4658
4912
  }
4659
4913
  const recipe = recipes.get(input.id ?? "");
4660
4914
  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) {
4920
+ return {
4921
+ ok: false,
4922
+ error: `\u7F3A\u5C11\u53D8\u91CF\uFF1A${missing.join("\u3001")}`,
4923
+ recipes: recipes.list()
4924
+ };
4925
+ }
4926
+ const steps = applyRecipeVars(recipe.steps, values);
4661
4927
  const driver = activeDriver;
4662
4928
  if (driver === null) return { ok: false, error: "Browser agent is not running", recipes: recipes.list() };
4663
4929
  const aligned = await alignToPreference().catch(() => ({ ok: true, error: void 0 }));
4664
4930
  if (!aligned.ok) return { ok: false, error: aligned.error ?? "Browser agent failed to start", recipes: recipes.list() };
4665
- const outcome = await replayDemoSteps(driver, recipe.steps).catch((error) => ({
4931
+ const outcome = await replayDemoSteps(driver, steps).catch((error) => ({
4666
4932
  status: "blocked",
4667
4933
  performed: 0,
4668
- total: recipe.steps.length,
4934
+ total: steps.length,
4669
4935
  lines: [],
4670
4936
  reason: error instanceof Error ? error.message : String(error),
4671
- pending: [...recipe.steps]
4937
+ pending: [...steps]
4672
4938
  }));
4673
4939
  const ranAll = outcome.status === "done";
4674
4940
  sessions.record({
@@ -4837,106 +5103,6 @@ function installBrowserAgent(ctx, options) {
4837
5103
  };
4838
5104
  }
4839
5105
 
4840
- // src/host/browser-agent/demo-recipes.ts
4841
- import { mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "node:fs";
4842
- import { dirname } from "node:path";
4843
- var MAX_RECIPES = 20;
4844
- var MAX_RECIPE_NAME = 60;
4845
- var MAX_RECIPE_STEPS = 200;
4846
- var FILE_VERSION = 1;
4847
- function metaOf(recipe) {
4848
- return {
4849
- id: recipe.id,
4850
- name: recipe.name,
4851
- createdAt: recipe.createdAt,
4852
- updatedAt: recipe.updatedAt,
4853
- steps: recipe.steps.length
4854
- };
4855
- }
4856
- function isStep(value) {
4857
- if (value === null || typeof value !== "object") return false;
4858
- const kind = value.kind;
4859
- return kind === "navigate" || kind === "click" || kind === "fill" || kind === "press";
4860
- }
4861
- function sanitizeRecipeSteps(raw) {
4862
- if (!Array.isArray(raw)) return [];
4863
- const steps = raw.filter(isStep).slice(0, MAX_RECIPE_STEPS);
4864
- return sanitizeDemoSteps(steps).map((step) => {
4865
- const { tabId: _volatileTabId, ...rest } = step;
4866
- return rest;
4867
- });
4868
- }
4869
- var DemoRecipeStore = class {
4870
- constructor(filePath = null) {
4871
- this.filePath = filePath;
4872
- }
4873
- filePath;
4874
- memory = [];
4875
- list() {
4876
- return this.read().map(metaOf).sort((a, b) => b.updatedAt - a.updatedAt);
4877
- }
4878
- get(id) {
4879
- return this.read().find((recipe) => recipe.id === id);
4880
- }
4881
- /** Save under `name`; the same name (case-insensitive) updates in place. */
4882
- save(input) {
4883
- const name2 = input.name.replace(/\s+/gu, " ").trim();
4884
- if (name2 === "") return { ok: false, error: "\u6D41\u7A0B\u540D\u4E0D\u80FD\u4E3A\u7A7A" };
4885
- if (name2.length > MAX_RECIPE_NAME) return { ok: false, error: `\u6D41\u7A0B\u540D\u6700\u957F ${MAX_RECIPE_NAME} \u4E2A\u5B57\u7B26` };
4886
- const steps = sanitizeRecipeSteps(input.steps);
4887
- if (steps.length === 0) return { ok: false, error: "\u8FD9\u6B21\u5F55\u5236\u6CA1\u6709\u53EF\u4FDD\u5B58\u7684\u6B65\u9AA4" };
4888
- const now = input.now ?? Date.now();
4889
- const recipes = this.read();
4890
- const existing = recipes.find((recipe) => recipe.name.toLowerCase() === name2.toLowerCase());
4891
- let saved;
4892
- if (existing !== void 0) {
4893
- saved = { ...existing, name: name2, steps, updatedAt: now };
4894
- } else {
4895
- if (recipes.length >= MAX_RECIPES) {
4896
- return { ok: false, error: `\u6700\u591A\u4FDD\u5B58 ${MAX_RECIPES} \u4E2A\u6D41\u7A0B\uFF0C\u5148\u5220\u6389\u4E00\u4E2A` };
4897
- }
4898
- saved = { id: `r-${now.toString(36)}-${Math.random().toString(36).slice(2, 7)}`, name: name2, createdAt: now, updatedAt: now, steps };
4899
- }
4900
- const next = existing === void 0 ? [...recipes, saved] : recipes.map((recipe) => recipe.id === saved.id ? saved : recipe);
4901
- this.write(next);
4902
- return { ok: true, recipe: metaOf(saved) };
4903
- }
4904
- remove(id) {
4905
- const recipes = this.read();
4906
- const next = recipes.filter((recipe) => recipe.id !== id);
4907
- if (next.length === recipes.length) return false;
4908
- this.write(next);
4909
- return true;
4910
- }
4911
- read() {
4912
- if (this.filePath === null) return this.memory;
4913
- try {
4914
- const parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
4915
- if (parsed.version !== FILE_VERSION || !Array.isArray(parsed.recipes)) return [];
4916
- return parsed.recipes.filter((recipe) => {
4917
- if (recipe === null || typeof recipe !== "object") return false;
4918
- if (typeof recipe.id !== "string" || typeof recipe.name !== "string") return false;
4919
- return typeof recipe.createdAt === "number" && typeof recipe.updatedAt === "number";
4920
- }).map((recipe) => ({ ...recipe, steps: sanitizeRecipeSteps(recipe.steps) })).filter((recipe) => recipe.steps.length > 0).slice(0, MAX_RECIPES);
4921
- } catch {
4922
- return [];
4923
- }
4924
- }
4925
- write(recipes) {
4926
- if (this.filePath === null) {
4927
- this.memory = [...recipes];
4928
- return;
4929
- }
4930
- try {
4931
- mkdirSync2(dirname(this.filePath), { recursive: true });
4932
- const shape = { version: FILE_VERSION, recipes };
4933
- writeFileSync(this.filePath, `${JSON.stringify(shape, null, 2)}
4934
- `, "utf8");
4935
- } catch {
4936
- }
4937
- }
4938
- };
4939
-
4940
5106
  // src/errors.ts
4941
5107
  var MESSAGES = {
4942
5108
  MODEL_UNAVAILABLE: "No model is available for Agent Enhance",
@@ -17003,18 +17169,37 @@ var browserAgentThumbnailResultCodec = codec(
17003
17169
  "dsh-agent-enhancer#BrowserAgentThumbnailResult",
17004
17170
  browserAgentThumbnailResultSchema
17005
17171
  );
17172
+ var demoRecipeVariableSchema = z4.strictObject({
17173
+ name: z4.string().min(1),
17174
+ default: z4.string()
17175
+ });
17006
17176
  var demoRecipeMetaSchema = z4.strictObject({
17007
17177
  id: z4.string().min(1),
17008
17178
  name: z4.string().min(1),
17009
17179
  createdAt: z4.number(),
17010
17180
  updatedAt: z4.number(),
17011
- steps: z4.number().int()
17181
+ steps: z4.number().int(),
17182
+ variables: z4.array(demoRecipeVariableSchema)
17183
+ });
17184
+ var demoRecipeStepSchema = z4.strictObject({
17185
+ index: z4.number().int(),
17186
+ kind: z4.enum(["navigate", "click", "fill", "press"]),
17187
+ label: z4.string(),
17188
+ /** A fill step that can become a `${name}` placeholder. */
17189
+ canParameterize: z4.boolean()
17012
17190
  });
17013
17191
  var browserAgentDemoRecipesRequestSchema = z4.discriminatedUnion("action", [
17014
17192
  z4.strictObject({ action: z4.literal("list") }),
17015
17193
  z4.strictObject({ action: z4.literal("save"), name: z4.string() }),
17016
- z4.strictObject({ action: z4.literal("run"), id: z4.string().min(1) }),
17017
- z4.strictObject({ action: z4.literal("delete"), id: z4.string().min(1) })
17194
+ z4.strictObject({
17195
+ action: z4.literal("run"),
17196
+ id: z4.string().min(1),
17197
+ vars: z4.record(z4.string(), z4.string()).optional()
17198
+ }),
17199
+ z4.strictObject({ action: z4.literal("delete"), id: z4.string().min(1) }),
17200
+ z4.strictObject({ action: z4.literal("steps"), id: z4.string().min(1) }),
17201
+ 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() })
17018
17203
  ]);
17019
17204
  var browserAgentDemoRecipesRequestCodec = codec(
17020
17205
  "dsh-agent-enhancer#BrowserAgentDemoRecipesRequest",
@@ -17026,6 +17211,8 @@ var browserAgentDemoRecipesResultSchema = z4.strictObject({
17026
17211
  recipe: demoRecipeMetaSchema.optional(),
17027
17212
  /** Replay lines when running a recipe (`1. ok …`). */
17028
17213
  lines: z4.array(z4.string()).optional(),
17214
+ /** Step metadata for action=steps (index + what the row can do). */
17215
+ steps: z4.array(demoRecipeStepSchema).optional(),
17029
17216
  /** 1-based step where a replay stopped. */
17030
17217
  stoppedAt: z4.number().int().optional(),
17031
17218
  reason: z4.string().optional(),
@@ -19508,13 +19695,20 @@ var AgentEnhancerService = class extends TypertRemoteService {
19508
19695
  const result = await runtime.demoRecipes({
19509
19696
  action: request.action,
19510
19697
  ..."name" in request ? { name: request.name } : {},
19511
- ..."id" in request ? { id: request.id } : {}
19698
+ ..."id" in request ? { id: request.id } : {},
19699
+ ..."index" in request ? { index: request.index } : {},
19700
+ ..."vars" in request && request.vars !== void 0 ? { vars: request.vars } : {}
19701
+ });
19702
+ const meta = (recipe) => ({
19703
+ ...recipe,
19704
+ variables: recipe.variables.map((variable) => ({ ...variable }))
19512
19705
  });
19513
19706
  return {
19514
19707
  ok: result.ok,
19515
- ...result.recipes === void 0 ? {} : { recipes: result.recipes.map((recipe) => ({ ...recipe })) },
19516
- ...result.recipe === void 0 ? {} : { recipe: { ...result.recipe } },
19708
+ ...result.recipes === void 0 ? {} : { recipes: result.recipes.map(meta) },
19709
+ ...result.recipe === void 0 ? {} : { recipe: meta(result.recipe) },
19517
19710
  ...result.lines === void 0 ? {} : { lines: [...result.lines] },
19711
+ ...result.steps === void 0 ? {} : { steps: result.steps.map((step) => ({ ...step })) },
19518
19712
  ...result.stoppedAt === void 0 ? {} : { stoppedAt: result.stoppedAt },
19519
19713
  ...result.reason === void 0 ? {} : { reason: result.reason },
19520
19714
  ...result.error === void 0 ? {} : { error: result.error }