dsh-agent-enhancer 0.3.17 → 0.3.19

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
@@ -1,5 +1,5 @@
1
1
  // src/host/index.ts
2
- import { existsSync as existsSync20, mkdirSync as mkdirSync12, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
2
+ import { existsSync as existsSync20, mkdirSync as mkdirSync13, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
3
  import { homedir as homedir5 } from "node:os";
4
4
  import { join as join30 } from "node:path";
5
5
  import z5 from "@deepseek-ai/schemastery";
@@ -1959,6 +1959,42 @@ 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
+ }
1962
1998
  async press(key) {
1963
1999
  const page = await this.requirePage();
1964
2000
  await page.keyboard.press(key);
@@ -2014,9 +2050,9 @@ var PlaywrightDriver = class {
2014
2050
  /** Small crop around the control a pending approval is about. */
2015
2051
  async thumbnail(ref) {
2016
2052
  const page = await this.requirePage();
2017
- const tabId = this.tabIdFor(page);
2018
- if (this.tabs.ref(tabId, ref) === void 0) return null;
2019
2053
  const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
2054
+ const count = await locator.count().catch(() => 0);
2055
+ if (count === 0) return null;
2020
2056
  const box = await locator.boundingBox().catch(() => null);
2021
2057
  if (box === null) return null;
2022
2058
  const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
@@ -2689,9 +2725,6 @@ function classify(input) {
2689
2725
  };
2690
2726
  }
2691
2727
 
2692
- // src/host/browser-agent/tools.ts
2693
- import { defineTool } from "@deepseek-ai/dsh-tools";
2694
-
2695
2728
  // src/host/browser-agent/demo-replay.ts
2696
2729
  function normalizeControlName(raw) {
2697
2730
  return raw.replace(/[\u200b-\u200d\ufeff]/gu, "").replace(/\s+/gu, " ").trim().toLowerCase();
@@ -2713,10 +2746,6 @@ function matchDemoControl(nodes, role, name2) {
2713
2746
  function replayObstacle(step) {
2714
2747
  if (step.kind !== "fill") return null;
2715
2748
  if (step.masked) return `secret field ${JSON.stringify(step.name)} was masked; type it yourself`;
2716
- if (step.role === "combobox") return `select ${JSON.stringify(step.name)} cannot be replayed by name`;
2717
- if (step.role === "checkbox" || step.role === "radio") {
2718
- return `${step.role} ${JSON.stringify(step.name)} cannot be replayed by name (click it, then continue)`;
2719
- }
2720
2749
  return null;
2721
2750
  }
2722
2751
  async function performStep(driver, step) {
@@ -2731,7 +2760,10 @@ async function performStep(driver, step) {
2731
2760
  const snapshot = await driver.snapshot();
2732
2761
  const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2733
2762
  if (node === void 0) {
2734
- return { ok: false, reason: `no control matching ${step.role} ${JSON.stringify(step.name)} on this page` };
2763
+ return {
2764
+ ok: false,
2765
+ reason: `no control matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2766
+ };
2735
2767
  }
2736
2768
  const result = await driver.click(node.ref);
2737
2769
  return { ok: true, url: result.url };
@@ -2740,7 +2772,18 @@ async function performStep(driver, step) {
2740
2772
  const snapshot = await driver.snapshot();
2741
2773
  const node = matchDemoControl(snapshot.nodes, step.role, step.name);
2742
2774
  if (node === void 0) {
2743
- return { ok: false, reason: `no field matching ${step.role} ${JSON.stringify(step.name)} on this page` };
2775
+ return {
2776
+ ok: false,
2777
+ reason: `no field matching ${step.role} ${JSON.stringify(step.name)} on ${snapshot.url}`
2778
+ };
2779
+ }
2780
+ if (step.role === "combobox") {
2781
+ const result2 = await driver.select(node.ref, step.value);
2782
+ return { ok: true, url: result2.url };
2783
+ }
2784
+ if (step.role === "checkbox" || step.role === "radio") {
2785
+ const result2 = await driver.check(node.ref, step.checked ?? step.value === "on");
2786
+ return { ok: true, url: result2.url };
2744
2787
  }
2745
2788
  const result = await driver.type(node.ref, step.value);
2746
2789
  return { ok: true, url: result.url };
@@ -2755,27 +2798,77 @@ async function performStep(driver, step) {
2755
2798
  }
2756
2799
  }
2757
2800
  }
2801
+ function samePage(a, b) {
2802
+ try {
2803
+ const left = new URL(a);
2804
+ const right = new URL(b);
2805
+ const path = (value) => value.replace(/\/+$/u, "");
2806
+ return left.origin === right.origin && path(left.pathname) === path(right.pathname);
2807
+ } catch {
2808
+ return a === b;
2809
+ }
2810
+ }
2758
2811
  async function replayDemoSteps(driver, steps) {
2759
2812
  const lines = [];
2760
2813
  let currentTab;
2761
2814
  let url;
2815
+ const recordedTabs = [];
2816
+ const tabUrls = /* @__PURE__ */ new Map();
2817
+ for (const step of steps) {
2818
+ if (step.tabId === void 0) continue;
2819
+ if (!recordedTabs.includes(step.tabId)) recordedTabs.push(step.tabId);
2820
+ if (!tabUrls.has(step.tabId) && step.tabUrl !== void 0) tabUrls.set(step.tabId, step.tabUrl);
2821
+ }
2822
+ const multiTab = recordedTabs.length > 1;
2823
+ const liveTabs = multiTab && typeof driver.listTabs === "function" ? await driver.listTabs().then((result) => result.tabs).catch(() => []) : [];
2824
+ const first = steps[0];
2825
+ if (first !== void 0 && first.kind !== "navigate" && first.tabUrl !== void 0 && /^https?:\/\//i.test(first.tabUrl)) {
2826
+ const current = await driver.snapshot().then((result) => result.url).catch(() => void 0);
2827
+ if (current === void 0 || !samePage(current, first.tabUrl)) {
2828
+ await driver.navigate(first.tabUrl).catch(() => void 0);
2829
+ }
2830
+ }
2831
+ const resolveTab = (recordedId) => {
2832
+ const wanted = tabUrls.get(recordedId);
2833
+ if (wanted === void 0) return void 0;
2834
+ return liveTabs.find((tab) => samePage(tab.url, wanted))?.tabId;
2835
+ };
2762
2836
  for (let index = 0; index < steps.length; index += 1) {
2763
2837
  const step = steps[index];
2764
- if (step.tabId !== void 0 && step.tabId !== currentTab) {
2838
+ if (multiTab && step.tabId !== void 0 && step.tabId !== currentTab) {
2765
2839
  try {
2766
- const followed = await driver.followTab(step.tabId);
2840
+ const followed = await driver.followTab(resolveTab(step.tabId) ?? step.tabId);
2767
2841
  currentTab = step.tabId;
2768
2842
  url = followed.url;
2769
2843
  } catch {
2770
- return {
2771
- status: "blocked",
2772
- performed: index,
2773
- total: steps.length,
2774
- lines,
2775
- reason: `tab ${step.tabId} is no longer open`,
2776
- pending: steps.slice(index),
2777
- ...url === void 0 ? {} : { url }
2778
- };
2844
+ const tabUrl = tabUrls.get(step.tabId);
2845
+ if (tabUrl !== void 0) {
2846
+ try {
2847
+ const navigated = await driver.navigate(tabUrl);
2848
+ currentTab = step.tabId;
2849
+ url = navigated.url;
2850
+ } catch {
2851
+ return {
2852
+ status: "blocked",
2853
+ performed: index,
2854
+ total: steps.length,
2855
+ lines,
2856
+ reason: `tab ${step.tabId} is no longer open and ${tabUrl} could not be reopened`,
2857
+ pending: steps.slice(index),
2858
+ ...url === void 0 ? {} : { url }
2859
+ };
2860
+ }
2861
+ } else {
2862
+ return {
2863
+ status: "blocked",
2864
+ performed: index,
2865
+ total: steps.length,
2866
+ lines,
2867
+ reason: `tab ${step.tabId} is no longer open and the recording has no URL for it`,
2868
+ pending: steps.slice(index),
2869
+ ...url === void 0 ? {} : { url }
2870
+ };
2871
+ }
2779
2872
  }
2780
2873
  }
2781
2874
  const obstacle = replayObstacle(step);
@@ -2818,6 +2911,7 @@ async function replayDemoSteps(driver, steps) {
2818
2911
  }
2819
2912
 
2820
2913
  // src/host/browser-agent/tools.ts
2914
+ import { defineTool } from "@deepseek-ai/dsh-tools";
2821
2915
  var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
2822
2916
  function textTool(name2, description, parameters, execute, timeoutMs = 6e4) {
2823
2917
  return defineTool({
@@ -3954,6 +4048,7 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
3954
4048
  if (status === "cancelled") {
3955
4049
  return "user_ack: cancelled\nAction: the demonstration was cancelled. Ask what they want next.";
3956
4050
  }
4051
+ if (steps.length > 0) options.onDemonstration?.(steps);
3957
4052
  const summary = summarizeDemoSteps(steps);
3958
4053
  options.sessions.record({
3959
4054
  sessionId,
@@ -4020,6 +4115,87 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
4020
4115
  },
4021
4116
  HUMAN_WAIT_TIMEOUT_MS
4022
4117
  )));
4118
+ disposers.push(ctx.tools.register(textTool(
4119
+ "browser_demo_recipes",
4120
+ '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.',
4121
+ {
4122
+ action: {
4123
+ type: "string",
4124
+ required: true,
4125
+ description: '"list" to show saved flows, "run" to replay one.'
4126
+ },
4127
+ name: {
4128
+ type: "string",
4129
+ description: "Flow name for action=run. Case-insensitive; a unique part of the name is enough."
4130
+ }
4131
+ },
4132
+ async (args, exec) => {
4133
+ guardEnabled();
4134
+ requireDemonstrate();
4135
+ const store = options.recipes;
4136
+ if (store === void 0) throw new Error("recipe store unavailable");
4137
+ const action = String(args.action ?? "").trim().toLowerCase();
4138
+ const rows = store.list();
4139
+ if (action === "list") {
4140
+ if (rows.length === 0) {
4141
+ return "saved flows: 0\nAction: none yet \u2014 the user can record a demonstration and save it in the sidebar, then retry.";
4142
+ }
4143
+ return [
4144
+ `saved flows: ${rows.length}`,
4145
+ ...rows.map((row) => `- ${row.name} (${row.steps} step(s))`),
4146
+ 'Action: run one with browser_demo_recipes { action: "run", name: "<name>" }.'
4147
+ ].join("\n");
4148
+ }
4149
+ if (action !== "run") throw new Error('action must be "list" or "run"');
4150
+ const wanted = String(args.name ?? "").trim();
4151
+ if (wanted === "") throw new Error("name is required for action=run");
4152
+ const exact = rows.find((row) => row.name.toLowerCase() === wanted.toLowerCase());
4153
+ const partial = rows.filter((row) => row.name.toLowerCase().includes(wanted.toLowerCase()));
4154
+ const meta = exact ?? (partial.length === 1 ? partial[0] : void 0);
4155
+ if (meta === void 0) {
4156
+ 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(", ")}`);
4157
+ }
4158
+ const recipe = store.get(meta.id);
4159
+ if (recipe === void 0) throw new Error("The saved flow disappeared; list again.");
4160
+ const sessionId = sessionIdOf(exec);
4161
+ await ensureConnected();
4162
+ await ensureSessionTab(sessionId);
4163
+ const firstUrl = recipe.steps.find((step) => step.tabUrl !== void 0)?.tabUrl;
4164
+ await requireMutation(
4165
+ exec,
4166
+ "browser_demo_recipes",
4167
+ `\u8FD0\u884C\u5DF2\u4FDD\u5B58\u6D41\u7A0B\u300C${recipe.name}\u300D\uFF08${recipe.steps.length} \u6B65\uFF09`,
4168
+ firstUrl
4169
+ );
4170
+ const outcome = await replayDemoSteps(driverOf(options), recipe.steps);
4171
+ const ranAll = outcome.status === "done";
4172
+ options.sessions.record({
4173
+ sessionId,
4174
+ tool: "browser_demo_recipes",
4175
+ summary: `Ran saved flow "${recipe.name}" (${outcome.performed}/${outcome.total}${ranAll ? "" : ", stopped"})`,
4176
+ outcome: ranAll ? "ok" : "error"
4177
+ });
4178
+ if (ranAll) {
4179
+ return [
4180
+ `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
4181
+ ...outcome.lines,
4182
+ `url: ${outcome.url}`,
4183
+ "Action: the flow ran to the end. Report what changed on screen; browser_snapshot if you need the new page."
4184
+ ].join("\n");
4185
+ }
4186
+ const pending = outcome.pending.map((step, offset) => {
4187
+ const n = outcome.performed + offset + 1;
4188
+ return `${n}. todo ${describeDemoStep(step)}`;
4189
+ });
4190
+ return [
4191
+ `saved flow: ${recipe.name} \u2014 replayed ${outcome.performed}/${outcome.total}`,
4192
+ ...outcome.lines,
4193
+ `stopped at step ${outcome.performed + 1}: ${outcome.reason}`,
4194
+ ...pending,
4195
+ "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."
4196
+ ].join("\n");
4197
+ }
4198
+ )));
4023
4199
  disposers.push(ctx.tools.register(textTool(
4024
4200
  "browser_list_tabs",
4025
4201
  "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.",
@@ -4106,6 +4282,8 @@ function installBrowserAgent(ctx, options) {
4106
4282
  const human = new BrowserHumanGate();
4107
4283
  const sessions = new BrowserSessionState();
4108
4284
  const tabScope = new TabScopeStore();
4285
+ const recipes = options.recipes;
4286
+ let lastDemoSteps = [];
4109
4287
  let availabilityCache = null;
4110
4288
  const browserAvailability = () => {
4111
4289
  if (availabilityCache !== null) return availabilityCache;
@@ -4225,6 +4403,10 @@ function installBrowserAgent(ctx, options) {
4225
4403
  tabScope,
4226
4404
  debugTools: () => options.debugTools?.() === true,
4227
4405
  demonstrate: () => options.demonstrate?.() === true,
4406
+ onDemonstration: (steps) => {
4407
+ lastDemoSteps = steps;
4408
+ },
4409
+ ...recipes === void 0 ? {} : { recipes },
4228
4410
  diagnosis: diagnoseNow,
4229
4411
  // Gate on settings only — `active` flips false during driver align and
4230
4412
  // must not make browser_* look "disabled" mid-turn.
@@ -4404,6 +4586,7 @@ function installBrowserAgent(ctx, options) {
4404
4586
  const aligned = await alignToPreference();
4405
4587
  if (!aligned.ok) return { ok: false, error: aligned.error ?? "Browser agent failed to start" };
4406
4588
  await requireDriver().startDemonstration();
4589
+ lastDemoSteps = [];
4407
4590
  sessions.record({
4408
4591
  sessionId: "sidebar",
4409
4592
  tool: "browser_demonstrate",
@@ -4420,6 +4603,7 @@ function installBrowserAgent(ctx, options) {
4420
4603
  if (driver === null) return { ok: false, error: "Browser agent is not running" };
4421
4604
  try {
4422
4605
  const steps = await driver.stopDemonstration();
4606
+ lastDemoSteps = steps;
4423
4607
  const summary = summarizeDemoSteps(steps);
4424
4608
  sessions.record({
4425
4609
  sessionId: "sidebar",
@@ -4435,6 +4619,72 @@ function installBrowserAgent(ctx, options) {
4435
4619
  demoActive() {
4436
4620
  return activeDriver?.demonstrationActive() === true;
4437
4621
  },
4622
+ lastDemonstrationSteps() {
4623
+ return lastDemoSteps.length;
4624
+ },
4625
+ async demoRecipes(input) {
4626
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
4627
+ if (recipes === void 0) return { ok: false, error: "recipe store unavailable" };
4628
+ if (input.action === "list") {
4629
+ return { ok: true, recipes: recipes.list() };
4630
+ }
4631
+ if (input.action === "delete") {
4632
+ const id = input.id ?? "";
4633
+ const removed = recipes.remove(id);
4634
+ sessions.record({
4635
+ sessionId: "sidebar",
4636
+ tool: "browser_demo_recipe",
4637
+ summary: removed ? `Deleted demonstration recipe ${id}` : `Recipe ${id} not found`,
4638
+ outcome: removed ? "ok" : "error"
4639
+ });
4640
+ return removed ? { ok: true, recipes: recipes.list() } : { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4641
+ }
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() };
4651
+ sessions.record({
4652
+ sessionId: "sidebar",
4653
+ tool: "browser_demo_recipe",
4654
+ summary: `Saved demonstration recipe "${saved.recipe.name}" (${saved.recipe.steps} step(s))`,
4655
+ outcome: "ok"
4656
+ });
4657
+ return { ok: true, recipe: saved.recipe, recipes: recipes.list() };
4658
+ }
4659
+ const recipe = recipes.get(input.id ?? "");
4660
+ if (recipe === void 0) return { ok: false, error: "\u6D41\u7A0B\u4E0D\u5B58\u5728", recipes: recipes.list() };
4661
+ const driver = activeDriver;
4662
+ if (driver === null) return { ok: false, error: "Browser agent is not running", recipes: recipes.list() };
4663
+ const aligned = await alignToPreference().catch(() => ({ ok: true, error: void 0 }));
4664
+ 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) => ({
4666
+ status: "blocked",
4667
+ performed: 0,
4668
+ total: recipe.steps.length,
4669
+ lines: [],
4670
+ reason: error instanceof Error ? error.message : String(error),
4671
+ pending: [...recipe.steps]
4672
+ }));
4673
+ const ranAll = outcome.status === "done";
4674
+ sessions.record({
4675
+ sessionId: "sidebar",
4676
+ tool: "browser_demo_recipe",
4677
+ summary: `Ran demonstration recipe "${recipe.name}" (${outcome.performed}/${outcome.total}${ranAll ? "" : ", stopped"})`,
4678
+ outcome: ranAll ? "ok" : "error"
4679
+ });
4680
+ return {
4681
+ ok: true,
4682
+ recipes: recipes.list(),
4683
+ lines: [...outcome.lines],
4684
+ ...ranAll ? {} : { stoppedAt: outcome.performed + 1 },
4685
+ ...ranAll ? {} : { reason: outcome.reason }
4686
+ };
4687
+ },
4438
4688
  async selectTab(input) {
4439
4689
  if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
4440
4690
  await switchGate.catch(() => void 0);
@@ -4587,6 +4837,106 @@ function installBrowserAgent(ctx, options) {
4587
4837
  };
4588
4838
  }
4589
4839
 
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
+
4590
4940
  // src/errors.ts
4591
4941
  var MESSAGES = {
4592
4942
  MODEL_UNAVAILABLE: "No model is available for Agent Enhance",
@@ -8216,7 +8566,7 @@ async function deleteSessionNow(options) {
8216
8566
 
8217
8567
  // src/host/web-chat-bridge/import-session.ts
8218
8568
  import { randomUUID as randomUUID7 } from "node:crypto";
8219
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, statSync } from "node:fs";
8569
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, statSync } from "node:fs";
8220
8570
  import { resolve as resolve2 } from "node:path";
8221
8571
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
8222
8572
  import {
@@ -9177,7 +9527,7 @@ function ensureResolvableWorkspaceCwd(cwd) {
9177
9527
  const absolute = resolve2(cwd);
9178
9528
  try {
9179
9529
  if (!existsSync5(absolute)) {
9180
- mkdirSync2(absolute, { recursive: true });
9530
+ mkdirSync3(absolute, { recursive: true });
9181
9531
  }
9182
9532
  if (!statSync(absolute).isDirectory()) {
9183
9533
  throw new WebChatImportError(
@@ -10044,8 +10394,8 @@ async function fetchWebChatShareContent(shareId, signal) {
10044
10394
  }
10045
10395
 
10046
10396
  // src/host/web-chat-bridge/login-snapshot.ts
10047
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
10048
- import { dirname, join as join9 } from "node:path";
10397
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
10398
+ import { dirname as dirname2, join as join9 } from "node:path";
10049
10399
 
10050
10400
  // src/host/web-chat-bridge/login-snapshot-types.ts
10051
10401
  var WEB_CHAT_OFFICIAL_ORIGIN = "https://chat.deepseek.com";
@@ -10113,7 +10463,7 @@ function loadWebChatLoginSnapshot(pluginDataPackageRoot) {
10113
10463
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
10114
10464
  if (!existsSync6(path)) return null;
10115
10465
  try {
10116
- return parseSnapshot(readFileSync(path, "utf8"));
10466
+ return parseSnapshot(readFileSync2(path, "utf8"));
10117
10467
  } catch {
10118
10468
  return null;
10119
10469
  }
@@ -10138,9 +10488,9 @@ function saveWebChatLoginSnapshot(pluginDataPackageRoot, input, options) {
10138
10488
  savedAt: typeof input.savedAt === "string" && input.savedAt.trim() !== "" ? input.savedAt : (/* @__PURE__ */ new Date()).toISOString()
10139
10489
  };
10140
10490
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
10141
- mkdirSync3(dirname(path), { recursive: true });
10491
+ mkdirSync4(dirname2(path), { recursive: true });
10142
10492
  const tmp = `${path}.${process.pid}.tmp`;
10143
- writeFileSync(tmp, `${JSON.stringify(snapshot, null, 2)}
10493
+ writeFileSync2(tmp, `${JSON.stringify(snapshot, null, 2)}
10144
10494
  `, "utf8");
10145
10495
  renameSync(tmp, path);
10146
10496
  return snapshot;
@@ -10418,8 +10768,8 @@ function loadExtraRootPaths(store, primaryCwd) {
10418
10768
  }
10419
10769
 
10420
10770
  // src/host/extra-folders/store.ts
10421
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
10422
- import { dirname as dirname2, join as join11 } from "node:path";
10771
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "node:fs";
10772
+ import { dirname as dirname3, join as join11 } from "node:path";
10423
10773
  function emptyDoc(primaryCwd) {
10424
10774
  return {
10425
10775
  version: EXTRA_FOLDERS_VERSION,
@@ -10451,14 +10801,14 @@ function parseDoc(raw, primaryCwd) {
10451
10801
  }
10452
10802
  }
10453
10803
  function createExtraFoldersStore(rootDir) {
10454
- mkdirSync4(rootDir, { recursive: true });
10804
+ mkdirSync5(rootDir, { recursive: true });
10455
10805
  const fileOf = (primaryCwd) => join11(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
10456
10806
  return {
10457
10807
  rootDir,
10458
10808
  load(primaryCwd) {
10459
10809
  const file = fileOf(primaryCwd);
10460
10810
  try {
10461
- return parseDoc(readFileSync2(file, "utf8"), primaryCwd);
10811
+ return parseDoc(readFileSync3(file, "utf8"), primaryCwd);
10462
10812
  } catch (error) {
10463
10813
  const code = error !== null && typeof error === "object" ? String(Reflect.get(error, "code") ?? "") : "";
10464
10814
  if (code === "ENOENT") return emptyDoc(primaryCwd);
@@ -10472,9 +10822,9 @@ function createExtraFoldersStore(rootDir) {
10472
10822
  roots: [...roots]
10473
10823
  };
10474
10824
  const file = fileOf(primaryCwd);
10475
- mkdirSync4(dirname2(file), { recursive: true });
10825
+ mkdirSync5(dirname3(file), { recursive: true });
10476
10826
  const tmp = `${file}.${process.pid}.tmp`;
10477
- writeFileSync2(tmp, `${JSON.stringify(doc, null, 2)}
10827
+ writeFileSync3(tmp, `${JSON.stringify(doc, null, 2)}
10478
10828
  `, "utf8");
10479
10829
  renameSync2(tmp, file);
10480
10830
  return doc;
@@ -10662,7 +11012,7 @@ async function writeWorkspaceFileNow(options) {
10662
11012
  // src/host/file-edit/monaco.ts
10663
11013
  import { existsSync as existsSync7 } from "node:fs";
10664
11014
  import { promises as fsp2 } from "node:fs";
10665
- import { dirname as dirname3, extname, join as join12, resolve as resolve6, sep as sep5 } from "node:path";
11015
+ import { dirname as dirname4, extname, join as join12, resolve as resolve6, sep as sep5 } from "node:path";
10666
11016
  import { fileURLToPath } from "node:url";
10667
11017
 
10668
11018
  // src/shared/monaco-route.ts
@@ -10671,7 +11021,7 @@ var MONACO_ROUTE = "/api/agent-enhancer/monaco";
10671
11021
  // src/host/file-edit/monaco.ts
10672
11022
  var FILE_PATTERN = /^(?:vs\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/;
10673
11023
  function packageRootCandidates() {
10674
- const here = dirname3(fileURLToPath(import.meta.url));
11024
+ const here = dirname4(fileURLToPath(import.meta.url));
10675
11025
  return [
10676
11026
  resolve6(here, "..", "vendor", "monaco", "vs"),
10677
11027
  resolve6(here, "..", "..", "vendor", "monaco", "vs"),
@@ -10817,16 +11167,16 @@ function installMonacoRoute(ctx) {
10817
11167
  }
10818
11168
 
10819
11169
  // src/host/instructions-skills/io.ts
10820
- import { existsSync as existsSync17, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
11170
+ import { existsSync as existsSync17, readFileSync as readFileSync8, statSync as statSync5 } from "node:fs";
10821
11171
  import { basename as basename13, join as join26, resolve as resolve16, sep as sep7 } from "node:path";
10822
11172
 
10823
11173
  // src/host/instructions-skills/create.ts
10824
- import { existsSync as existsSync9, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
10825
- import { dirname as dirname5, join as join14, resolve as resolve8 } from "node:path";
11174
+ import { existsSync as existsSync9, mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "node:fs";
11175
+ import { dirname as dirname6, join as join14, resolve as resolve8 } from "node:path";
10826
11176
 
10827
11177
  // src/host/instructions-skills/paths.ts
10828
11178
  import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
10829
- import { basename as basename5, dirname as dirname4, join as join13, resolve as resolve7, sep as sep6 } from "node:path";
11179
+ import { basename as basename5, dirname as dirname5, join as join13, resolve as resolve7, sep as sep6 } from "node:path";
10830
11180
  import { homedir as homedir3 } from "node:os";
10831
11181
  var INSTRUCTION_CANDIDATES = [
10832
11182
  "AGENTS.md",
@@ -10851,7 +11201,7 @@ function findProjectRoot(cwd, markers = PROJECT_ROOT_MARKERS) {
10851
11201
  for (const marker of markers) {
10852
11202
  if (existsSync8(join13(current, marker))) return current;
10853
11203
  }
10854
- const parent = dirname4(current);
11204
+ const parent = dirname5(current);
10855
11205
  if (parent === current) return resolve7(cwd);
10856
11206
  current = parent;
10857
11207
  }
@@ -10865,7 +11215,7 @@ function projectChainDirs(projectRoot, cwd) {
10865
11215
  for (; ; ) {
10866
11216
  parts.push(current);
10867
11217
  if (samePath2(current, root)) break;
10868
- const parent = dirname4(current);
11218
+ const parent = dirname5(current);
10869
11219
  if (parent === current) break;
10870
11220
  current = parent;
10871
11221
  }
@@ -10949,8 +11299,8 @@ function createWorkspaceAgentsFile(projectRoot) {
10949
11299
  if (existsSync9(path)) {
10950
11300
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
10951
11301
  }
10952
- mkdirSync5(dirname5(path), { recursive: true });
10953
- writeFileSync3(path, AGENTS_STUB, "utf8");
11302
+ mkdirSync6(dirname6(path), { recursive: true });
11303
+ writeFileSync4(path, AGENTS_STUB, "utf8");
10954
11304
  return { path, created: true };
10955
11305
  }
10956
11306
  function createWorkspaceSkill(projectRoot, rawName) {
@@ -10963,14 +11313,14 @@ function createWorkspaceSkill(projectRoot, rawName) {
10963
11313
  if (existsSync9(path) || existsSync9(dir)) {
10964
11314
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
10965
11315
  }
10966
- mkdirSync5(dir, { recursive: true });
10967
- writeFileSync3(path, skillStubMarkdown(name2), "utf8");
11316
+ mkdirSync6(dir, { recursive: true });
11317
+ writeFileSync4(path, skillStubMarkdown(name2), "utf8");
10968
11318
  return { path, created: true, name: name2 };
10969
11319
  }
10970
11320
 
10971
11321
  // src/host/instructions-skills/discover.ts
10972
- import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
10973
- import { basename as basename9, dirname as dirname8, join as join19, resolve as resolve12 } from "node:path";
11322
+ import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "node:fs";
11323
+ import { basename as basename9, dirname as dirname9, join as join19, resolve as resolve12 } from "node:path";
10974
11324
 
10975
11325
  // src/host/instructions-skills/types.ts
10976
11326
  function defaultSkillInstallMeta() {
@@ -11047,19 +11397,19 @@ function removeQuietly(path) {
11047
11397
 
11048
11398
  // src/host/instructions-skills/uninstall.ts
11049
11399
  import { lstatSync as lstatSync3 } from "node:fs";
11050
- import { basename as basename8, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
11400
+ import { basename as basename8, dirname as dirname8, join as join18, resolve as resolve11 } from "node:path";
11051
11401
 
11052
11402
  // src/host/instructions-skills/install-ledger.ts
11053
- import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
11054
- import { dirname as dirname6, join as join16 } from "node:path";
11403
+ import { existsSync as existsSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync4, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "node:fs";
11404
+ import { dirname as dirname7, join as join16 } from "node:path";
11055
11405
  function ledgerPath(dataRoot) {
11056
11406
  return join16(dataRoot, "skills-install", "registry.json");
11057
11407
  }
11058
11408
  function writeLedger(dataRoot, ledger) {
11059
11409
  const path = ledgerPath(dataRoot);
11060
- mkdirSync6(dirname6(path), { recursive: true });
11410
+ mkdirSync7(dirname7(path), { recursive: true });
11061
11411
  const tmp = `${path}.${process.pid}.tmp`;
11062
- writeFileSync4(tmp, `${JSON.stringify(ledger, null, 2)}
11412
+ writeFileSync5(tmp, `${JSON.stringify(ledger, null, 2)}
11063
11413
  `, "utf8");
11064
11414
  renameSync4(tmp, path);
11065
11415
  }
@@ -11067,7 +11417,7 @@ function readInstallLedger(dataRoot) {
11067
11417
  const path = ledgerPath(dataRoot);
11068
11418
  if (!existsSync11(path)) return {};
11069
11419
  try {
11070
- const raw = readFileSync3(path, "utf8").trim();
11420
+ const raw = readFileSync4(path, "utf8").trim();
11071
11421
  if (raw === "") return {};
11072
11422
  return JSON.parse(raw);
11073
11423
  } catch {
@@ -11275,7 +11625,7 @@ function removePathRobust(target) {
11275
11625
  function skillEntryPath(skillMdOrBundlePath) {
11276
11626
  const absolute = resolve11(skillMdOrBundlePath);
11277
11627
  const base = basename8(absolute);
11278
- if (base.toLowerCase() === "skill.md") return dirname7(absolute);
11628
+ if (base.toLowerCase() === "skill.md") return dirname8(absolute);
11279
11629
  if (base.toLowerCase().endsWith(".md")) return absolute;
11280
11630
  return absolute;
11281
11631
  }
@@ -11294,7 +11644,7 @@ function managedSkillEntriesForName(root, name2) {
11294
11644
  const asFile = join18(root, `${name2}.md`);
11295
11645
  for (const entry of [asDir, asFile]) {
11296
11646
  if (!pathPresent2(entry)) continue;
11297
- if (!samePath2(dirname7(entry), root)) continue;
11647
+ if (!samePath2(dirname8(entry), root)) continue;
11298
11648
  if (!isInsideOrSame(root, entry)) continue;
11299
11649
  out.push(entry);
11300
11650
  }
@@ -11308,7 +11658,7 @@ function resolveManagedSkillRemovalTarget(path, name2, managedRoots) {
11308
11658
  const asFile = join18(root, `${name2}.md`);
11309
11659
  if (samePath2(entry, asDir) || samePath2(entry, asFile)) {
11310
11660
  if (!pathPresent2(entry)) return null;
11311
- if (!samePath2(dirname7(entry), root)) return null;
11661
+ if (!samePath2(dirname8(entry), root)) return null;
11312
11662
  if (!isInsideOrSame(root, entry)) return null;
11313
11663
  return entry;
11314
11664
  }
@@ -11437,7 +11787,7 @@ function discoverInstructionFiles(options) {
11437
11787
  }
11438
11788
  function descriptionFromSkillMd(path) {
11439
11789
  try {
11440
- const text3 = readFileSync4(path, "utf8");
11790
+ const text3 = readFileSync5(path, "utf8");
11441
11791
  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text3);
11442
11792
  if (match === null) return "";
11443
11793
  const block = match[1];
@@ -11488,7 +11838,7 @@ function dirnameLabel(root, projectRoot, env) {
11488
11838
  if (samePath2(root, join19(projectRoot, ".dsh", "skills"))) return "project-dsh";
11489
11839
  if (samePath2(root, join19(agentsHomeOf(env), "skills"))) return "shared";
11490
11840
  if (samePath2(root, join19(dshHomeOf(env), "skills"))) return "dsh-home";
11491
- const parent = basename9(dirname8(root)).toLowerCase();
11841
+ const parent = basename9(dirname9(root)).toLowerCase();
11492
11842
  const leaf = basename9(root).toLowerCase();
11493
11843
  if (parent === ".cursor" && leaf === "skills") return "cursor";
11494
11844
  if (parent === ".cursor" && leaf === "skills-cursor") return "cursor-builtin";
@@ -11704,14 +12054,14 @@ function parseGitSkillSource(raw) {
11704
12054
  import { execFile as execFile3, spawn } from "node:child_process";
11705
12055
  import { existsSync as existsSync15, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
11706
12056
  import { tmpdir as tmpdir3 } from "node:os";
11707
- import { basename as basename11, dirname as dirname10, join as join23, resolve as resolve14 } from "node:path";
12057
+ import { basename as basename11, dirname as dirname11, join as join23, resolve as resolve14 } from "node:path";
11708
12058
  import { promisify as promisify3 } from "node:util";
11709
12059
 
11710
12060
  // src/host/instructions-skills/github-archive.ts
11711
12061
  import { execFile as execFile2 } from "node:child_process";
11712
12062
  import {
11713
12063
  createWriteStream,
11714
- mkdirSync as mkdirSync7,
12064
+ mkdirSync as mkdirSync8,
11715
12065
  readdirSync as readdirSync4,
11716
12066
  renameSync as renameSync5,
11717
12067
  rmSync as rmSync3,
@@ -11762,7 +12112,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
11762
12112
  }
11763
12113
  async function extractZip(zipPath, destDir, signal) {
11764
12114
  signal.throwIfAborted();
11765
- mkdirSync7(destDir, { recursive: true });
12115
+ mkdirSync8(destDir, { recursive: true });
11766
12116
  try {
11767
12117
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
11768
12118
  windowsHide: true,
@@ -11820,10 +12170,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
11820
12170
  }
11821
12171
  async function fetchGithubRepoArchive(options) {
11822
12172
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
11823
- mkdirSync7(workDir, { recursive: true });
12173
+ mkdirSync8(workDir, { recursive: true });
11824
12174
  const zipPath = join20(workDir, "repo.zip");
11825
12175
  const extractDir = join20(workDir, "extract");
11826
- mkdirSync7(extractDir, { recursive: true });
12176
+ mkdirSync8(extractDir, { recursive: true });
11827
12177
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
11828
12178
  const candidates = archiveCandidates(owner, repo, defaultBranch);
11829
12179
  const errors = [];
@@ -11834,7 +12184,7 @@ async function fetchGithubRepoArchive(options) {
11834
12184
  try {
11835
12185
  rmSync3(zipPath, { force: true });
11836
12186
  rmSync3(extractDir, { recursive: true, force: true });
11837
- mkdirSync7(extractDir, { recursive: true });
12187
+ mkdirSync8(extractDir, { recursive: true });
11838
12188
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
11839
12189
  if (!downloadStarted) {
11840
12190
  onStage?.("downloading", detail);
@@ -11878,16 +12228,16 @@ import {
11878
12228
  cpSync,
11879
12229
  existsSync as existsSync14,
11880
12230
  lstatSync as lstatSync4,
11881
- mkdirSync as mkdirSync8,
12231
+ mkdirSync as mkdirSync9,
11882
12232
  readdirSync as readdirSync5,
11883
- readFileSync as readFileSync5,
12233
+ readFileSync as readFileSync6,
11884
12234
  renameSync as renameSync6,
11885
12235
  symlinkSync
11886
12236
  } from "node:fs";
11887
- import { basename as basename10, dirname as dirname9, join as join21, resolve as resolve13 } from "node:path";
12237
+ import { basename as basename10, dirname as dirname10, join as join21, resolve as resolve13 } from "node:path";
11888
12238
  function frontmatterBlock(path) {
11889
12239
  try {
11890
- const text3 = readFileSync5(path, "utf8");
12240
+ const text3 = readFileSync6(path, "utf8");
11891
12241
  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text3);
11892
12242
  return match?.[1] ?? null;
11893
12243
  } catch {
@@ -11953,7 +12303,7 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
11953
12303
  throw new AuxiliaryError("FILE_NOT_FOUND", `Path not found in repository: ${subpath ?? "."}`);
11954
12304
  }
11955
12305
  if (base.toLowerCase().endsWith("skill.md") && existsSync14(base)) {
11956
- const dir = dirname9(base);
12306
+ const dir = dirname10(base);
11957
12307
  const name2 = directoryBundleName(dir, basename10(dir));
11958
12308
  if (!isKebabCaseName(name2)) {
11959
12309
  throw new AuxiliaryError("FILE_DENIED", `Skill directory name must be kebab-case: ${name2}`);
@@ -12027,7 +12377,7 @@ function copySkillTree(source, dest) {
12027
12377
  }
12028
12378
  }
12029
12379
  function copySkillTreeAtomic(source, dest, kind) {
12030
- mkdirSync8(dirname9(dest), { recursive: true });
12380
+ mkdirSync9(dirname10(dest), { recursive: true });
12031
12381
  if (kind === "file") {
12032
12382
  if (destinationPresent(dest)) removeDestination(dest);
12033
12383
  copySkillTree(source, dest);
@@ -12055,7 +12405,7 @@ function copySkillTreeAtomic(source, dest, kind) {
12055
12405
  }
12056
12406
  }
12057
12407
  function linkOrCopy(source, dest, mode, kind) {
12058
- mkdirSync8(dirname9(dest), { recursive: true });
12408
+ mkdirSync9(dirname10(dest), { recursive: true });
12059
12409
  if (mode === "copy") {
12060
12410
  copySkillTreeAtomic(source, dest, kind);
12061
12411
  return "copy";
@@ -12093,7 +12443,7 @@ function installBundle(options) {
12093
12443
 
12094
12444
  // src/host/instructions-skills/content-revision.ts
12095
12445
  import { createHash as createHash7 } from "node:crypto";
12096
- import { readdirSync as readdirSync6, readFileSync as readFileSync6 } from "node:fs";
12446
+ import { readdirSync as readdirSync6, readFileSync as readFileSync7 } from "node:fs";
12097
12447
  import { join as join22, relative as relative3 } from "node:path";
12098
12448
  function listRelativeFiles(dir, root) {
12099
12449
  const entries = [];
@@ -12112,7 +12462,7 @@ function contentRevisionOfDir(dir) {
12112
12462
  const paths = listRelativeFiles(dir, dir).sort();
12113
12463
  const aggregate = createHash7("sha256");
12114
12464
  for (const relPath of paths) {
12115
- const contents = readFileSync6(join22(dir, relPath));
12465
+ const contents = readFileSync7(join22(dir, relPath));
12116
12466
  const fileDigest = createHash7("sha256").update(`${relPath}\0`).update(contents).digest();
12117
12467
  aggregate.update(fileDigest);
12118
12468
  }
@@ -12530,7 +12880,7 @@ async function checkGithubSkillUpdate(record2, options) {
12530
12880
 
12531
12881
  // src/host/instructions-skills/zip-install.ts
12532
12882
  import { execFile as execFile4 } from "node:child_process";
12533
- import { existsSync as existsSync16, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
12883
+ import { existsSync as existsSync16, mkdirSync as mkdirSync10, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
12534
12884
  import { tmpdir as tmpdir5 } from "node:os";
12535
12885
  import { basename as basename12, join as join25, resolve as resolve15 } from "node:path";
12536
12886
  import { promisify as promisify4 } from "node:util";
@@ -12545,7 +12895,7 @@ function tempWorkDir3(prefix) {
12545
12895
  }
12546
12896
  async function extractZipArchive(zipPath, destDir, signal) {
12547
12897
  signal.throwIfAborted();
12548
- mkdirSync9(destDir, { recursive: true });
12898
+ mkdirSync10(destDir, { recursive: true });
12549
12899
  try {
12550
12900
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
12551
12901
  windowsHide: true,
@@ -12990,7 +13340,7 @@ async function readSkillDocumentNow(options) {
12990
13340
  options.signal.throwIfAborted();
12991
13341
  let text3;
12992
13342
  try {
12993
- text3 = readFileSync7(absolutePath2, "utf8");
13343
+ text3 = readFileSync8(absolutePath2, "utf8");
12994
13344
  } catch {
12995
13345
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
12996
13346
  }
@@ -13129,7 +13479,7 @@ function parseMcpJsonText(jsonText) {
13129
13479
  }
13130
13480
 
13131
13481
  // src/host/mcp-connectors/install-git.ts
13132
- import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
13482
+ import { existsSync as existsSync18, mkdirSync as mkdirSync11, readFileSync as readFileSync9, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
13133
13483
  import { join as join28 } from "node:path";
13134
13484
 
13135
13485
  // src/host/mcp-connectors/paths.ts
@@ -13172,7 +13522,7 @@ function inferStdioFromPackageJson(installDir, override) {
13172
13522
  };
13173
13523
  }
13174
13524
  try {
13175
- const pkg = JSON.parse(readFileSync8(pkgPath, "utf8"));
13525
+ const pkg = JSON.parse(readFileSync9(pkgPath, "utf8"));
13176
13526
  if (isRecord4(pkg)) {
13177
13527
  const bin = pkg.bin;
13178
13528
  if (typeof bin === "string" && bin.trim() !== "") {
@@ -13227,11 +13577,11 @@ async function installMcpServerFromGit(options) {
13227
13577
  }
13228
13578
  removePathRobust(installDir);
13229
13579
  }
13230
- mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
13580
+ mkdirSync11(join28(options.rootDir, "mcp-servers"), { recursive: true });
13231
13581
  const staging = `${installDir}.staging.${process.pid}`;
13232
13582
  try {
13233
13583
  if (existsSync18(staging)) removePathRobust(staging);
13234
- mkdirSync10(staging, { recursive: true });
13584
+ mkdirSync11(staging, { recursive: true });
13235
13585
  if (parsed.github === null) {
13236
13586
  throw new AuxiliaryError(
13237
13587
  "FILE_EDIT_FAILED",
@@ -13253,7 +13603,7 @@ async function installMcpServerFromGit(options) {
13253
13603
  }
13254
13604
  contentRoot = nested;
13255
13605
  }
13256
- mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
13606
+ mkdirSync11(join28(options.rootDir, "mcp-servers"), { recursive: true });
13257
13607
  if (contentRoot !== repoDir) {
13258
13608
  const nestedStaging = `${installDir}.nested.${process.pid}`;
13259
13609
  renameSync7(contentRoot, nestedStaging);
@@ -13519,8 +13869,8 @@ async function probeMcpConnectorNow(host, request, signal) {
13519
13869
  }
13520
13870
 
13521
13871
  // src/host/mcp-connectors/store.ts
13522
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
13523
- import { dirname as dirname11 } from "node:path";
13872
+ import { mkdirSync as mkdirSync12, readFileSync as readFileSync10, renameSync as renameSync8, writeFileSync as writeFileSync6 } from "node:fs";
13873
+ import { dirname as dirname12 } from "node:path";
13524
13874
 
13525
13875
  // src/host/mcp-connectors/types.ts
13526
13876
  var MCP_CONNECTORS_VERSION = 1;
@@ -13602,13 +13952,13 @@ function parseDoc2(raw) {
13602
13952
  }
13603
13953
  }
13604
13954
  function createMcpConnectorsStore(rootDir) {
13605
- mkdirSync11(rootDir, { recursive: true });
13955
+ mkdirSync12(rootDir, { recursive: true });
13606
13956
  const file = mcpConnectorsLedgerPath(rootDir);
13607
13957
  return {
13608
13958
  rootDir,
13609
13959
  load() {
13610
13960
  try {
13611
- return parseDoc2(readFileSync9(file, "utf8"));
13961
+ return parseDoc2(readFileSync10(file, "utf8"));
13612
13962
  } catch (error) {
13613
13963
  const code = error !== null && typeof error === "object" ? String(Reflect.get(error, "code") ?? "") : "";
13614
13964
  if (code !== "ENOENT") {
@@ -13621,9 +13971,9 @@ function createMcpConnectorsStore(rootDir) {
13621
13971
  version: MCP_CONNECTORS_VERSION,
13622
13972
  connectors: [...connectors]
13623
13973
  };
13624
- mkdirSync11(dirname11(file), { recursive: true });
13974
+ mkdirSync12(dirname12(file), { recursive: true });
13625
13975
  const tmp = `${file}.${process.pid}.tmp`;
13626
- writeFileSync5(tmp, `${JSON.stringify(doc, null, 2)}
13976
+ writeFileSync6(tmp, `${JSON.stringify(doc, null, 2)}
13627
13977
  `, "utf8");
13628
13978
  renameSync8(tmp, file);
13629
13979
  return doc;
@@ -16601,7 +16951,9 @@ var browserAgentSnapshotSchema = z4.strictObject({
16601
16951
  /** Demonstration recorder: switch state and whether it is recording now. */
16602
16952
  demo: z4.strictObject({
16603
16953
  enabled: z4.boolean(),
16604
- recording: z4.boolean()
16954
+ recording: z4.boolean(),
16955
+ /** Steps from the last finished recording, whoever stopped it. */
16956
+ lastSteps: z4.number().int()
16605
16957
  }),
16606
16958
  tabConflict: browserAgentTabConflictSchema.nullable(),
16607
16959
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
@@ -16651,6 +17003,38 @@ var browserAgentThumbnailResultCodec = codec(
16651
17003
  "dsh-agent-enhancer#BrowserAgentThumbnailResult",
16652
17004
  browserAgentThumbnailResultSchema
16653
17005
  );
17006
+ var demoRecipeMetaSchema = z4.strictObject({
17007
+ id: z4.string().min(1),
17008
+ name: z4.string().min(1),
17009
+ createdAt: z4.number(),
17010
+ updatedAt: z4.number(),
17011
+ steps: z4.number().int()
17012
+ });
17013
+ var browserAgentDemoRecipesRequestSchema = z4.discriminatedUnion("action", [
17014
+ z4.strictObject({ action: z4.literal("list") }),
17015
+ 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) })
17018
+ ]);
17019
+ var browserAgentDemoRecipesRequestCodec = codec(
17020
+ "dsh-agent-enhancer#BrowserAgentDemoRecipesRequest",
17021
+ browserAgentDemoRecipesRequestSchema
17022
+ );
17023
+ var browserAgentDemoRecipesResultSchema = z4.strictObject({
17024
+ ok: z4.boolean(),
17025
+ recipes: z4.array(demoRecipeMetaSchema).optional(),
17026
+ recipe: demoRecipeMetaSchema.optional(),
17027
+ /** Replay lines when running a recipe (`1. ok …`). */
17028
+ lines: z4.array(z4.string()).optional(),
17029
+ /** 1-based step where a replay stopped. */
17030
+ stoppedAt: z4.number().int().optional(),
17031
+ reason: z4.string().optional(),
17032
+ error: z4.string().optional()
17033
+ });
17034
+ var browserAgentDemoRecipesResultCodec = codec(
17035
+ "dsh-agent-enhancer#BrowserAgentDemoRecipesResult",
17036
+ browserAgentDemoRecipesResultSchema
17037
+ );
16654
17038
  var browserAgentResolveRequestSchema = z4.strictObject({
16655
17039
  id: z4.string().min(1),
16656
17040
  decision: browserAgentApprovalDecisionSchema
@@ -17545,6 +17929,18 @@ var remoteInfo = createTypertRemoteInfo({
17545
17929
  }],
17546
17930
  result: browserAgentSelectTabResultCodec
17547
17931
  },
17932
+ "agentEnhancer/browserAgentDemoRecipes": {
17933
+ service: "agentEnhancer",
17934
+ implementation: "browserAgentDemoRecipes",
17935
+ invocation: { kind: "direct" },
17936
+ parameters: [{
17937
+ name: "request",
17938
+ source: "json",
17939
+ codec: browserAgentDemoRecipesRequestCodec,
17940
+ strictCodec: browserAgentDemoRecipesRequestCodec
17941
+ }],
17942
+ result: browserAgentDemoRecipesResultCodec
17943
+ },
17548
17944
  "agentEnhancer/browserAgentThumbnail": {
17549
17945
  service: "agentEnhancer",
17550
17946
  implementation: "browserAgentThumbnail",
@@ -18389,7 +18785,8 @@ var AgentEnhancerService = class extends TypertRemoteService {
18389
18785
  },
18390
18786
  demo: {
18391
18787
  enabled: settings.demonstrate,
18392
- recording: this.browserAgent?.demoActive() === true
18788
+ recording: this.browserAgent?.demoActive() === true,
18789
+ lastSteps: this.browserAgent?.lastDemonstrationSteps() ?? 0
18393
18790
  },
18394
18791
  diagnosis: diag ?? {
18395
18792
  code: settings.enabled ? "idle" : "disabled",
@@ -19104,6 +19501,25 @@ var AgentEnhancerService = class extends TypertRemoteService {
19104
19501
  if (thumb === null) return { ok: false, error: "no preview for this approval" };
19105
19502
  return { ok: true, mime: thumb.mime, base64: thumb.base64 };
19106
19503
  }
19504
+ async browserAgentDemoRecipes(request) {
19505
+ this.assertOwner();
19506
+ const runtime = this.browserAgent;
19507
+ if (runtime === null) return { ok: false, error: "runtime unavailable" };
19508
+ const result = await runtime.demoRecipes({
19509
+ action: request.action,
19510
+ ..."name" in request ? { name: request.name } : {},
19511
+ ..."id" in request ? { id: request.id } : {}
19512
+ });
19513
+ return {
19514
+ ok: result.ok,
19515
+ ...result.recipes === void 0 ? {} : { recipes: result.recipes.map((recipe) => ({ ...recipe })) },
19516
+ ...result.recipe === void 0 ? {} : { recipe: { ...result.recipe } },
19517
+ ...result.lines === void 0 ? {} : { lines: [...result.lines] },
19518
+ ...result.stoppedAt === void 0 ? {} : { stoppedAt: result.stoppedAt },
19519
+ ...result.reason === void 0 ? {} : { reason: result.reason },
19520
+ ...result.error === void 0 ? {} : { error: result.error }
19521
+ };
19522
+ }
19107
19523
  async browserAgentDemo(request) {
19108
19524
  this.assertOwner();
19109
19525
  if (request.action === "start") {
@@ -19141,7 +19557,7 @@ function resolveCheckpointRoot(dshHome2) {
19141
19557
  const next = join30(nextPkg, "checkpoint");
19142
19558
  const prev = join30(base, LEGACY_PACKAGE_NAME, "checkpoint");
19143
19559
  if (!existsSync20(next) && existsSync20(prev)) {
19144
- mkdirSync12(nextPkg, { recursive: true });
19560
+ mkdirSync13(nextPkg, { recursive: true });
19145
19561
  renameSync9(prev, next);
19146
19562
  const prevPkg = join30(base, LEGACY_PACKAGE_NAME);
19147
19563
  try {
@@ -19310,6 +19726,7 @@ function apply(ctx, config) {
19310
19726
  debugTools: () => settings().browserAgentDebugTools,
19311
19727
  demonstrate: () => settings().browserAgentDemonstrate,
19312
19728
  idleClose: () => settings().browserAgentIdleClose,
19729
+ recipes: new DemoRecipeStore(join30(pluginDataPackageRoot, "demo-recipes.json")),
19313
19730
  profileRoot: pluginDataPackageRoot,
19314
19731
  softPause: softPauseGate,
19315
19732
  softPauseEnabled: () => settings().softPauseEnabled,