dsh-agent-enhancer 0.3.18 → 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
@@ -1959,6 +1959,57 @@ var PlaywrightDriver = class {
1959
1959
  tabId: this.tabIdFor(page)
1960
1960
  };
1961
1961
  }
1962
+ async select(ref, value) {
1963
+ const page = await this.requirePage();
1964
+ const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
1965
+ if (await locator.count().catch(() => 0) === 0) {
1966
+ throw new Error(`Ref ${ref} is not stamped in the DOM; call browser_snapshot again`);
1967
+ }
1968
+ await locator.selectOption({ label: value }, { timeout: 5e3 }).catch(async () => {
1969
+ await locator.selectOption(value, { timeout: 5e3 });
1970
+ });
1971
+ return {
1972
+ url: page.url(),
1973
+ title: await page.title().catch(() => ""),
1974
+ changed: false,
1975
+ tabId: this.tabIdFor(page)
1976
+ };
1977
+ }
1978
+ async check(ref, checked) {
1979
+ const page = await this.requirePage();
1980
+ const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
1981
+ if (await locator.count().catch(() => 0) === 0) {
1982
+ throw new Error(`Ref ${ref} is not stamped in the DOM; call browser_snapshot again`);
1983
+ }
1984
+ const tag = await locator.evaluate((el) => el.tagName.toLowerCase()).catch(() => "");
1985
+ if (tag === "input" && checked) await locator.check({ timeout: 3e3 }).catch(() => locator.click({ timeout: 3e3 }));
1986
+ else if (tag === "input") await locator.uncheck({ timeout: 3e3 }).catch(() => locator.click({ timeout: 3e3 }));
1987
+ else {
1988
+ const state = await locator.getAttribute("aria-checked").catch(() => null);
1989
+ if (state === null || state === "true" !== checked) await locator.click({ timeout: 3e3 });
1990
+ }
1991
+ return {
1992
+ url: page.url(),
1993
+ title: await page.title().catch(() => ""),
1994
+ changed: false,
1995
+ tabId: this.tabIdFor(page)
1996
+ };
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
+ }
1962
2013
  async press(key) {
1963
2014
  const page = await this.requirePage();
1964
2015
  await page.keyboard.press(key);
@@ -2693,30 +2744,49 @@ function classify(input) {
2693
2744
  function normalizeControlName(raw) {
2694
2745
  return raw.replace(/[\u200b-\u200d\ufeff]/gu, "").replace(/\s+/gu, " ").trim().toLowerCase();
2695
2746
  }
2696
- function matchDemoControl(nodes, role, name2) {
2747
+ function matchDemoControls(nodes, role, name2) {
2697
2748
  const wanted = normalizeControlName(name2);
2698
- if (wanted === "") return void 0;
2749
+ if (wanted === "") return [];
2699
2750
  const sameRole = nodes.filter((node) => node.role === role);
2700
- const exact = sameRole.find((node) => normalizeControlName(node.name) === wanted);
2701
- if (exact !== void 0) return exact;
2702
- const exactAnyRole = nodes.find((node) => normalizeControlName(node.name) === wanted);
2703
- if (exactAnyRole !== void 0) return exactAnyRole;
2704
- const partial = sameRole.filter((node) => {
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) => {
2705
2756
  const candidate = normalizeControlName(node.name);
2706
2757
  return candidate.includes(wanted) || wanted.includes(candidate);
2707
2758
  });
2708
- 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}` };
2709
2783
  }
2710
2784
  function replayObstacle(step) {
2711
2785
  if (step.kind !== "fill") return null;
2712
2786
  if (step.masked) return `secret field ${JSON.stringify(step.name)} was masked; type it yourself`;
2713
- if (step.role === "combobox") return `select ${JSON.stringify(step.name)} cannot be replayed by name`;
2714
- if (step.role === "checkbox" || step.role === "radio") {
2715
- return `${step.role} ${JSON.stringify(step.name)} cannot be replayed by name (click it, then continue)`;
2716
- }
2717
2787
  return null;
2718
2788
  }
2719
- async function performStep(driver, step) {
2789
+ async function performStep(driver, step, retryDelayMs = CONTROL_RETRY_MS) {
2720
2790
  switch (step.kind) {
2721
2791
  case "navigate": {
2722
2792
  const current = (await driver.snapshot()).url;
@@ -2725,25 +2795,26 @@ async function performStep(driver, step) {
2725
2795
  return { ok: true, url: result.url };
2726
2796
  }
2727
2797
  case "click": {
2728
- const snapshot = await driver.snapshot();
2729
- const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2730
- if (node === void 0) {
2731
- return {
2732
- ok: false,
2733
- reason: `no control matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2734
- };
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" };
2735
2801
  }
2736
- const result = await driver.click(node.ref);
2802
+ const result = await driver.click(located.node.ref);
2737
2803
  return { ok: true, url: result.url };
2738
2804
  }
2739
2805
  case "fill": {
2740
- const snapshot = await driver.snapshot();
2741
- const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2742
- if (node === void 0) {
2743
- return {
2744
- ok: false,
2745
- reason: `no field matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2746
- };
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" };
2809
+ }
2810
+ const node = located.node;
2811
+ if (step.role === "combobox") {
2812
+ const result2 = await driver.select(node.ref, step.value);
2813
+ return { ok: true, url: result2.url };
2814
+ }
2815
+ if (step.role === "checkbox" || step.role === "radio") {
2816
+ const result2 = await driver.check(node.ref, step.checked ?? step.value === "on");
2817
+ return { ok: true, url: result2.url };
2747
2818
  }
2748
2819
  const result = await driver.type(node.ref, step.value);
2749
2820
  return { ok: true, url: result.url };
@@ -2768,7 +2839,8 @@ function samePage(a, b) {
2768
2839
  return a === b;
2769
2840
  }
2770
2841
  }
2771
- async function replayDemoSteps(driver, steps) {
2842
+ async function replayDemoSteps(driver, steps, options = {}) {
2843
+ const retryDelayMs = options.retryDelayMs ?? CONTROL_RETRY_MS;
2772
2844
  const lines = [];
2773
2845
  let currentTab;
2774
2846
  let url;
@@ -2843,7 +2915,7 @@ async function replayDemoSteps(driver, steps) {
2843
2915
  ...url === void 0 ? {} : { url }
2844
2916
  };
2845
2917
  }
2846
- const outcome = await performStep(driver, step).catch((error) => ({
2918
+ const outcome = await performStep(driver, step, retryDelayMs).catch((error) => ({
2847
2919
  ok: false,
2848
2920
  reason: error instanceof Error ? error.message : String(error)
2849
2921
  }));
@@ -2870,6 +2942,190 @@ async function replayDemoSteps(driver, steps) {
2870
2942
  };
2871
2943
  }
2872
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
+
2873
3129
  // src/host/browser-agent/tools.ts
2874
3130
  import { defineTool } from "@deepseek-ai/dsh-tools";
2875
3131
  var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
@@ -4075,6 +4331,101 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4075
4331
  },
4076
4332
  HUMAN_WAIT_TIMEOUT_MS
4077
4333
  )));
4334
+ disposers.push(ctx.tools.register(textTool(
4335
+ "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.',
4337
+ {
4338
+ action: {
4339
+ type: "string",
4340
+ required: true,
4341
+ description: '"list" to show saved flows, "run" to replay one.'
4342
+ },
4343
+ name: {
4344
+ type: "string",
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.`
4351
+ }
4352
+ },
4353
+ async (args, exec) => {
4354
+ guardEnabled();
4355
+ requireDemonstrate();
4356
+ const store = options.recipes;
4357
+ if (store === void 0) throw new Error("recipe store unavailable");
4358
+ const action = String(args.action ?? "").trim().toLowerCase();
4359
+ const rows = store.list();
4360
+ if (action === "list") {
4361
+ if (rows.length === 0) {
4362
+ return "saved flows: 0\nAction: none yet \u2014 the user can record a demonstration and save it in the sidebar, then retry.";
4363
+ }
4364
+ 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(", ")}`})`),
4367
+ 'Action: run one with browser_demo_recipes { action: "run", name: "<name>" }.'
4368
+ ].join("\n");
4369
+ }
4370
+ if (action !== "run") throw new Error('action must be "list" or "run"');
4371
+ const wanted = String(args.name ?? "").trim();
4372
+ if (wanted === "") throw new Error("name is required for action=run");
4373
+ const exact = rows.find((row) => row.name.toLowerCase() === wanted.toLowerCase());
4374
+ const partial = rows.filter((row) => row.name.toLowerCase().includes(wanted.toLowerCase()));
4375
+ const meta = exact ?? (partial.length === 1 ? partial[0] : void 0);
4376
+ if (meta === void 0) {
4377
+ throw new Error(rows.length === 0 ? "No saved flows yet; the user can save one from the sidebar demonstration panel." : `No unique saved flow matching "${wanted}"; saved: ${rows.map((row) => row.name).join(", ")}`);
4378
+ }
4379
+ const recipe = store.get(meta.id);
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);
4390
+ const sessionId = sessionIdOf(exec);
4391
+ await ensureConnected();
4392
+ await ensureSessionTab(sessionId);
4393
+ const firstUrl = recipe.steps.find((step) => step.tabUrl !== void 0)?.tabUrl;
4394
+ await requireMutation(
4395
+ exec,
4396
+ "browser_demo_recipes",
4397
+ `\u8FD0\u884C\u5DF2\u4FDD\u5B58\u6D41\u7A0B\u300C${recipe.name}\u300D\uFF08${recipe.steps.length} \u6B65\uFF09`,
4398
+ firstUrl
4399
+ );
4400
+ const outcome = await replayDemoSteps(driverOf(options), replaySteps);
4401
+ const ranAll = outcome.status === "done";
4402
+ options.sessions.record({
4403
+ sessionId,
4404
+ tool: "browser_demo_recipes",
4405
+ summary: `Ran saved flow "${recipe.name}" (${outcome.performed}/${outcome.total}${ranAll ? "" : ", stopped"})`,
4406
+ outcome: ranAll ? "ok" : "error"
4407
+ });
4408
+ if (ranAll) {
4409
+ return [
4410
+ `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
4411
+ ...outcome.lines,
4412
+ `url: ${outcome.url}`,
4413
+ "Action: the flow ran to the end. Report what changed on screen; browser_snapshot if you need the new page."
4414
+ ].join("\n");
4415
+ }
4416
+ const pending = outcome.pending.map((step, offset) => {
4417
+ const n = outcome.performed + offset + 1;
4418
+ return `${n}. todo ${describeDemoStep(step)}`;
4419
+ });
4420
+ return [
4421
+ `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
4422
+ ...outcome.lines,
4423
+ `stopped at step ${outcome.performed + 1}: ${outcome.reason}`,
4424
+ ...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."
4426
+ ].join("\n");
4427
+ }
4428
+ )));
4078
4429
  disposers.push(ctx.tools.register(textTool(
4079
4430
  "browser_list_tabs",
4080
4431
  "List open browser tabs (id, title, url, active, bound). Read-only; no approval. Use with browser_follow_tab to bind this session to another tab.",
@@ -4285,6 +4636,7 @@ function installBrowserAgent(ctx, options) {
4285
4636
  onDemonstration: (steps) => {
4286
4637
  lastDemoSteps = steps;
4287
4638
  },
4639
+ ...recipes === void 0 ? {} : { recipes },
4288
4640
  diagnosis: diagnoseNow,
4289
4641
  // Gate on settings only — `active` flips false during driver align and
4290
4642
  // must not make browser_* look "disabled" mid-turn.
@@ -4517,36 +4869,72 @@ function installBrowserAgent(ctx, options) {
4517
4869
  });
4518
4870
  return removed ? { ok: true, recipes: recipes.list() } : { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4519
4871
  }
4520
- if (input.action === "save") {
4521
- if (options.demonstrate?.() !== true) {
4522
- return { ok: false, error: "\u6F14\u793A\u5F55\u5236\u672A\u5F00\u542F\uFF1A\u8BBE\u7F6E \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent" };
4523
- }
4524
- if (lastDemoSteps.length === 0) {
4525
- return { ok: false, error: "\u5148\u5F55\u5236\u4E00\u6B21\uFF0C\u518D\u4FDD\u5B58\u4E3A\u6D41\u7A0B", recipes: recipes.list() };
4526
- }
4527
- const saved = recipes.save({ name: input.name ?? "", steps: lastDemoSteps });
4528
- if (!saved.ok) return { ok: false, error: saved.error, recipes: recipes.list() };
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() };
4894
+ sessions.record({
4895
+ sessionId: "sidebar",
4896
+ tool: "browser_demo_recipe",
4897
+ summary: `Parameterized demonstration recipe "${result.recipe.name}"`,
4898
+ outcome: "ok"
4899
+ });
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() };
4529
4905
  sessions.record({
4530
4906
  sessionId: "sidebar",
4531
4907
  tool: "browser_demo_recipe",
4532
- summary: `Saved demonstration recipe "${saved.recipe.name}" (${saved.recipe.steps} step(s))`,
4908
+ summary: `Renamed demonstration recipe to "${renamed.recipe.name}"`,
4533
4909
  outcome: "ok"
4534
4910
  });
4535
- return { ok: true, recipe: saved.recipe, recipes: recipes.list() };
4911
+ return { ok: true, recipe: renamed.recipe, recipes: recipes.list() };
4536
4912
  }
4537
4913
  const recipe = recipes.get(input.id ?? "");
4538
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);
4539
4927
  const driver = activeDriver;
4540
4928
  if (driver === null) return { ok: false, error: "Browser agent is not running", recipes: recipes.list() };
4541
4929
  const aligned = await alignToPreference().catch(() => ({ ok: true, error: void 0 }));
4542
4930
  if (!aligned.ok) return { ok: false, error: aligned.error ?? "Browser agent failed to start", recipes: recipes.list() };
4543
- const outcome = await replayDemoSteps(driver, recipe.steps).catch((error) => ({
4931
+ const outcome = await replayDemoSteps(driver, steps).catch((error) => ({
4544
4932
  status: "blocked",
4545
4933
  performed: 0,
4546
- total: recipe.steps.length,
4934
+ total: steps.length,
4547
4935
  lines: [],
4548
4936
  reason: error instanceof Error ? error.message : String(error),
4549
- pending: [...recipe.steps]
4937
+ pending: [...steps]
4550
4938
  }));
4551
4939
  const ranAll = outcome.status === "done";
4552
4940
  sessions.record({
@@ -4715,106 +5103,6 @@ function installBrowserAgent(ctx, options) {
4715
5103
  };
4716
5104
  }
4717
5105
 
4718
- // src/host/browser-agent/demo-recipes.ts
4719
- import { mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "node:fs";
4720
- import { dirname } from "node:path";
4721
- var MAX_RECIPES = 20;
4722
- var MAX_RECIPE_NAME = 60;
4723
- var MAX_RECIPE_STEPS = 200;
4724
- var FILE_VERSION = 1;
4725
- function metaOf(recipe) {
4726
- return {
4727
- id: recipe.id,
4728
- name: recipe.name,
4729
- createdAt: recipe.createdAt,
4730
- updatedAt: recipe.updatedAt,
4731
- steps: recipe.steps.length
4732
- };
4733
- }
4734
- function isStep(value) {
4735
- if (value === null || typeof value !== "object") return false;
4736
- const kind = value.kind;
4737
- return kind === "navigate" || kind === "click" || kind === "fill" || kind === "press";
4738
- }
4739
- function sanitizeRecipeSteps(raw) {
4740
- if (!Array.isArray(raw)) return [];
4741
- const steps = raw.filter(isStep).slice(0, MAX_RECIPE_STEPS);
4742
- return sanitizeDemoSteps(steps).map((step) => {
4743
- const { tabId: _volatileTabId, ...rest } = step;
4744
- return rest;
4745
- });
4746
- }
4747
- var DemoRecipeStore = class {
4748
- constructor(filePath = null) {
4749
- this.filePath = filePath;
4750
- }
4751
- filePath;
4752
- memory = [];
4753
- list() {
4754
- return this.read().map(metaOf).sort((a, b) => b.updatedAt - a.updatedAt);
4755
- }
4756
- get(id) {
4757
- return this.read().find((recipe) => recipe.id === id);
4758
- }
4759
- /** Save under `name`; the same name (case-insensitive) updates in place. */
4760
- save(input) {
4761
- const name2 = input.name.replace(/\s+/gu, " ").trim();
4762
- if (name2 === "") return { ok: false, error: "\u6D41\u7A0B\u540D\u4E0D\u80FD\u4E3A\u7A7A" };
4763
- if (name2.length > MAX_RECIPE_NAME) return { ok: false, error: `\u6D41\u7A0B\u540D\u6700\u957F ${MAX_RECIPE_NAME} \u4E2A\u5B57\u7B26` };
4764
- const steps = sanitizeRecipeSteps(input.steps);
4765
- if (steps.length === 0) return { ok: false, error: "\u8FD9\u6B21\u5F55\u5236\u6CA1\u6709\u53EF\u4FDD\u5B58\u7684\u6B65\u9AA4" };
4766
- const now = input.now ?? Date.now();
4767
- const recipes = this.read();
4768
- const existing = recipes.find((recipe) => recipe.name.toLowerCase() === name2.toLowerCase());
4769
- let saved;
4770
- if (existing !== void 0) {
4771
- saved = { ...existing, name: name2, steps, updatedAt: now };
4772
- } else {
4773
- if (recipes.length >= MAX_RECIPES) {
4774
- return { ok: false, error: `\u6700\u591A\u4FDD\u5B58 ${MAX_RECIPES} \u4E2A\u6D41\u7A0B\uFF0C\u5148\u5220\u6389\u4E00\u4E2A` };
4775
- }
4776
- saved = { id: `r-${now.toString(36)}-${Math.random().toString(36).slice(2, 7)}`, name: name2, createdAt: now, updatedAt: now, steps };
4777
- }
4778
- const next = existing === void 0 ? [...recipes, saved] : recipes.map((recipe) => recipe.id === saved.id ? saved : recipe);
4779
- this.write(next);
4780
- return { ok: true, recipe: metaOf(saved) };
4781
- }
4782
- remove(id) {
4783
- const recipes = this.read();
4784
- const next = recipes.filter((recipe) => recipe.id !== id);
4785
- if (next.length === recipes.length) return false;
4786
- this.write(next);
4787
- return true;
4788
- }
4789
- read() {
4790
- if (this.filePath === null) return this.memory;
4791
- try {
4792
- const parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
4793
- if (parsed.version !== FILE_VERSION || !Array.isArray(parsed.recipes)) return [];
4794
- return parsed.recipes.filter((recipe) => {
4795
- if (recipe === null || typeof recipe !== "object") return false;
4796
- if (typeof recipe.id !== "string" || typeof recipe.name !== "string") return false;
4797
- return typeof recipe.createdAt === "number" && typeof recipe.updatedAt === "number";
4798
- }).map((recipe) => ({ ...recipe, steps: sanitizeRecipeSteps(recipe.steps) })).filter((recipe) => recipe.steps.length > 0).slice(0, MAX_RECIPES);
4799
- } catch {
4800
- return [];
4801
- }
4802
- }
4803
- write(recipes) {
4804
- if (this.filePath === null) {
4805
- this.memory = [...recipes];
4806
- return;
4807
- }
4808
- try {
4809
- mkdirSync2(dirname(this.filePath), { recursive: true });
4810
- const shape = { version: FILE_VERSION, recipes };
4811
- writeFileSync(this.filePath, `${JSON.stringify(shape, null, 2)}
4812
- `, "utf8");
4813
- } catch {
4814
- }
4815
- }
4816
- };
4817
-
4818
5106
  // src/errors.ts
4819
5107
  var MESSAGES = {
4820
5108
  MODEL_UNAVAILABLE: "No model is available for Agent Enhance",
@@ -16881,18 +17169,37 @@ var browserAgentThumbnailResultCodec = codec(
16881
17169
  "dsh-agent-enhancer#BrowserAgentThumbnailResult",
16882
17170
  browserAgentThumbnailResultSchema
16883
17171
  );
17172
+ var demoRecipeVariableSchema = z4.strictObject({
17173
+ name: z4.string().min(1),
17174
+ default: z4.string()
17175
+ });
16884
17176
  var demoRecipeMetaSchema = z4.strictObject({
16885
17177
  id: z4.string().min(1),
16886
17178
  name: z4.string().min(1),
16887
17179
  createdAt: z4.number(),
16888
17180
  updatedAt: z4.number(),
16889
- 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()
16890
17190
  });
16891
17191
  var browserAgentDemoRecipesRequestSchema = z4.discriminatedUnion("action", [
16892
17192
  z4.strictObject({ action: z4.literal("list") }),
16893
17193
  z4.strictObject({ action: z4.literal("save"), name: z4.string() }),
16894
- z4.strictObject({ action: z4.literal("run"), id: z4.string().min(1) }),
16895
- z4.strictObject({ action: z4.literal("delete"), id: z4.string().min(1) })
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() })
16896
17203
  ]);
16897
17204
  var browserAgentDemoRecipesRequestCodec = codec(
16898
17205
  "dsh-agent-enhancer#BrowserAgentDemoRecipesRequest",
@@ -16904,6 +17211,8 @@ var browserAgentDemoRecipesResultSchema = z4.strictObject({
16904
17211
  recipe: demoRecipeMetaSchema.optional(),
16905
17212
  /** Replay lines when running a recipe (`1. ok …`). */
16906
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(),
16907
17216
  /** 1-based step where a replay stopped. */
16908
17217
  stoppedAt: z4.number().int().optional(),
16909
17218
  reason: z4.string().optional(),
@@ -19386,13 +19695,20 @@ var AgentEnhancerService = class extends TypertRemoteService {
19386
19695
  const result = await runtime.demoRecipes({
19387
19696
  action: request.action,
19388
19697
  ..."name" in request ? { name: request.name } : {},
19389
- ..."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 }))
19390
19705
  });
19391
19706
  return {
19392
19707
  ok: result.ok,
19393
- ...result.recipes === void 0 ? {} : { recipes: result.recipes.map((recipe) => ({ ...recipe })) },
19394
- ...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) },
19395
19710
  ...result.lines === void 0 ? {} : { lines: [...result.lines] },
19711
+ ...result.steps === void 0 ? {} : { steps: result.steps.map((step) => ({ ...step })) },
19396
19712
  ...result.stoppedAt === void 0 ? {} : { stoppedAt: result.stoppedAt },
19397
19713
  ...result.reason === void 0 ? {} : { reason: result.reason },
19398
19714
  ...result.error === void 0 ? {} : { error: result.error }