dsh-agent-enhancer 0.3.8 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.en.md +8 -5
  2. package/README.md +8 -5
  3. package/lib/client/browser-agent/chat-links.d.ts +9 -0
  4. package/lib/client/browser-agent/chat-links.d.ts.map +1 -0
  5. package/lib/client/browser-agent/guide-icon.d.ts +4 -0
  6. package/lib/client/browser-agent/guide-icon.d.ts.map +1 -0
  7. package/lib/client/browser-agent/kind.d.ts +3 -0
  8. package/lib/client/browser-agent/kind.d.ts.map +1 -0
  9. package/lib/client/browser-agent/overlay.d.ts +7 -0
  10. package/lib/client/browser-agent/overlay.d.ts.map +1 -0
  11. package/lib/client/browser-agent/tab.d.ts +16 -0
  12. package/lib/client/browser-agent/tab.d.ts.map +1 -0
  13. package/lib/client/dsh/settings-catalog.d.ts +2 -2
  14. package/lib/client/dsh/settings-catalog.d.ts.map +1 -1
  15. package/lib/client/dsh/settings-features.d.ts +2 -1
  16. package/lib/client/dsh/settings-features.d.ts.map +1 -1
  17. package/lib/client/dsh/settings.d.ts +2 -0
  18. package/lib/client/dsh/settings.d.ts.map +1 -1
  19. package/lib/client/index.d.ts.map +1 -1
  20. package/lib/client/locales.d.ts +81 -1
  21. package/lib/client/locales.d.ts.map +1 -1
  22. package/lib/client/remote.d.ts +25 -1
  23. package/lib/client/remote.d.ts.map +1 -1
  24. package/lib/client/run-alerts/copy.d.ts.map +1 -1
  25. package/lib/client/run-alerts/host.d.ts +2 -0
  26. package/lib/client/run-alerts/host.d.ts.map +1 -1
  27. package/lib/client/run-alerts/types.d.ts +2 -2
  28. package/lib/client/run-alerts/types.d.ts.map +1 -1
  29. package/lib/client.js +4494 -3525
  30. package/lib/client.js.map +1 -1
  31. package/lib/config.d.ts +7 -1
  32. package/lib/config.d.ts.map +1 -1
  33. package/lib/host/browser-agent/approval.d.ts +38 -0
  34. package/lib/host/browser-agent/approval.d.ts.map +1 -0
  35. package/lib/host/browser-agent/auto-nav.d.ts +16 -0
  36. package/lib/host/browser-agent/auto-nav.d.ts.map +1 -0
  37. package/lib/host/browser-agent/auto-nav.test.d.ts +2 -0
  38. package/lib/host/browser-agent/auto-nav.test.d.ts.map +1 -0
  39. package/lib/host/browser-agent/driver.d.ts +76 -0
  40. package/lib/host/browser-agent/driver.d.ts.map +1 -0
  41. package/lib/host/browser-agent/extract.test.d.ts +2 -0
  42. package/lib/host/browser-agent/extract.test.d.ts.map +1 -0
  43. package/lib/host/browser-agent/human-gate.d.ts +36 -0
  44. package/lib/host/browser-agent/human-gate.d.ts.map +1 -0
  45. package/lib/host/browser-agent/human-gate.test.d.ts +2 -0
  46. package/lib/host/browser-agent/human-gate.test.d.ts.map +1 -0
  47. package/lib/host/browser-agent/install.d.ts +71 -0
  48. package/lib/host/browser-agent/install.d.ts.map +1 -0
  49. package/lib/host/browser-agent/launch.d.ts +38 -0
  50. package/lib/host/browser-agent/launch.d.ts.map +1 -0
  51. package/lib/host/browser-agent/page-links.d.ts +12 -0
  52. package/lib/host/browser-agent/page-links.d.ts.map +1 -0
  53. package/lib/host/browser-agent/page-links.test.d.ts +2 -0
  54. package/lib/host/browser-agent/page-links.test.d.ts.map +1 -0
  55. package/lib/host/browser-agent/path-key.test.d.ts +2 -0
  56. package/lib/host/browser-agent/path-key.test.d.ts.map +1 -0
  57. package/lib/host/browser-agent/pick-auto-nav.test.d.ts +2 -0
  58. package/lib/host/browser-agent/pick-auto-nav.test.d.ts.map +1 -0
  59. package/lib/host/browser-agent/playwright-driver.d.ts +81 -0
  60. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -0
  61. package/lib/host/browser-agent/playwright-snapshot.d.ts +50 -0
  62. package/lib/host/browser-agent/playwright-snapshot.d.ts.map +1 -0
  63. package/lib/host/browser-agent/prompt.d.ts +7 -0
  64. package/lib/host/browser-agent/prompt.d.ts.map +1 -0
  65. package/lib/host/browser-agent/protocol.d.ts +139 -0
  66. package/lib/host/browser-agent/protocol.d.ts.map +1 -0
  67. package/lib/host/browser-agent/proximity.d.ts +27 -0
  68. package/lib/host/browser-agent/proximity.d.ts.map +1 -0
  69. package/lib/host/browser-agent/session-state.d.ts +60 -0
  70. package/lib/host/browser-agent/session-state.d.ts.map +1 -0
  71. package/lib/host/browser-agent/tools.d.ts +29 -0
  72. package/lib/host/browser-agent/tools.d.ts.map +1 -0
  73. package/lib/host/index.d.ts +28 -2
  74. package/lib/host/index.d.ts.map +1 -1
  75. package/lib/host/rpc.d.ts +550 -0
  76. package/lib/host/rpc.d.ts.map +1 -1
  77. package/lib/host/run-alerts/notify.d.ts.map +1 -1
  78. package/lib/identity.d.ts +1 -1
  79. package/lib/index.js +3381 -324
  80. package/lib/index.js.map +4 -4
  81. package/package.json +5 -1
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/host/index.ts
2
- import { existsSync as existsSync16, mkdirSync as mkdirSync9, readdirSync as readdirSync7, renameSync as renameSync8, rmdirSync } from "node:fs";
3
- import { homedir as homedir5 } from "node:os";
4
- import { join as join30 } from "node:path";
2
+ import { existsSync as existsSync17, mkdirSync as mkdirSync10, readdirSync as readdirSync7, renameSync as renameSync8, rmdirSync } from "node:fs";
3
+ import { homedir as homedir6 } from "node:os";
4
+ import { join as join31 } from "node:path";
5
5
  import z5 from "@deepseek-ai/schemastery";
6
6
  import { RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
7
7
 
@@ -20,6 +20,16 @@ function resolveRunAlertsLevel(value) {
20
20
  return "unfocused";
21
21
  }
22
22
  }
23
+ function resolveBrowserAgentBrowser(value) {
24
+ switch (value) {
25
+ case "auto":
26
+ case "chrome":
27
+ case "edge":
28
+ return value;
29
+ default:
30
+ return "auto";
31
+ }
32
+ }
23
33
  var DEFAULT_AUXILIARY_MODEL = {
24
34
  provider: "",
25
35
  model: "",
@@ -38,6 +48,8 @@ var DEFAULT_SETTINGS = {
38
48
  softPauseEnabled: true,
39
49
  runAlertsEnabled: true,
40
50
  runAlertsLevel: "unfocused",
51
+ browserAgentEnabled: false,
52
+ browserAgentBrowser: "auto",
41
53
  instructionsSkillsEnabled: true,
42
54
  mcpConnectorsEnabled: true,
43
55
  optimizeProvider: "",
@@ -80,6 +92,8 @@ function resolveSettings(value) {
80
92
  softPauseEnabled: value?.softPauseEnabled ?? true,
81
93
  runAlertsEnabled: value?.runAlertsEnabled ?? true,
82
94
  runAlertsLevel: resolveRunAlertsLevel(value?.runAlertsLevel),
95
+ browserAgentEnabled: value?.browserAgentEnabled ?? false,
96
+ browserAgentBrowser: resolveBrowserAgentBrowser(value?.browserAgentBrowser),
83
97
  instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
84
98
  mcpConnectorsEnabled: value?.mcpConnectorsEnabled ?? true,
85
99
  optimizeProvider: text(value?.optimizeProvider),
@@ -105,63 +119,2649 @@ function resolveSettings(value) {
105
119
  autoClassifierModel: text(value?.autoClassifierModel),
106
120
  autoClassifierReasoningEffort: text(value?.autoClassifierReasoningEffort)
107
121
  };
108
- }
109
- function isAutoModel(selection) {
110
- return selection.provider === AUTO_PROVIDER && selection.model === AUTO_MODEL;
111
- }
112
- function autoRouteMapOf(settings) {
122
+ }
123
+ function isAutoModel(selection) {
124
+ return selection.provider === AUTO_PROVIDER && selection.model === AUTO_MODEL;
125
+ }
126
+ function autoRouteMapOf(settings) {
127
+ return {
128
+ instant: {
129
+ provider: settings.autoInstantProvider,
130
+ model: settings.autoInstantModel,
131
+ reasoningEffort: settings.autoInstantReasoningEffort
132
+ },
133
+ thinking: {
134
+ provider: settings.autoThinkingProvider,
135
+ model: settings.autoThinkingModel,
136
+ reasoningEffort: settings.autoThinkingReasoningEffort
137
+ },
138
+ pro: {
139
+ provider: settings.autoProProvider,
140
+ model: settings.autoProModel,
141
+ reasoningEffort: settings.autoProReasoningEffort
142
+ },
143
+ classifier: {
144
+ provider: settings.autoClassifierProvider,
145
+ model: settings.autoClassifierModel,
146
+ reasoningEffort: settings.autoClassifierReasoningEffort
147
+ }
148
+ };
149
+ }
150
+ function auxiliaryModelOf(settings, feature) {
151
+ switch (feature) {
152
+ case "optimize":
153
+ return {
154
+ provider: settings.optimizeProvider,
155
+ model: settings.optimizeModel,
156
+ reasoningEffort: settings.optimizeReasoningEffort
157
+ };
158
+ case "predict":
159
+ return {
160
+ provider: settings.predictProvider,
161
+ model: settings.predictModel,
162
+ reasoningEffort: settings.predictReasoningEffort
163
+ };
164
+ case "compact":
165
+ return {
166
+ provider: settings.compactProvider,
167
+ model: settings.compactModel,
168
+ reasoningEffort: settings.compactReasoningEffort
169
+ };
170
+ default: {
171
+ const _exhaustive = feature;
172
+ return _exhaustive;
173
+ }
174
+ }
175
+ }
176
+ function isFollowSessionModel(selection) {
177
+ return selection.provider === "" || selection.model === "";
178
+ }
179
+
180
+ // src/host/browser-agent/protocol.ts
181
+ function originOfUrl(url) {
182
+ try {
183
+ const parsed = new URL(url);
184
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
185
+ return parsed.origin;
186
+ } catch {
187
+ return void 0;
188
+ }
189
+ }
190
+
191
+ // src/host/browser-agent/approval.ts
192
+ var BrowserApprovalGate = class {
193
+ pending = /* @__PURE__ */ new Map();
194
+ allowedOrigins = /* @__PURE__ */ new Map();
195
+ seq = 0;
196
+ listener;
197
+ setListener(listener) {
198
+ this.listener = listener;
199
+ }
200
+ allowedOriginList(sessionId) {
201
+ if (sessionId !== void 0) {
202
+ return [...this.allowedOrigins.get(sessionId) ?? []];
203
+ }
204
+ const all = /* @__PURE__ */ new Set();
205
+ for (const set of this.allowedOrigins.values()) {
206
+ for (const origin of set) all.add(origin);
207
+ }
208
+ return [...all];
209
+ }
210
+ clearSession(sessionId) {
211
+ this.allowedOrigins.delete(sessionId);
212
+ for (const [id, entry] of [...this.pending]) {
213
+ if (entry.request.sessionId !== sessionId) continue;
214
+ this.pending.delete(id);
215
+ entry.detachAbort();
216
+ entry.reject(new Error("browser approval cancelled: session cleared"));
217
+ }
218
+ this.emitTop();
219
+ }
220
+ clearAll() {
221
+ this.allowedOrigins.clear();
222
+ for (const [, entry] of this.pending) {
223
+ entry.detachAbort();
224
+ entry.reject(new Error("browser approval cancelled"));
225
+ }
226
+ this.pending.clear();
227
+ this.emitTop();
228
+ }
229
+ current() {
230
+ const first = this.pending.values().next().value;
231
+ return first?.request ?? null;
232
+ }
233
+ /**
234
+ * Returns true when the action may proceed without prompting.
235
+ * Read-only tools should skip this gate entirely.
236
+ */
237
+ isPreauthorized(sessionId, url) {
238
+ const origin = url === void 0 ? void 0 : originOfUrl(url);
239
+ if (origin === void 0) return false;
240
+ return this.allowedOrigins.get(sessionId)?.has(origin) === true;
241
+ }
242
+ async requestApproval(input) {
243
+ if (!input.forcePrompt && this.isPreauthorized(input.sessionId, input.url)) return "allow";
244
+ if (input.signal.aborted) return "deny";
245
+ this.seq += 1;
246
+ const id = `ba-${this.seq}`;
247
+ const origin = input.url === void 0 ? void 0 : originOfUrl(input.url);
248
+ const request = {
249
+ id,
250
+ sessionId: input.sessionId,
251
+ tool: input.tool,
252
+ summary: input.summary,
253
+ ...input.url === void 0 ? {} : { url: input.url },
254
+ ...origin === void 0 ? {} : { origin }
255
+ };
256
+ const decision = await new Promise((resolve16, reject) => {
257
+ const onAbort = () => {
258
+ const entry = this.pending.get(id);
259
+ if (entry === void 0) return;
260
+ this.pending.delete(id);
261
+ entry.detachAbort();
262
+ reject(new Error("browser approval aborted"));
263
+ this.emitTop();
264
+ };
265
+ const detachAbort = () => {
266
+ input.signal.removeEventListener("abort", onAbort);
267
+ };
268
+ this.pending.set(id, {
269
+ request,
270
+ resolve: resolve16,
271
+ reject,
272
+ detachAbort
273
+ });
274
+ input.signal.addEventListener("abort", onAbort, { once: true });
275
+ this.emitTop();
276
+ });
277
+ if (decision === "deny") return "deny";
278
+ if (decision === "allow-origin" && origin !== void 0) {
279
+ let set = this.allowedOrigins.get(input.sessionId);
280
+ if (set === void 0) {
281
+ set = /* @__PURE__ */ new Set();
282
+ this.allowedOrigins.set(input.sessionId, set);
283
+ }
284
+ set.add(origin);
285
+ }
286
+ return "allow";
287
+ }
288
+ resolve(id, decision) {
289
+ const entry = this.pending.get(id);
290
+ if (entry === void 0) return false;
291
+ this.pending.delete(id);
292
+ entry.detachAbort();
293
+ entry.resolve(decision);
294
+ this.emitTop();
295
+ return true;
296
+ }
297
+ emitTop() {
298
+ this.listener?.(this.current());
299
+ }
300
+ };
301
+
302
+ // src/host/browser-agent/human-gate.ts
303
+ var BrowserHumanGate = class {
304
+ pending = /* @__PURE__ */ new Map();
305
+ seq = 0;
306
+ listener;
307
+ setListener(listener) {
308
+ this.listener = listener;
309
+ }
310
+ current() {
311
+ const first = this.pending.values().next().value;
312
+ return first?.request ?? null;
313
+ }
314
+ clearSession(sessionId) {
315
+ for (const [id, entry] of [...this.pending]) {
316
+ if (entry.request.sessionId !== sessionId) continue;
317
+ this.pending.delete(id);
318
+ entry.detachAbort();
319
+ entry.resolve("cancelled");
320
+ }
321
+ this.emitTop();
322
+ }
323
+ clearAll() {
324
+ for (const [, entry] of this.pending) {
325
+ entry.detachAbort();
326
+ entry.resolve("cancelled");
327
+ }
328
+ this.pending.clear();
329
+ this.emitTop();
330
+ }
331
+ /**
332
+ * Block until the user acknowledges (Continue) or the tool abort signal fires.
333
+ */
334
+ async waitForHuman(input) {
335
+ if (input.signal.aborted) return "cancelled";
336
+ this.seq += 1;
337
+ const id = `bh-${this.seq}`;
338
+ const request = {
339
+ id,
340
+ sessionId: input.sessionId,
341
+ prompt: input.prompt,
342
+ detail: input.detail,
343
+ ...input.url === void 0 ? {} : { url: input.url }
344
+ };
345
+ return await new Promise((resolve16, reject) => {
346
+ const onAbort = () => {
347
+ const entry = this.pending.get(id);
348
+ if (entry === void 0) return;
349
+ this.pending.delete(id);
350
+ entry.detachAbort();
351
+ reject(new Error("browser human wait aborted"));
352
+ this.emitTop();
353
+ };
354
+ const detachAbort = () => {
355
+ input.signal.removeEventListener("abort", onAbort);
356
+ };
357
+ this.pending.set(id, {
358
+ request,
359
+ resolve: resolve16,
360
+ reject,
361
+ detachAbort
362
+ });
363
+ input.signal.addEventListener("abort", onAbort, { once: true });
364
+ this.emitTop();
365
+ });
366
+ }
367
+ /** Resolve the waiting tool for a session (Continue button). */
368
+ acknowledge(sessionId) {
369
+ const target = typeof sessionId === "string" && sessionId.trim() !== "" ? [...this.pending.values()].find((entry) => entry.request.sessionId === sessionId.trim()) : this.pending.values().next().value;
370
+ if (target === void 0) return false;
371
+ this.pending.delete(target.request.id);
372
+ target.detachAbort();
373
+ target.resolve("continued");
374
+ this.emitTop();
375
+ return true;
376
+ }
377
+ emitTop() {
378
+ this.listener?.(this.current());
379
+ }
380
+ };
381
+
382
+ // src/host/browser-agent/launch.ts
383
+ import { execFileSync } from "node:child_process";
384
+ import { existsSync } from "node:fs";
385
+ import { homedir } from "node:os";
386
+ import { join } from "node:path";
387
+ function windowsEnv(name2, env = process.env) {
388
+ const variants = [
389
+ name2,
390
+ name2.toUpperCase(),
391
+ name2.toLowerCase(),
392
+ // Common mixed-case forms used by Windows / Electron.
393
+ name2 === "ProgramFiles" ? "PROGRAMFILES" : null,
394
+ name2 === "ProgramFiles(x86)" ? "PROGRAMFILES(X86)" : null,
395
+ name2 === "ProgramW6432" ? "PROGRAMW6432" : null,
396
+ name2 === "LocalAppData" ? "LOCALAPPDATA" : null
397
+ ];
398
+ for (const key of variants) {
399
+ if (key === null) continue;
400
+ const value = env[key];
401
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
402
+ }
403
+ return void 0;
404
+ }
405
+ function browserExecutableCandidates(kind, platform = process.platform, env = process.env) {
406
+ const home = homedir();
407
+ if (platform === "win32") {
408
+ const local = windowsEnv("LocalAppData", env);
409
+ const programFiles64 = windowsEnv("ProgramW6432", env) ?? "C:\\Program Files";
410
+ const programFiles = windowsEnv("ProgramFiles", env) ?? programFiles64;
411
+ const programFilesX86 = windowsEnv("ProgramFiles(x86)", env) ?? "C:\\Program Files (x86)";
412
+ const roots = [...new Set([local, programFiles64, programFiles, programFilesX86].filter(
413
+ (path) => typeof path === "string" && path !== ""
414
+ ))];
415
+ if (kind === "chrome") {
416
+ return [
417
+ ...roots.map((root) => join(root, "Google", "Chrome", "Application", "chrome.exe")),
418
+ // Hardcoded fallbacks when env is stripped in Electron.
419
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
420
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
421
+ join(home, "AppData", "Local", "Google", "Chrome", "Application", "chrome.exe")
422
+ ];
423
+ }
424
+ return [
425
+ ...roots.map((root) => join(root, "Microsoft", "Edge", "Application", "msedge.exe")),
426
+ "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
427
+ "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
428
+ join(home, "AppData", "Local", "Microsoft", "Edge", "Application", "msedge.exe")
429
+ ];
430
+ }
431
+ if (platform === "darwin") {
432
+ if (kind === "chrome") {
433
+ return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
434
+ }
435
+ return ["/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];
436
+ }
437
+ if (kind === "chrome") {
438
+ return ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser"];
439
+ }
440
+ return ["/usr/bin/microsoft-edge", "/usr/bin/microsoft-edge-stable"];
441
+ }
442
+ function lookUpOnPath(kind, platform, where, exists) {
443
+ const names = platform === "win32" ? kind === "chrome" ? ["chrome.exe", "chrome"] : ["msedge.exe", "msedge"] : kind === "chrome" ? ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"] : ["microsoft-edge", "microsoft-edge-stable", "msedge"];
444
+ for (const name2 of names) {
445
+ const hit = where(name2);
446
+ if (hit !== null && exists(hit)) return hit;
447
+ }
448
+ return null;
449
+ }
450
+ function defaultWhere(command) {
451
+ try {
452
+ if (process.platform === "win32") {
453
+ const out2 = execFileSync("where.exe", [command], {
454
+ encoding: "utf8",
455
+ timeout: 3e3,
456
+ windowsHide: true
457
+ });
458
+ const first2 = out2.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== "");
459
+ return first2 ?? null;
460
+ }
461
+ const out = execFileSync("which", [command], { encoding: "utf8", timeout: 3e3 });
462
+ const first = out.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== "");
463
+ return first ?? null;
464
+ } catch {
465
+ return null;
466
+ }
467
+ }
468
+ function resolveBrowserExecutable(preference = "auto", options = {}) {
469
+ const exists = options.exists ?? existsSync;
470
+ const platform = options.platform ?? process.platform;
471
+ const env = options.env ?? process.env;
472
+ const order = preference === "auto" ? platform === "win32" ? ["edge", "chrome"] : ["chrome", "edge"] : [preference];
473
+ for (const kind of order) {
474
+ const seen = /* @__PURE__ */ new Set();
475
+ for (const executable of browserExecutableCandidates(kind, platform, env)) {
476
+ if (seen.has(executable)) continue;
477
+ seen.add(executable);
478
+ if (exists(executable)) return { kind, executable };
479
+ }
480
+ const fromPath = lookUpOnPath(kind, platform, options.where ?? defaultWhere, exists);
481
+ if (fromPath !== null) return { kind, executable: fromPath };
482
+ }
483
+ return null;
484
+ }
485
+ function defaultBrowserAgentProfileDir(pluginDataPackageRoot) {
486
+ return browserAgentProfileDirFor(pluginDataPackageRoot, "auto");
487
+ }
488
+ function browserAgentProfileDirFor(pluginDataPackageRoot, preference) {
489
+ const slot = preference === "chrome" || preference === "edge" ? preference : "auto";
490
+ return join(pluginDataPackageRoot, "browser-agent", `profile-${slot}`);
491
+ }
492
+ function playwrightChannelOrder(preference, platform = process.platform) {
493
+ if (preference === "chrome") return ["chrome"];
494
+ if (preference === "edge") return ["msedge"];
495
+ return platform === "win32" ? ["msedge", "chrome"] : ["chrome", "msedge"];
496
+ }
497
+ function stopAgentBrowserProcesses(profileDir) {
498
+ if (profileDir.trim() === "") return;
499
+ if (process.platform === "win32") {
500
+ try {
501
+ execFileSync(
502
+ "powershell.exe",
503
+ [
504
+ "-NoProfile",
505
+ "-NonInteractive",
506
+ "-Command",
507
+ [
508
+ '$ErrorActionPreference = "SilentlyContinue"',
509
+ '$needle = ($env:DSH_BA_PROFILE_DIR -replace "\\\\","/").ToLowerInvariant()',
510
+ `Get-CimInstance Win32_Process | Where-Object { ($_.Name -eq 'msedge.exe' -or $_.Name -eq 'chrome.exe') -and $_.CommandLine -and (($_.CommandLine -replace "\\\\","/").ToLowerInvariant().IndexOf($needle) -ge 0) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`
511
+ ].join("; ")
512
+ ],
513
+ {
514
+ timeout: 8e3,
515
+ windowsHide: true,
516
+ env: { ...process.env, DSH_BA_PROFILE_DIR: profileDir }
517
+ }
518
+ );
519
+ } catch {
520
+ }
521
+ return;
522
+ }
523
+ const needle = profileDir.replace(/\\/g, "/");
524
+ try {
525
+ execFileSync("pkill", ["-f", needle], { timeout: 5e3 });
526
+ } catch {
527
+ }
528
+ }
529
+
530
+ // src/host/browser-agent/playwright-driver.ts
531
+ import { mkdirSync } from "node:fs";
532
+ import { chromium } from "playwright-core";
533
+
534
+ // src/host/browser-agent/proximity.ts
535
+ function attachHrefByProximity(nodes, anchors) {
536
+ if (!Array.isArray(nodes) || !Array.isArray(anchors) || anchors.length === 0) return 0;
537
+ const prepared = anchors.filter((a) => a && /^https?:\/\//i.test(String(a.href || "")) && Number(a.w) > 0 && Number(a.h) > 0).map((a) => ({
538
+ href: String(a.href),
539
+ name: String(a.name || "").replace(/\s+/g, " ").trim().toLowerCase(),
540
+ x: Number(a.x),
541
+ y: Number(a.y),
542
+ w: Number(a.w),
543
+ h: Number(a.h),
544
+ cx: Number(a.x) + Number(a.w) / 2,
545
+ cy: Number(a.y) + Number(a.h) / 2,
546
+ area: Number(a.w) * Number(a.h)
547
+ }));
548
+ if (prepared.length === 0) return 0;
549
+ let attached = 0;
550
+ for (const node of nodes) {
551
+ if (!node || typeof node.href === "string" && /^https?:\/\//i.test(node.href)) continue;
552
+ const nx = typeof node.x === "number" ? node.x : Number.NaN;
553
+ const ny = typeof node.y === "number" ? node.y : Number.NaN;
554
+ let best = null;
555
+ let bestArea = Infinity;
556
+ if (Number.isFinite(nx) && Number.isFinite(ny)) {
557
+ for (const a of prepared) {
558
+ if (nx >= a.x && nx <= a.x + a.w && ny >= a.y && ny <= a.y + a.h) {
559
+ if (a.area < bestArea) {
560
+ bestArea = a.area;
561
+ best = a;
562
+ }
563
+ }
564
+ }
565
+ if (best === null) {
566
+ let bestDist = 96;
567
+ for (const a of prepared) {
568
+ const dist = Math.hypot(nx - a.cx, ny - a.cy);
569
+ if (dist < bestDist) {
570
+ bestDist = dist;
571
+ best = a;
572
+ }
573
+ }
574
+ }
575
+ }
576
+ if (best === null) {
577
+ const rawName = String(node.name || "").replace(/\s+/g, " ").trim().toLowerCase();
578
+ if (rawName.length >= 4 && rawName !== "link" && rawName !== "a" && rawName !== "button") {
579
+ for (const a of prepared) {
580
+ if (!a.name || a.name.length < 4) continue;
581
+ if (a.name.includes(rawName) || rawName.includes(a.name)) {
582
+ best = a;
583
+ break;
584
+ }
585
+ const tokens = rawName.split(/[^0-9A-Za-z\u0080-\uffff]+/).filter((t) => t.length >= 4);
586
+ if (tokens.some((t) => a.name.includes(t))) {
587
+ best = a;
588
+ break;
589
+ }
590
+ }
591
+ }
592
+ }
593
+ if (best === null) continue;
594
+ node.href = best.href;
595
+ node.priority = 0;
596
+ attached += 1;
597
+ }
598
+ return attached;
599
+ }
600
+
601
+ // src/host/browser-agent/playwright-snapshot.ts
602
+ var PLAYWRIGHT_DRIVER_VERSION = "pw-0.1.0";
603
+ var PLAYWRIGHT_REF_ATTR = "data-dsh-ba-ref";
604
+ var MAX_NODES = 80;
605
+ var HARVEST_PAGE_SNAPSHOT_SOURCE = `"use strict";
606
+ var REF = "data-dsh-ba-ref";
607
+ var SELECTOR = [
608
+ "a[href]",
609
+ "button",
610
+ "input:not([type=\\"hidden\\"])",
611
+ "textarea",
612
+ "select",
613
+ "[role=\\"button\\"]",
614
+ "[role=\\"link\\"]",
615
+ "[role=\\"textbox\\"]",
616
+ "[role=\\"checkbox\\"]",
617
+ "[role=\\"radio\\"]",
618
+ "[role=\\"menuitem\\"]",
619
+ "[role=\\"tab\\"]",
620
+ "[role=\\"option\\"]",
621
+ "[role=\\"switch\\"]",
622
+ "[contenteditable=\\"true\\"]"
623
+ ].join(",");
624
+ var cleared = document.querySelectorAll("[" + REF + "]");
625
+ for (var ci = 0; ci < cleared.length; ci++) cleared[ci].removeAttribute(REF);
626
+ var interactive = [];
627
+ var seen = [];
628
+ function roleOf(el) {
629
+ var explicit = el.getAttribute("role");
630
+ if (explicit) return explicit;
631
+ var tag = el.tagName.toLowerCase();
632
+ if (tag === "a") return "link";
633
+ if (tag === "button") return "button";
634
+ if (tag === "select") return "combobox";
635
+ if (tag === "textarea") return "textbox";
636
+ if (tag === "input") {
637
+ var type = (el.getAttribute("type") || "text").toLowerCase();
638
+ if (type === "checkbox") return "checkbox";
639
+ if (type === "radio") return "radio";
640
+ if (type === "submit" || type === "button") return "button";
641
+ return "textbox";
642
+ }
643
+ if (el.getAttribute("contenteditable") === "true") return "textbox";
644
+ return tag;
645
+ }
646
+ function nameOf(el) {
647
+ var labelled = el.getAttribute("aria-label");
648
+ if (labelled && labelled.trim()) return labelled.trim().slice(0, 120);
649
+ var labelledBy = el.getAttribute("aria-labelledby");
650
+ if (labelledBy) {
651
+ var ids = labelledBy.split(/\\s+/);
652
+ var parts = [];
653
+ for (var i = 0; i < ids.length; i++) {
654
+ var node = document.getElementById(ids[i]);
655
+ if (node === null) continue;
656
+ var t = (node.innerText || node.textContent || "").trim();
657
+ if (t) parts.push(t);
658
+ }
659
+ if (parts.length > 0) return parts.join(" ").slice(0, 120);
660
+ }
661
+ if (el.tagName === "INPUT" || el.tagName === "TEXTAREA") {
662
+ var ph = el.getAttribute("placeholder");
663
+ if (ph && ph.trim()) return ph.trim().slice(0, 120);
664
+ }
665
+ var text = (el.innerText || el.textContent || "").replace(/\\s+/g, " ").trim();
666
+ if (text) return text.slice(0, 120);
667
+ return el.tagName.toLowerCase();
668
+ }
669
+ function alreadySeen(el) {
670
+ for (var i = 0; i < seen.length; i++) if (seen[i] === el) return true;
671
+ return false;
672
+ }
673
+ function pushEl(el, forceHref) {
674
+ if (!(el instanceof HTMLElement) || alreadySeen(el)) return;
675
+ var style = getComputedStyle(el);
676
+ if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return;
677
+ var rect = el.getBoundingClientRect();
678
+ if (rect.width < 1 || rect.height < 1) return;
679
+ seen.push(el);
680
+ var type = (el.getAttribute("type") || "").toLowerCase();
681
+ var sensitive = type === "password"
682
+ || el.getAttribute("autocomplete") === "current-password"
683
+ || el.getAttribute("autocomplete") === "new-password";
684
+ var anchor = typeof el.closest === "function" ? el.closest("a[href]") : null;
685
+ var hrefRaw = forceHref
686
+ || (anchor && anchor.href ? String(anchor.href) : "")
687
+ || (el.tagName === "A" && el.href ? String(el.href) : "")
688
+ || "";
689
+ var href = /^https?:\\/\\//i.test(hrefRaw) ? hrefRaw : "";
690
+ interactive.push({
691
+ role: roleOf(el),
692
+ name: sensitive ? (nameOf(el) || "password") : nameOf(el),
693
+ tag: el.tagName.toLowerCase(),
694
+ href: href,
695
+ x: rect.left + rect.width / 2,
696
+ y: rect.top + rect.height / 2,
697
+ w: rect.width,
698
+ h: rect.height,
699
+ sensitive: sensitive,
700
+ priority: href ? 0 : 1
701
+ });
702
+ }
703
+ var allAnchors = document.querySelectorAll("a[href]");
704
+ for (var ai = 0; ai < allAnchors.length; ai++) {
705
+ var a = allAnchors[ai];
706
+ if (!/^https?:\\/\\//i.test(a.href || "")) continue;
707
+ pushEl(a, a.href || "");
708
+ }
709
+ var matched = document.querySelectorAll(SELECTOR);
710
+ for (var mi = 0; mi < matched.length; mi++) pushEl(matched[mi], "");
711
+ interactive.sort(function (a, b) { return a.priority - b.priority; });
712
+ var anchors = [];
713
+ var seenHref = {};
714
+ function pushAnchor(el, hrefOverride) {
715
+ var href = hrefOverride || "";
716
+ try {
717
+ if (!href && el.href) href = String(el.href);
718
+ if (!href) href = el.getAttribute("href") || "";
719
+ if (href.indexOf("//") === 0) href = location.protocol + href;
720
+ if (href.charAt(0) === "/") href = new URL(href, location.href).href;
721
+ } catch (e) {
722
+ return;
723
+ }
724
+ if (!/^https?:\\/\\//i.test(href)) return;
725
+ var rect = el.getBoundingClientRect();
726
+ var key = href + "@" + Math.round(rect.left) + "," + Math.round(rect.top);
727
+ if (seenHref[key]) return;
728
+ seenHref[key] = true;
729
+ var name = (el.getAttribute("aria-label") || el.innerText || "")
730
+ .replace(/\\s+/g, " ")
731
+ .trim()
732
+ .slice(0, 120);
733
+ anchors.push({
734
+ href: href,
735
+ name: name || href,
736
+ x: rect.left,
737
+ y: rect.top,
738
+ w: rect.width,
739
+ h: rect.height
740
+ });
741
+ }
742
+ var hrefEls = document.querySelectorAll("a[href], area[href]");
743
+ for (var hi = 0; hi < hrefEls.length; hi++) pushAnchor(hrefEls[hi], "");
744
+ var dataEls = document.querySelectorAll("[data-href],[data-url],[data-target-url],[data-link]");
745
+ var dataAttrs = ["data-href", "data-url", "data-target-url", "data-link"];
746
+ for (var di = 0; di < dataEls.length; di++) {
747
+ for (var dai = 0; dai < dataAttrs.length; dai++) {
748
+ var raw = dataEls[di].getAttribute(dataAttrs[dai]);
749
+ if (raw) pushAnchor(dataEls[di], raw);
750
+ }
751
+ }
752
+ var textPreview = "";
753
+ try {
754
+ var root = document.querySelector("main, article, [role=\\"main\\"]") || document.body;
755
+ textPreview = ((root && root.innerText) || "").replace(/\\s+/g, " ").trim().slice(0, 2000);
756
+ } catch (e) {
757
+ textPreview = "";
758
+ }
759
+ return { interactive: interactive, anchors: anchors, textPreview: textPreview };
760
+ `;
761
+ var STAMP_REFS_SOURCE = `"use strict";
762
+ var attr = __dsh.attr;
763
+ var records = __dsh.records;
764
+ var cleared = document.querySelectorAll("[" + attr + "]");
765
+ for (var i = 0; i < cleared.length; i++) cleared[i].removeAttribute(attr);
766
+ for (var ri = 0; ri < records.length; ri++) {
767
+ var rec = records[ri];
768
+ var hit = document.elementFromPoint(rec.x, rec.y);
769
+ var target = hit;
770
+ if (target && target.nodeType === 3) target = target.parentElement;
771
+ if (!target) continue;
772
+ var preferred = target.closest
773
+ ? (target.closest("a[href], button, input, textarea, select, [role=\\"link\\"], [role=\\"button\\"], [contenteditable=\\"true\\"]") || target)
774
+ : target;
775
+ preferred.setAttribute(attr, String(rec.ref));
776
+ }
777
+ `;
778
+ async function capturePlaywrightSnapshot(page) {
779
+ const harvest = await page.evaluate(`(() => { ${HARVEST_PAGE_SNAPSHOT_SOURCE} })()`);
780
+ const proximityNodes = harvest.interactive.map((item) => ({
781
+ href: item.href,
782
+ name: item.name,
783
+ x: item.x,
784
+ y: item.y,
785
+ priority: item.priority
786
+ }));
787
+ const proximityAnchors = harvest.anchors.map((item) => ({
788
+ href: item.href,
789
+ name: item.name,
790
+ x: item.x,
791
+ y: item.y,
792
+ w: item.w,
793
+ h: item.h
794
+ }));
795
+ const proximityHits = attachHrefByProximity(proximityNodes, proximityAnchors);
796
+ const rows = proximityNodes.map((node, index) => {
797
+ const item = harvest.interactive[index];
798
+ const href = typeof node.href === "string" && /^https?:\/\//i.test(node.href) ? node.href : "";
799
+ return {
800
+ name: node.name || item?.name || "link",
801
+ role: item?.role || "link",
802
+ tag: item?.tag || "a",
803
+ href,
804
+ x: typeof node.x === "number" ? node.x : 0,
805
+ y: typeof node.y === "number" ? node.y : 0,
806
+ sensitive: item?.sensitive === true,
807
+ priority: node.priority ?? (href ? 0 : 1)
808
+ };
809
+ });
810
+ const knownHrefs = new Set(rows.map((r) => r.href).filter((h) => h !== ""));
811
+ for (const anchor of proximityAnchors) {
812
+ if (knownHrefs.has(anchor.href)) continue;
813
+ knownHrefs.add(anchor.href);
814
+ rows.push({
815
+ name: anchor.name || anchor.href,
816
+ role: "link",
817
+ tag: "a",
818
+ href: anchor.href,
819
+ x: anchor.x + anchor.w / 2,
820
+ y: anchor.y + anchor.h / 2,
821
+ sensitive: false,
822
+ priority: 0
823
+ });
824
+ }
825
+ rows.sort((a, b) => a.priority - b.priority);
826
+ const limited = rows.slice(0, MAX_NODES);
827
+ const nodes = [];
828
+ const refs = /* @__PURE__ */ new Map();
829
+ for (const row of limited) {
830
+ const ref = nodes.length + 1;
831
+ nodes.push({
832
+ ref,
833
+ role: row.role,
834
+ name: row.name,
835
+ tag: row.tag,
836
+ ...row.href !== "" ? { href: row.href } : {},
837
+ ...row.sensitive ? { sensitive: true } : {}
838
+ });
839
+ refs.set(ref, {
840
+ ref,
841
+ role: row.role,
842
+ name: row.name,
843
+ href: row.href,
844
+ x: row.x,
845
+ y: row.y,
846
+ tag: row.tag
847
+ });
848
+ }
849
+ await page.evaluate(
850
+ ({ source, attr, records }) => {
851
+ const run = new Function("__dsh", source);
852
+ run({ attr, records });
853
+ },
854
+ {
855
+ source: STAMP_REFS_SOURCE,
856
+ attr: PLAYWRIGHT_REF_ATTR,
857
+ records: [...refs.values()].map((r) => ({ ref: r.ref, x: r.x, y: r.y }))
858
+ }
859
+ );
860
+ const withHref = nodes.filter((n) => typeof n.href === "string" && n.href !== "").length;
861
+ const body = {
862
+ url: page.url(),
863
+ title: await page.title().catch(() => ""),
864
+ nodes,
865
+ textPreview: harvest.textPreview,
866
+ tabId: 1,
867
+ source: harvest.anchors.length > 0 || proximityHits > 0 ? "playwright+anchors" : "playwright",
868
+ extensionVersion: PLAYWRIGHT_DRIVER_VERSION,
869
+ anchorCount: harvest.anchors.length,
870
+ ...withHref === 0 ? {
871
+ note: `No http(s) href on interactive refs yet (anchors_in_dom=${harvest.anchors.length}). browser_wait then browser_snapshot again.`
872
+ } : proximityHits > 0 ? { note: `Bound ${proximityHits} ref(s) to nearby document hrefs (anchors_in_dom=${harvest.anchors.length}).` } : { note: `anchors_in_dom=${harvest.anchors.length}` }
873
+ };
874
+ return { body, refs };
875
+ }
876
+
877
+ // src/host/browser-agent/auto-nav.ts
878
+ function pathKey(raw) {
879
+ try {
880
+ const u = new URL(raw);
881
+ const path = u.pathname.replace(/\/+$/u, "") || "/";
882
+ return `${u.origin}${path}`;
883
+ } catch {
884
+ return raw.split("?")[0]?.split("#")[0]?.replace(/\/+$/u, "") ?? raw;
885
+ }
886
+ }
887
+ function pathsDiffer(a, b) {
888
+ return pathKey(a) !== pathKey(b);
889
+ }
890
+ function normalizeName(raw) {
891
+ return raw.toLowerCase().replace(/\s+/gu, " ").trim();
892
+ }
893
+ function namesLooselyMatch(preferredName, linkName) {
894
+ const a = normalizeName(preferredName);
895
+ const b = normalizeName(linkName);
896
+ if (a.length < 2 || b.length < 2) return false;
897
+ if (a === b) return true;
898
+ if (a.includes(b) || b.includes(a)) return true;
899
+ const tokensA = new Set(a.split(/[^\p{L}\p{N}]+/u).filter((t) => t.length >= 4));
900
+ if (tokensA.size === 0) return false;
901
+ for (const token of b.split(/[^\p{L}\p{N}]+/u)) {
902
+ if (token.length >= 4 && tokensA.has(token)) return true;
903
+ }
904
+ return false;
905
+ }
906
+ function pickAutoNavigateHref(links, beforeUrl, preferredName = "") {
907
+ if (preferredName.trim() === "") return null;
908
+ let beforeOrigin = "";
909
+ try {
910
+ beforeOrigin = new URL(beforeUrl).origin;
911
+ } catch {
912
+ beforeOrigin = "";
913
+ }
914
+ let best = null;
915
+ let bestDepth = -1;
916
+ for (const item of links) {
917
+ if (!/^https?:\/\//i.test(item.href) || !pathsDiffer(beforeUrl, item.href)) continue;
918
+ if (!namesLooselyMatch(preferredName, item.name || item.href)) continue;
919
+ try {
920
+ const u = new URL(item.href);
921
+ if (beforeOrigin !== "" && u.origin !== beforeOrigin) continue;
922
+ const depth = u.pathname.split("/").filter(Boolean).length;
923
+ if (depth > bestDepth) {
924
+ bestDepth = depth;
925
+ best = item.href;
926
+ }
927
+ } catch {
928
+ }
929
+ }
930
+ return best;
931
+ }
932
+
933
+ // src/host/browser-agent/playwright-driver.ts
934
+ var PlaywrightDriver = class {
935
+ kind = "playwright";
936
+ profileDirOption;
937
+ preferenceOption;
938
+ profileRoot;
939
+ headless;
940
+ context = null;
941
+ page = null;
942
+ lastError = null;
943
+ channel = null;
944
+ launchedProfileDir = null;
945
+ lastRefs = /* @__PURE__ */ new Map();
946
+ constructor(options) {
947
+ this.profileDirOption = options.profileDir;
948
+ this.preferenceOption = options.preference ?? "auto";
949
+ this.profileRoot = options.profileRoot;
950
+ this.headless = options.headless === true;
951
+ }
952
+ currentPreference() {
953
+ return typeof this.preferenceOption === "function" ? this.preferenceOption() : this.preferenceOption;
954
+ }
955
+ currentProfileDir() {
956
+ return typeof this.profileDirOption === "function" ? this.profileDirOption() : this.profileDirOption;
957
+ }
958
+ /** Latest snapshot refs — used by the click/type path. */
959
+ refOf(ref) {
960
+ return this.lastRefs.get(ref);
961
+ }
962
+ status() {
963
+ const ready = this.context !== null && this.page !== null && !this.page.isClosed();
964
+ const preference = this.currentPreference();
965
+ return {
966
+ kind: "playwright",
967
+ ready,
968
+ listening: this.context !== null,
969
+ lastError: this.lastError,
970
+ endpoint: this.channel !== null ? `playwright:${this.channel}` : `playwright:unlaunched:${preference}`
971
+ };
972
+ }
973
+ async ensureReady(startUrl) {
974
+ const preference = this.currentPreference();
975
+ const profileDir = this.currentProfileDir();
976
+ const wantChannel = playwrightChannelOrder(preference, process.platform)[0];
977
+ const runningOk = this.context !== null && this.page !== null && !this.page.isClosed() && this.channel === wantChannel && this.launchedProfileDir === profileDir;
978
+ if (runningOk) {
979
+ if (typeof startUrl === "string" && /^https?:\/\//i.test(startUrl)) {
980
+ const current = this.page.url();
981
+ if (current === "about:blank" || current === "") {
982
+ await this.page.goto(startUrl, { waitUntil: "domcontentloaded" }).catch(() => void 0);
983
+ }
984
+ }
985
+ return;
986
+ }
987
+ if (this.context !== null) {
988
+ await this.dispose().catch(() => void 0);
989
+ }
990
+ this.stopPreferenceProfiles(profileDir);
991
+ mkdirSync(profileDir, { recursive: true });
992
+ const order = [...playwrightChannelOrder(preference, process.platform)];
993
+ let lastDetail = "";
994
+ for (const channel of order) {
995
+ const kind = channel === "msedge" ? "edge" : "chrome";
996
+ const resolved = resolveBrowserExecutable(kind);
997
+ if (preference === "chrome" || preference === "edge") {
998
+ if (resolved === null || resolved.kind !== preference) {
999
+ lastDetail = `${preference} is not installed or not found on PATH`;
1000
+ this.lastError = lastDetail;
1001
+ continue;
1002
+ }
1003
+ } else if (resolved === null) {
1004
+ lastDetail = `${kind} is not installed or not found on PATH`;
1005
+ this.lastError = lastDetail;
1006
+ continue;
1007
+ }
1008
+ try {
1009
+ const context = await chromium.launchPersistentContext(profileDir, {
1010
+ executablePath: resolved.executable,
1011
+ headless: this.headless,
1012
+ // Avoid Edge/Chrome infobar: "unsupported command-line flag: --no-sandbox".
1013
+ chromiumSandbox: true,
1014
+ ignoreDefaultArgs: ["--no-sandbox"],
1015
+ viewport: this.headless ? { width: 1280, height: 800 } : null,
1016
+ args: ["--no-first-run", "--no-default-browser-check", "--disable-default-apps"]
1017
+ });
1018
+ this.context = context;
1019
+ this.channel = channel;
1020
+ this.launchedProfileDir = profileDir;
1021
+ this.lastError = null;
1022
+ this.page = context.pages()[0] ?? await context.newPage();
1023
+ if (typeof startUrl === "string" && /^https?:\/\//i.test(startUrl)) {
1024
+ await this.page.goto(startUrl, { waitUntil: "domcontentloaded" }).catch(() => void 0);
1025
+ }
1026
+ context.on("close", () => {
1027
+ this.context = null;
1028
+ this.page = null;
1029
+ this.launchedProfileDir = null;
1030
+ this.lastRefs.clear();
1031
+ });
1032
+ return;
1033
+ } catch (error) {
1034
+ lastDetail = error instanceof Error ? error.message : String(error);
1035
+ this.lastError = lastDetail;
1036
+ }
1037
+ }
1038
+ const hint = preference === "chrome" || preference === "edge" ? ` Preference is locked to ${preference} (no silent fallback).` : "";
1039
+ throw new Error(
1040
+ `Playwright could not launch a persistent browser (tried ${order.join(", ")}): ${lastDetail}.${hint}`
1041
+ );
1042
+ }
1043
+ stopPreferenceProfiles(activeProfileDir) {
1044
+ stopAgentBrowserProcesses(activeProfileDir);
1045
+ if (this.launchedProfileDir !== null && this.launchedProfileDir !== activeProfileDir) {
1046
+ stopAgentBrowserProcesses(this.launchedProfileDir);
1047
+ }
1048
+ if (this.profileRoot !== void 0) {
1049
+ for (const slot of ["auto", "chrome", "edge"]) {
1050
+ const dir = browserAgentProfileDirFor(this.profileRoot, slot);
1051
+ if (dir !== activeProfileDir) stopAgentBrowserProcesses(dir);
1052
+ }
1053
+ }
1054
+ }
1055
+ async requirePage() {
1056
+ await this.ensureReady();
1057
+ if (this.page === null || this.page.isClosed()) {
1058
+ throw new Error("Playwright page is not available");
1059
+ }
1060
+ return this.page;
1061
+ }
1062
+ async pageStatus() {
1063
+ const page = await this.requirePage();
1064
+ return {
1065
+ connected: true,
1066
+ url: page.url(),
1067
+ title: await page.title().catch(() => ""),
1068
+ tabId: 1,
1069
+ bound: true
1070
+ };
1071
+ }
1072
+ async navigate(url) {
1073
+ const page = await this.requirePage();
1074
+ await page.goto(url, { waitUntil: "domcontentloaded" });
1075
+ await settlePage(page);
1076
+ this.lastRefs.clear();
1077
+ return {
1078
+ url: page.url(),
1079
+ title: await page.title().catch(() => ""),
1080
+ tabId: 1
1081
+ };
1082
+ }
1083
+ async snapshot() {
1084
+ const page = await this.requirePage();
1085
+ const { body, refs } = await capturePlaywrightSnapshot(page);
1086
+ this.lastRefs = new Map(refs);
1087
+ return body;
1088
+ }
1089
+ async extract(input = {}) {
1090
+ const page = await this.requirePage();
1091
+ const maxChars = Math.min(Math.max(input.maxChars ?? 8e3, 500), 5e4);
1092
+ const text3 = await page.locator('main, article, [role="main"], body').first().innerText().catch(() => "");
1093
+ const clipped = text3.replace(/\s+/g, " ").trim();
1094
+ return {
1095
+ url: page.url(),
1096
+ title: await page.title().catch(() => ""),
1097
+ text: clipped.slice(0, maxChars),
1098
+ truncated: clipped.length > maxChars,
1099
+ ...input.focus === void 0 || input.focus.trim() === "" ? {} : { focus: input.focus.trim() },
1100
+ tabId: 1
1101
+ };
1102
+ }
1103
+ async click(ref) {
1104
+ const page = await this.requirePage();
1105
+ const record2 = this.lastRefs.get(ref);
1106
+ if (record2 === void 0) {
1107
+ throw new Error(`Unknown ref ${ref}; call browser_snapshot first`);
1108
+ }
1109
+ const beforeUrl = page.url();
1110
+ const href = /^https?:\/\//i.test(record2.href) ? record2.href : "";
1111
+ const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
1112
+ const count = await locator.count().catch(() => 0);
1113
+ if (count === 0) {
1114
+ return this.clickAtPoint(page, beforeUrl, href, record2);
1115
+ }
1116
+ const context = page.context();
1117
+ const popupWait = context.waitForEvent("page", { timeout: 5e3 }).catch(() => null);
1118
+ await locator.hover({ timeout: 3e3 }).catch(() => void 0);
1119
+ await sleep(180);
1120
+ if (href !== "" && pathsDiffer(beforeUrl, href)) {
1121
+ await page.goto(href, { waitUntil: "domcontentloaded" });
1122
+ await settlePage(page);
1123
+ this.lastRefs.clear();
1124
+ const after = page.url();
1125
+ return {
1126
+ url: after,
1127
+ title: await page.title().catch(() => ""),
1128
+ changed: pathsDiffer(beforeUrl, after),
1129
+ href,
1130
+ tabId: 1,
1131
+ warning: "Opened this ref's href after snapshot bound a nearby document link."
1132
+ };
1133
+ }
1134
+ const navWait = page.waitForURL((url) => pathsDiffer(beforeUrl, url.toString()), { timeout: 5e3 }).catch(() => null);
1135
+ await locator.click({ timeout: 5e3 });
1136
+ await Promise.race([navWait, sleep(800)]);
1137
+ const popup = await popupWait;
1138
+ if (popup !== null && !popup.isClosed()) {
1139
+ const adopted = await adoptPopup(popup, beforeUrl);
1140
+ if (adopted) {
1141
+ this.page = popup;
1142
+ this.lastRefs.clear();
1143
+ await settlePage(popup);
1144
+ return {
1145
+ url: popup.url(),
1146
+ title: await popup.title().catch(() => ""),
1147
+ changed: true,
1148
+ ...href !== "" ? { href } : {},
1149
+ tabId: tabIdOf(context, popup),
1150
+ warning: "Click opened a new tab; rebound the browser-agent session to it."
1151
+ };
1152
+ }
1153
+ }
1154
+ await settlePage(page);
1155
+ let afterUrl = page.url();
1156
+ let changed = pathsDiffer(beforeUrl, afterUrl);
1157
+ if (!changed) {
1158
+ const deadline = Date.now() + 3e3;
1159
+ while (Date.now() < deadline && !changed) {
1160
+ await sleep(300);
1161
+ afterUrl = page.url();
1162
+ changed = pathsDiffer(beforeUrl, afterUrl);
1163
+ }
1164
+ }
1165
+ let followedHref = false;
1166
+ if (!changed && href !== "" && pathsDiffer(beforeUrl, href)) {
1167
+ await page.goto(href, { waitUntil: "domcontentloaded" });
1168
+ await settlePage(page);
1169
+ afterUrl = page.url();
1170
+ changed = pathsDiffer(beforeUrl, afterUrl);
1171
+ followedHref = changed;
1172
+ }
1173
+ this.lastRefs.clear();
1174
+ let pageLinks = [];
1175
+ if (!changed && href === "") {
1176
+ pageLinks = await listHttpAnchors(page);
1177
+ }
1178
+ return {
1179
+ url: afterUrl,
1180
+ title: await page.title().catch(() => ""),
1181
+ changed,
1182
+ tabId: 1,
1183
+ ...href !== "" ? { href } : {},
1184
+ ...pageLinks.length > 0 ? { pageLinks: pageLinks.slice(0, 8) } : {},
1185
+ ...followedHref ? { warning: "Click missed; opened this ref's own href via navigation." } : !changed ? {
1186
+ warning: href !== "" ? "Pathname unchanged; could not open this ref's href. browser_navigate to this ref's href or pick another ref with href=." : pageLinks.length > 0 ? "Pathname unchanged and this ref has no href (common for SPA cards). Prefer a snapshot ref that lists href=, or browser_navigate once to a page_links URL below \u2014 do NOT re-click this ref." : "Pathname unchanged and this ref has no href. browser_snapshot again, pick a ref with href=, or browser_navigate to a known URL. Do NOT re-click this ref."
1187
+ } : {}
1188
+ };
1189
+ }
1190
+ async clickAtPoint(page, beforeUrl, href, record2) {
1191
+ if (href !== "" && pathsDiffer(beforeUrl, href)) {
1192
+ await page.goto(href, { waitUntil: "domcontentloaded" });
1193
+ await settlePage(page);
1194
+ this.lastRefs.clear();
1195
+ const after = page.url();
1196
+ return {
1197
+ url: after,
1198
+ title: await page.title().catch(() => ""),
1199
+ changed: pathsDiffer(beforeUrl, after),
1200
+ href,
1201
+ tabId: 1,
1202
+ warning: "Ref stamp missing; opened this ref's href directly."
1203
+ };
1204
+ }
1205
+ await page.mouse.move(record2.x, record2.y);
1206
+ await sleep(120);
1207
+ await page.mouse.click(record2.x, record2.y);
1208
+ await settlePage(page);
1209
+ const afterUrl = page.url();
1210
+ const changed = pathsDiffer(beforeUrl, afterUrl);
1211
+ this.lastRefs.clear();
1212
+ return {
1213
+ url: afterUrl,
1214
+ title: await page.title().catch(() => ""),
1215
+ changed,
1216
+ tabId: 1,
1217
+ ...href !== "" ? { href } : {},
1218
+ ...!changed ? {
1219
+ warning: "Pathname unchanged after coordinate click. browser_snapshot again or browser_navigate by href."
1220
+ } : {}
1221
+ };
1222
+ }
1223
+ async type(ref, text3) {
1224
+ const page = await this.requirePage();
1225
+ if (this.lastRefs.get(ref) === void 0) {
1226
+ throw new Error(`Unknown ref ${ref}; call browser_snapshot first`);
1227
+ }
1228
+ const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
1229
+ const count = await locator.count().catch(() => 0);
1230
+ if (count === 0) {
1231
+ throw new Error(`Ref ${ref} is not stamped in the DOM; call browser_snapshot again`);
1232
+ }
1233
+ await locator.click({ timeout: 3e3 }).catch(() => void 0);
1234
+ const tag = await locator.evaluate((el) => el.tagName.toLowerCase()).catch(() => "");
1235
+ if (tag === "input" || tag === "textarea" || tag === "select") {
1236
+ await locator.fill(text3, { timeout: 5e3 });
1237
+ } else {
1238
+ await locator.pressSequentially(text3, { delay: 10 });
1239
+ }
1240
+ await settlePage(page);
1241
+ this.lastRefs.clear();
1242
+ return {
1243
+ url: page.url(),
1244
+ title: await page.title().catch(() => ""),
1245
+ changed: false,
1246
+ tabId: 1
1247
+ };
1248
+ }
1249
+ async scroll(dy) {
1250
+ const page = await this.requirePage();
1251
+ await page.mouse.wheel(0, dy);
1252
+ await sleep(80);
1253
+ return { url: page.url(), title: await page.title().catch(() => ""), changed: false, tabId: 1 };
1254
+ }
1255
+ async wait(input = {}) {
1256
+ const page = await this.requirePage();
1257
+ const timeoutMs = Math.min(Math.max(input.timeoutMs ?? 8e3, 200), 6e4);
1258
+ let matched = true;
1259
+ if (typeof input.text === "string" && input.text.trim() !== "") {
1260
+ try {
1261
+ await page.getByText(input.text.trim()).first().waitFor({ timeout: timeoutMs });
1262
+ matched = true;
1263
+ } catch {
1264
+ matched = false;
1265
+ }
1266
+ } else {
1267
+ await settlePage(page, timeoutMs);
1268
+ }
1269
+ return {
1270
+ url: page.url(),
1271
+ title: await page.title().catch(() => ""),
1272
+ matched,
1273
+ tabId: 1
1274
+ };
1275
+ }
1276
+ async screenshot() {
1277
+ const page = await this.requirePage();
1278
+ const buf = await page.screenshot({ type: "png", fullPage: false });
1279
+ return { mime: "image/png", base64: buf.toString("base64"), tabId: 1 };
1280
+ }
1281
+ async listTabs() {
1282
+ await this.ensureReady();
1283
+ const pages = this.context?.pages() ?? [];
1284
+ return {
1285
+ tabs: await Promise.all(pages.map(async (p, index) => ({
1286
+ tabId: index + 1,
1287
+ title: await p.title().catch(() => ""),
1288
+ url: p.url(),
1289
+ active: p === this.page,
1290
+ bound: p === this.page
1291
+ }))),
1292
+ boundTabId: this.page ? pages.indexOf(this.page) + 1 : null
1293
+ };
1294
+ }
1295
+ async followTab(tabId, _activate = false) {
1296
+ await this.ensureReady();
1297
+ const pages = this.context?.pages() ?? [];
1298
+ const page = pages[tabId - 1];
1299
+ if (page === void 0) throw new Error(`No Playwright page for tabId ${tabId}`);
1300
+ this.page = page;
1301
+ this.lastRefs.clear();
1302
+ return { tabId, url: page.url(), title: await page.title().catch(() => "") };
1303
+ }
1304
+ async bind(tabId, _sessionId) {
1305
+ return this.followTab(tabId, true);
1306
+ }
1307
+ async dispose() {
1308
+ const ctx = this.context;
1309
+ const profileDir = this.launchedProfileDir;
1310
+ this.context = null;
1311
+ this.page = null;
1312
+ this.channel = null;
1313
+ this.launchedProfileDir = null;
1314
+ this.lastRefs.clear();
1315
+ if (ctx !== null) {
1316
+ await ctx.close().catch(() => void 0);
1317
+ }
1318
+ if (profileDir !== null) {
1319
+ stopAgentBrowserProcesses(profileDir);
1320
+ }
1321
+ }
1322
+ };
1323
+ function sleep(ms) {
1324
+ return new Promise((resolve16) => {
1325
+ setTimeout(resolve16, ms);
1326
+ });
1327
+ }
1328
+ async function settlePage(page, quietMs = 800) {
1329
+ await page.waitForLoadState("domcontentloaded").catch(() => void 0);
1330
+ await Promise.race([
1331
+ page.waitForLoadState("networkidle").catch(() => void 0),
1332
+ sleep(Math.min(Math.max(quietMs, 100), 3e3))
1333
+ ]);
1334
+ await sleep(50);
1335
+ }
1336
+ async function adoptPopup(popup, beforeUrl) {
1337
+ const deadline = Date.now() + 4e3;
1338
+ while (Date.now() < deadline) {
1339
+ if (popup.isClosed()) return false;
1340
+ const url2 = popup.url();
1341
+ if (/^https?:\/\//i.test(url2) && pathsDiffer(beforeUrl, url2)) return true;
1342
+ await sleep(250);
1343
+ }
1344
+ const url = popup.isClosed() ? "" : popup.url();
1345
+ return /^https?:\/\//i.test(url) && pathsDiffer(beforeUrl, url);
1346
+ }
1347
+ function tabIdOf(context, page) {
1348
+ const pages = context.pages();
1349
+ const index = pages.indexOf(page);
1350
+ return index >= 0 ? index + 1 : 1;
1351
+ }
1352
+ async function listHttpAnchors(page) {
1353
+ return page.evaluate(`(() => {
1354
+ var out = [];
1355
+ var seen = {};
1356
+ var nodes = document.querySelectorAll("a[href], area[href]");
1357
+ for (var i = 0; i < nodes.length; i++) {
1358
+ var el = nodes[i];
1359
+ var href = "";
1360
+ try {
1361
+ href = String(el.href || el.getAttribute("href") || "");
1362
+ if (href.indexOf("//") === 0) href = location.protocol + href;
1363
+ if (href.charAt(0) === "/") href = new URL(href, location.href).href;
1364
+ } catch (e) {
1365
+ continue;
1366
+ }
1367
+ if (!/^https?:\\/\\//i.test(href) || seen[href]) continue;
1368
+ seen[href] = true;
1369
+ var name = (el.getAttribute("aria-label") || el.innerText || "")
1370
+ .replace(/\\s+/g, " ")
1371
+ .trim()
1372
+ .slice(0, 120);
1373
+ out.push({ href: href, name: name || href });
1374
+ if (out.length >= 24) break;
1375
+ }
1376
+ return out;
1377
+ })()`);
1378
+ }
1379
+
1380
+ // src/host/browser-agent/prompt.ts
1381
+ var SECTION_NAME = "agent-enhancer:browser-agent";
1382
+ var GUIDANCE = [
1383
+ "## Browser agent (Desktop dedicated Chrome/Edge)",
1384
+ "When the user asks to open a website, browse the web, click pages, fill forms, read on-page content, log into a site, or verify UI in a real browser, you MUST use the browser_* tools \u2014 do not only describe steps or ask the user to open a browser manually.",
1385
+ "Goal phases: (1) reach the target page once, (2) stay and observe/extract, (3) answer the user. Do not keep navigating without a new user goal.",
1386
+ "Preferred loop: browser_navigate (or reuse a tab) \u2192 browser_wait if slow \u2192 browser_snapshot \u2192 click/type/scroll using listed refs \u2192 browser_snapshot or browser_extract again.",
1387
+ "Perception is accessibility-tree based (Playwright MCP style): prefer refs that show href=\u2026. browser_screenshot exists but is optional \u2014 do not wait for screenshots; dead clicks are usually missing hrefs on SPA cards, not missing vision.",
1388
+ "If browser_click leaves pathname unchanged and that ref has an http(s) href, the host may open that same href once. If the tool says the ref has no href / lists page_links: do NOT re-click the same ref \u2014 browser_navigate once to a page_links URL or pick another ref that lists href=. Never invent URLs.",
1389
+ "Below-the-fold or long content: browser_scroll \u2192 browser_wait \u2192 browser_extract. Report what extract returns; do not hop to unrelated pages.",
1390
+ "The dedicated browser auto-launches when needed; never tell the user to click \u201CLaunch browser agent\u201D unless the tool error says so.",
1391
+ "Mutation tools may pause for an in-app Allow card \u2014 wait for allow/deny.",
1392
+ "Login / captcha / 2FA: NEVER type passwords. When needs_human appears, call browser_ask_user and STOP until the user finishes in the dedicated window. A bare \u201CLog in\u201D chip on a normal page is not a wall.",
1393
+ "Do not invent page content or refs. Prefer finishing the user task over exploring more pages."
1394
+ ].join("\n");
1395
+ function registerBrowserAgentPrompt(ctx) {
1396
+ let disposeSection;
1397
+ try {
1398
+ const service = ctx.get("systemPrompt");
1399
+ if (service === void 0 || typeof service.section !== "function") {
1400
+ return () => void 0;
1401
+ }
1402
+ const order = typeof service.getSectionOrder === "function" ? service.getSectionOrder("TOOL_COMPUTER_USE") + 10 : 3010;
1403
+ disposeSection = service.section({
1404
+ name: SECTION_NAME,
1405
+ order,
1406
+ text: GUIDANCE,
1407
+ interpolate: false
1408
+ });
1409
+ } catch {
1410
+ return () => void 0;
1411
+ }
1412
+ return () => {
1413
+ try {
1414
+ disposeSection?.();
1415
+ } catch {
1416
+ }
1417
+ };
1418
+ }
1419
+
1420
+ // src/host/browser-agent/session-state.ts
1421
+ var MAX_AUDIT = 40;
1422
+ var BrowserSessionState = class {
1423
+ tabBySession = /* @__PURE__ */ new Map();
1424
+ sessionByTab = /* @__PURE__ */ new Map();
1425
+ needsHumanBySession = /* @__PURE__ */ new Map();
1426
+ /** Refs from the latest successful browser_snapshot for this session. */
1427
+ lastRefsBySession = /* @__PURE__ */ new Map();
1428
+ /** Optional href per ref from the latest snapshot (follow only that ref's href after a dead click). */
1429
+ lastHrefBySession = /* @__PURE__ */ new Map();
1430
+ /** Optional accessible name per ref from the latest snapshot (name-matched auto-nav). */
1431
+ lastNameBySession = /* @__PURE__ */ new Map();
1432
+ /** Refs that already failed a click with no navigation — block re-click until a fresh snapshot. */
1433
+ deadClickRefsBySession = /* @__PURE__ */ new Map();
1434
+ /** Last http(s) page URL for approval origin when pageStatus is blank/about:blank. */
1435
+ lastHttpUrlBySession = /* @__PURE__ */ new Map();
1436
+ conflict = null;
1437
+ audit = [];
1438
+ bind(sessionId, tabId) {
1439
+ const prev = this.tabBySession.get(sessionId);
1440
+ if (prev !== void 0 && prev !== tabId) this.sessionByTab.delete(prev);
1441
+ const owner = this.sessionByTab.get(tabId);
1442
+ if (owner !== void 0 && owner !== sessionId) this.tabBySession.delete(owner);
1443
+ this.tabBySession.set(sessionId, tabId);
1444
+ this.sessionByTab.set(tabId, sessionId);
1445
+ if (this.conflict?.sessionId === sessionId) this.conflict = null;
1446
+ }
1447
+ tabOf(sessionId) {
1448
+ return this.tabBySession.get(sessionId);
1449
+ }
1450
+ sessionOf(tabId) {
1451
+ return this.sessionByTab.get(tabId);
1452
+ }
1453
+ clearSession(sessionId) {
1454
+ const tabId = this.tabBySession.get(sessionId);
1455
+ this.tabBySession.delete(sessionId);
1456
+ if (tabId !== void 0) this.sessionByTab.delete(tabId);
1457
+ this.needsHumanBySession.delete(sessionId);
1458
+ this.lastRefsBySession.delete(sessionId);
1459
+ this.lastHrefBySession.delete(sessionId);
1460
+ this.lastNameBySession.delete(sessionId);
1461
+ this.deadClickRefsBySession.delete(sessionId);
1462
+ this.lastHttpUrlBySession.delete(sessionId);
1463
+ if (this.conflict?.sessionId === sessionId) this.conflict = null;
1464
+ for (let i = this.audit.length - 1; i >= 0; i -= 1) {
1465
+ if (this.audit[i]?.sessionId === sessionId) this.audit.splice(i, 1);
1466
+ }
1467
+ }
1468
+ setLastRefs(sessionId, refs) {
1469
+ this.lastRefsBySession.set(sessionId, new Set(refs.filter((ref) => Number.isFinite(ref))));
1470
+ this.deadClickRefsBySession.delete(sessionId);
1471
+ }
1472
+ setLastHrefs(sessionId, hrefs) {
1473
+ this.lastHrefBySession.set(sessionId, hrefs);
1474
+ }
1475
+ setLastNames(sessionId, names) {
1476
+ this.lastNameBySession.set(sessionId, names);
1477
+ }
1478
+ clearLastRefs(sessionId) {
1479
+ this.lastRefsBySession.delete(sessionId);
1480
+ this.lastHrefBySession.delete(sessionId);
1481
+ this.lastNameBySession.delete(sessionId);
1482
+ }
1483
+ markDeadClickRef(sessionId, ref) {
1484
+ const set = this.deadClickRefsBySession.get(sessionId) ?? /* @__PURE__ */ new Set();
1485
+ set.add(ref);
1486
+ this.deadClickRefsBySession.set(sessionId, set);
1487
+ }
1488
+ isDeadClickRef(sessionId, ref) {
1489
+ return this.deadClickRefsBySession.get(sessionId)?.has(ref) === true;
1490
+ }
1491
+ hasRef(sessionId, ref) {
1492
+ return this.lastRefsBySession.get(sessionId)?.has(ref) === true;
1493
+ }
1494
+ hrefOfRef(sessionId, ref) {
1495
+ return this.lastHrefBySession.get(sessionId)?.get(ref);
1496
+ }
1497
+ nameOfRef(sessionId, ref) {
1498
+ return this.lastNameBySession.get(sessionId)?.get(ref);
1499
+ }
1500
+ rememberHttpUrl(sessionId, url) {
1501
+ if (!/^https?:\/\//i.test(url)) return;
1502
+ this.lastHttpUrlBySession.set(sessionId, url);
1503
+ }
1504
+ lastHttpUrl(sessionId) {
1505
+ return this.lastHttpUrlBySession.get(sessionId);
1506
+ }
1507
+ lastRefList(sessionId) {
1508
+ return [...this.lastRefsBySession.get(sessionId) ?? []];
1509
+ }
1510
+ setConflict(conflict) {
1511
+ this.conflict = conflict;
1512
+ }
1513
+ clearConflict(sessionId) {
1514
+ if (sessionId === void 0 || this.conflict?.sessionId === sessionId) this.conflict = null;
1515
+ }
1516
+ currentConflict() {
1517
+ return this.conflict;
1518
+ }
1519
+ setNeedsHuman(sessionId, detail) {
1520
+ this.needsHumanBySession.set(sessionId, detail);
1521
+ }
1522
+ clearNeedsHuman(sessionId) {
1523
+ this.needsHumanBySession.delete(sessionId);
1524
+ }
1525
+ needsHuman(sessionId) {
1526
+ return this.needsHumanBySession.get(sessionId);
1527
+ }
1528
+ anyNeedsHuman() {
1529
+ for (const [sessionId, detail] of this.needsHumanBySession) {
1530
+ return { sessionId, detail };
1531
+ }
1532
+ return null;
1533
+ }
1534
+ record(entry) {
1535
+ this.audit.push({ ...entry, at: Date.now() });
1536
+ while (this.audit.length > MAX_AUDIT) this.audit.shift();
1537
+ }
1538
+ recentAudit(limit = 12) {
1539
+ return this.audit.slice(-limit);
1540
+ }
1541
+ };
1542
+
1543
+ // src/host/browser-agent/tools.ts
1544
+ import { defineTool } from "@deepseek-ai/dsh-tools";
1545
+ var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
1546
+ function textTool(name2, description, parameters, execute, timeoutMs = 6e4) {
1547
+ return defineTool({
1548
+ name: name2,
1549
+ description,
1550
+ parameters,
1551
+ output: {
1552
+ schema: { type: "string" },
1553
+ render: (_args, value) => [{ type: "text", text: String(value) }]
1554
+ },
1555
+ timeoutMs,
1556
+ isConcurrencySafe: () => false,
1557
+ async execute(args, exec) {
1558
+ return await execute(args, exec);
1559
+ }
1560
+ });
1561
+ }
1562
+ function formatSnapshot(body, extra) {
1563
+ const lines = [
1564
+ `url: ${body.url}`,
1565
+ `title: ${body.title}`,
1566
+ body.tabId !== void 0 ? `tabId: ${body.tabId}` : null,
1567
+ body.rebound === true ? "note: rebound to focused tab (previous bound tab was gone)" : null,
1568
+ body.conflict === true ? "note: tab focus conflict pending \u2014 user must Follow or Stay in Desktop" : null,
1569
+ body.needsHuman === true ? [
1570
+ "needs_human: true",
1571
+ "Action: Login/captcha/auth wall. Call browser_ask_user NOW and STOP. Wait for the user to finish in the dedicated browser, then browser_snapshot / browser_extract.",
1572
+ "Do NOT type passwords or solve captchas."
1573
+ ].join("\n") : null,
1574
+ typeof body.source === "string" ? `snapshot_source: ${body.source}` : null,
1575
+ typeof body.extensionVersion === "string" ? `extension: ${body.extensionVersion}` : null,
1576
+ typeof body.anchorCount === "number" ? `anchors_in_dom: ${body.anchorCount}` : null,
1577
+ typeof body.note === "string" && body.note.trim() !== "" ? `note: ${body.note.trim()}` : null,
1578
+ ...extra ?? [],
1579
+ "interactive (prefer refs that include href=\u2026 ; never invent URLs; re-snapshot after navigation):",
1580
+ ...body.nodes.slice(0, 80).map((node) => `- [${node.ref}] ${node.role}${node.tag !== void 0 ? `/${node.tag}` : ""}${node.sensitive === true ? " [sensitive]" : ""}${typeof node.href === "string" && node.href !== "" ? ` href=${JSON.stringify(node.href)}` : ""} ${JSON.stringify(node.name)}`),
1581
+ "text_preview (short \u2014 use browser_extract for long/below-fold content):",
1582
+ body.textPreview.slice(0, 2e3)
1583
+ ];
1584
+ return lines.filter((line) => line !== null).join("\n");
1585
+ }
1586
+ function sessionIdOf(exec) {
1587
+ const id = exec.agent?.session?.id;
1588
+ if (typeof id === "string" && id.trim() !== "") return id.trim();
1589
+ return "unknown-session";
1590
+ }
1591
+ function formatBridgeError(error) {
1592
+ const message = error instanceof Error ? error.message : String(error);
1593
+ if (/click_noop:|click_blocked:/i.test(message)) {
1594
+ return `${message}
1595
+ Do not retry the same browser_click. Prefer browser_navigate or a ref with href=.`;
1596
+ }
1597
+ if (/No element for ref/i.test(message) || /Refs are only valid/i.test(message)) {
1598
+ return `${message}
1599
+ Action: call browser_snapshot, then retry with a fresh ref. Never invent refs.`;
1600
+ }
1601
+ if (/about:blank|not an http\(s\) page|Cannot inject into|Cannot access contents of url/i.test(message)) {
1602
+ return `${message}
1603
+ Action: The dedicated browser was still on about:blank. Call browser_navigate to the https URL again, wait, then browser_snapshot. Do not click yet.`;
1604
+ }
1605
+ if (/all_urls|activeTab|unserializable|Page injection failed|Debugger attach failed|Cannot automate restricted URL/i.test(message)) {
1606
+ return `${message}
1607
+ Action: STOP clicking. Tell the user to fully quit the dedicated browser window and click \u201CLaunch browser agent\u201D again (extension v0.2.5+). Do not invent refs or keep calling browser_click.`;
1608
+ }
1609
+ if (/not typeable/i.test(message)) {
1610
+ return `${message}
1611
+ Action: call browser_snapshot and choose a textbox / input ref.`;
1612
+ }
1613
+ if (/extension not connected|WebSocket|not listening|did not connect|Could not launch/i.test(message)) {
1614
+ return `${message}
1615
+ Action: Browser agent tried to auto-launch the dedicated browser. If it still fails, ask the user to open the right-sidebar \u201CBrowser agent\u201D tab and launch once, then retry the same browser_* tool. Do not ask them to open their everyday Chrome manually.`;
1616
+ }
1617
+ if (/Tab focus conflict/i.test(message)) {
1618
+ return `${message}
1619
+ Action: ask the user to choose Follow or Stay in the Desktop browser-agent card.`;
1620
+ }
1621
+ if (error?.needsHuman === true || /needs_human|captcha|验证码|人机验证/i.test(message)) {
1622
+ return `${message}
1623
+ needs_human: true
1624
+ Action: Call browser_ask_user now (blocking). Do not retry clicks. After it returns, call browser_snapshot.`;
1625
+ }
1626
+ return message;
1627
+ }
1628
+ async function runBridge(fn) {
1629
+ try {
1630
+ return await fn();
1631
+ } catch (error) {
1632
+ throw new Error(formatBridgeError(error));
1633
+ }
1634
+ }
1635
+ function maskTypeSummary(text3) {
1636
+ if (text3.length <= 2) return "\u2022\u2022";
1637
+ return `${text3.slice(0, 1)}\u2026(${text3.length} chars)`;
1638
+ }
1639
+ function driverOf(options) {
1640
+ const value = options.driver;
1641
+ return typeof value === "function" ? value() : value;
1642
+ }
1643
+ function registerBrowserTools(ctx, options) {
1644
+ const disposers = [];
1645
+ const guardEnabled = () => {
1646
+ if (!options.enabled()) {
1647
+ throw new Error("Browser agent is disabled in settings (\u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent).");
1648
+ }
1649
+ };
1650
+ const rememberTab = async (sessionId, tabId) => {
1651
+ if (typeof tabId !== "number") return;
1652
+ options.sessions.bind(sessionId, tabId);
1653
+ try {
1654
+ await driverOf(options).bind(tabId, sessionId);
1655
+ } catch {
1656
+ }
1657
+ };
1658
+ const ensureSessionTab = async (sessionId) => {
1659
+ const tabId = options.sessions.tabOf(sessionId);
1660
+ if (tabId === void 0) return;
1661
+ try {
1662
+ await driverOf(options).bind(tabId, sessionId);
1663
+ } catch {
1664
+ }
1665
+ };
1666
+ const ensureConnected = async (startUrl) => {
1667
+ if (options.alignPreference !== void 0) {
1668
+ await options.alignPreference(startUrl);
1669
+ return;
1670
+ }
1671
+ await driverOf(options).ensureReady(startUrl);
1672
+ };
1673
+ const requireMutation = async (exec, tool, summary, url) => {
1674
+ const sessionId = sessionIdOf(exec);
1675
+ let effectiveUrl = typeof url === "string" && /^https?:\/\//i.test(url) ? url : void 0;
1676
+ if (effectiveUrl === void 0) {
1677
+ effectiveUrl = options.sessions.lastHttpUrl(sessionId);
1678
+ } else {
1679
+ options.sessions.rememberHttpUrl(sessionId, effectiveUrl);
1680
+ }
1681
+ const decision = await options.approval.requestApproval({
1682
+ sessionId,
1683
+ tool,
1684
+ summary,
1685
+ url: effectiveUrl,
1686
+ signal: exec.signal
1687
+ });
1688
+ if (decision === "deny") {
1689
+ options.sessions.record({
1690
+ sessionId,
1691
+ tool,
1692
+ summary,
1693
+ url: effectiveUrl ?? url,
1694
+ outcome: "denied"
1695
+ });
1696
+ throw new Error("User denied this browser action.");
1697
+ }
1698
+ };
1699
+ const noteHuman = (sessionId, body, error) => {
1700
+ if (body.needsHuman === true || error?.needsHuman === true) {
1701
+ options.sessions.setNeedsHuman(sessionId, "Login or captcha required in the bound browser tab");
1702
+ return;
1703
+ }
1704
+ if (/needs_human|login|captcha|验证码|登录/i.test(error instanceof Error ? error.message : String(error ?? ""))) {
1705
+ options.sessions.setNeedsHuman(sessionId, "Login or captcha required in the bound browser tab");
1706
+ return;
1707
+ }
1708
+ options.sessions.clearNeedsHuman(sessionId);
1709
+ };
1710
+ const focusBoundTab = async (sessionId, tabId) => {
1711
+ const id = tabId ?? options.sessions.tabOf(sessionId);
1712
+ if (typeof id !== "number") return;
1713
+ try {
1714
+ await driverOf(options).followTab(id, true);
1715
+ } catch {
1716
+ }
1717
+ };
1718
+ const pauseForHuman = async (input) => {
1719
+ options.sessions.setNeedsHuman(input.sessionId, input.detail);
1720
+ await focusBoundTab(input.sessionId, input.tabId);
1721
+ try {
1722
+ return await options.human.waitForHuman({
1723
+ sessionId: input.sessionId,
1724
+ prompt: input.prompt,
1725
+ detail: input.detail,
1726
+ ...input.url === void 0 ? {} : { url: input.url },
1727
+ signal: input.signal
1728
+ });
1729
+ } finally {
1730
+ if (options.human.current()?.sessionId !== input.sessionId) {
1731
+ options.sessions.clearNeedsHuman(input.sessionId);
1732
+ }
1733
+ }
1734
+ };
1735
+ const rememberSnapshotRefs = (sessionId, body) => {
1736
+ options.sessions.setLastRefs(sessionId, body.nodes.map((node) => node.ref));
1737
+ const hrefs = /* @__PURE__ */ new Map();
1738
+ const names = /* @__PURE__ */ new Map();
1739
+ for (const node of body.nodes) {
1740
+ if (typeof node.href === "string" && /^https?:\/\//iu.test(node.href)) {
1741
+ hrefs.set(node.ref, node.href);
1742
+ }
1743
+ if (typeof node.name === "string" && node.name.trim() !== "") {
1744
+ names.set(node.ref, node.name.trim());
1745
+ }
1746
+ }
1747
+ options.sessions.setLastHrefs(sessionId, hrefs);
1748
+ options.sessions.setLastNames(sessionId, names);
1749
+ };
1750
+ const requireFreshRef = (sessionId, ref, tool) => {
1751
+ if (options.sessions.hasRef(sessionId, ref)) return;
1752
+ const known = options.sessions.lastRefList(sessionId);
1753
+ if (known.length === 0) {
1754
+ throw new Error(
1755
+ `${tool}: ref ${ref} is not from a browser_snapshot in this session. Call browser_snapshot first and use a listed [ref]. Never invent refs.`
1756
+ );
1757
+ }
1758
+ throw new Error(
1759
+ `${tool}: ref ${ref} is not in the latest browser_snapshot (have: ${known.slice(0, 24).join(", ")}${known.length > 24 ? ", \u2026" : ""}). Call browser_snapshot again and pick a listed ref \u2014 do not guess.`
1760
+ );
1761
+ };
1762
+ const snapshotWithHumanPause = async (sessionId, exec) => {
1763
+ let body = await runBridge(() => driverOf(options).snapshot());
1764
+ await rememberTab(sessionId, body.tabId);
1765
+ options.sessions.rememberHttpUrl(sessionId, body.url);
1766
+ rememberSnapshotRefs(sessionId, body);
1767
+ if (body.nodes.length === 0) {
1768
+ options.sessions.clearLastRefs(sessionId);
1769
+ options.sessions.record({
1770
+ sessionId,
1771
+ tool: "browser_snapshot",
1772
+ summary: `Empty snapshot ${body.url}`,
1773
+ url: body.url,
1774
+ outcome: "error"
1775
+ });
1776
+ return [
1777
+ formatSnapshot(body, [
1778
+ "warning: zero interactive refs \u2014 page may still be loading, be a blank/restricted document, or injection failed.",
1779
+ "Action: browser_wait then browser_snapshot again. Do NOT call browser_click with invented refs."
1780
+ ])
1781
+ ].join("\n");
1782
+ }
1783
+ if (body.needsHuman !== true) {
1784
+ options.sessions.clearNeedsHuman(sessionId);
1785
+ options.sessions.record({
1786
+ sessionId,
1787
+ tool: "browser_snapshot",
1788
+ summary: `Snapshot ${body.url} (${body.nodes.length} refs)`,
1789
+ url: body.url,
1790
+ outcome: "ok"
1791
+ });
1792
+ return formatSnapshot(body);
1793
+ }
1794
+ options.sessions.record({
1795
+ sessionId,
1796
+ tool: "browser_snapshot",
1797
+ summary: `Needs human: ${body.url}`,
1798
+ url: body.url,
1799
+ outcome: "needs_human"
1800
+ });
1801
+ const prompt = [
1802
+ "Login, captcha, or verification is required in the dedicated browser window.",
1803
+ `Page: ${body.title || "(no title)"}`,
1804
+ `URL: ${body.url}`,
1805
+ "Complete it there, then click \u201CI\u2019m done \u2014 continue\u201D. Do not use your everyday browser."
1806
+ ].join(" ");
1807
+ const status = await pauseForHuman({
1808
+ sessionId,
1809
+ prompt,
1810
+ detail: `Login/captcha: ${body.title || body.url}`,
1811
+ url: body.url,
1812
+ tabId: body.tabId,
1813
+ signal: exec.signal
1814
+ });
1815
+ if (status === "cancelled") {
1816
+ throw new Error(
1817
+ "Human login wait was cancelled. Call browser_ask_user again when the user is ready, or ask what they want next."
1818
+ );
1819
+ }
1820
+ options.sessions.clearNeedsHuman(sessionId);
1821
+ const after = await runBridge(() => driverOf(options).snapshot());
1822
+ await rememberTab(sessionId, after.tabId);
1823
+ rememberSnapshotRefs(sessionId, after);
1824
+ noteHuman(sessionId, after);
1825
+ options.sessions.record({
1826
+ sessionId,
1827
+ tool: "browser_snapshot",
1828
+ summary: `After human: ${after.url}`,
1829
+ url: after.url,
1830
+ outcome: after.needsHuman === true ? "needs_human" : "ok"
1831
+ });
1832
+ return formatSnapshot(after, [
1833
+ "user_ack: continued",
1834
+ after.needsHuman === true ? "note: page still looks like login/captcha \u2014 call browser_ask_user again if the user is not done, otherwise continue with a different approach and tell the user what you see." : "note: user finished the human step \u2014 continue the original task with these fresh refs."
1835
+ ]);
1836
+ };
1837
+ disposers.push(ctx.tools.register(textTool(
1838
+ "browser_status",
1839
+ "Check the Desktop dedicated-browser bridge (Chrome/Edge + extension): connection, bound tab URL/title/tabId. Use this for any real-browser / webpage / on-page task. Auto-launches the dedicated browser when disconnected \u2014 do not ask the user to launch manually first.",
1840
+ {},
1841
+ async (_args, exec) => {
1842
+ guardEnabled();
1843
+ const sessionId = sessionIdOf(exec);
1844
+ const st = driverOf(options).status();
1845
+ if (!st.listening) {
1846
+ return [
1847
+ `driver: ${st.kind}`,
1848
+ "bridge: not listening",
1849
+ st.port !== void 0 ? `port: ${st.port}` : null,
1850
+ `error: ${st.lastError ?? "not started"}`
1851
+ ].filter((line) => line !== null).join("\n");
1852
+ }
1853
+ if (!st.ready) {
1854
+ try {
1855
+ await ensureConnected();
1856
+ } catch (error) {
1857
+ return [
1858
+ `driver: ${st.kind}`,
1859
+ st.endpoint !== void 0 ? `bridge: listening on ${st.endpoint}` : "bridge: listening",
1860
+ "extension: disconnected",
1861
+ formatBridgeError(error)
1862
+ ].join("\n");
1863
+ }
1864
+ }
1865
+ try {
1866
+ await ensureSessionTab(sessionId);
1867
+ const tab = await runBridge(() => driverOf(options).pageStatus());
1868
+ await rememberTab(sessionId, tab.tabId);
1869
+ return [
1870
+ `driver: ${driverOf(options).kind}`,
1871
+ "bridge: ok",
1872
+ "extension: connected",
1873
+ `url: ${tab.url}`,
1874
+ `title: ${tab.title}`,
1875
+ `tabId: ${tab.tabId}`,
1876
+ `sessionBound: ${options.sessions.tabOf(sessionId) === tab.tabId ? "yes" : "no"}`,
1877
+ `bound: ${tab.bound === false ? "no" : "yes"}`,
1878
+ tab.rebound === true ? "note: rebound to focused tab" : null,
1879
+ tab.conflict === true ? "note: tab focus conflict pending" : null
1880
+ ].filter((line) => line !== null).join("\n");
1881
+ } catch (error) {
1882
+ noteHuman(sessionId, {}, error);
1883
+ return `driver: ${driverOf(options).kind}
1884
+ bridge: listening
1885
+ extension: connected but status failed: ${formatBridgeError(error)}`;
1886
+ }
1887
+ }
1888
+ )));
1889
+ disposers.push(ctx.tools.register(textTool(
1890
+ "browser_snapshot",
1891
+ "Read the dedicated browser tab: URL, title, numbered interactive refs, text preview. ALWAYS call this before browser_click / browser_type and ONLY click refs listed here \u2014 never invent refs. Password fields are sensitive. Only a real login/captcha wall auto-pauses for the user (a homepage \u201C\u767B\u5F55\u201D link does not). Auto-launches when disconnected. Read-only; no approval.",
1892
+ {},
1893
+ async (_args, exec) => {
1894
+ guardEnabled();
1895
+ const sessionId = sessionIdOf(exec);
1896
+ await ensureConnected();
1897
+ await ensureSessionTab(sessionId);
1898
+ try {
1899
+ return await snapshotWithHumanPause(sessionId, exec);
1900
+ } catch (error) {
1901
+ noteHuman(sessionId, {}, error);
1902
+ options.sessions.record({
1903
+ sessionId,
1904
+ tool: "browser_snapshot",
1905
+ summary: "Snapshot failed",
1906
+ outcome: "error"
1907
+ });
1908
+ throw error;
1909
+ }
1910
+ },
1911
+ HUMAN_WAIT_TIMEOUT_MS
1912
+ )));
1913
+ disposers.push(ctx.tools.register(textTool(
1914
+ "browser_ask_user",
1915
+ "Pause the agent turn and wait for the user (login, captcha, 2FA, or any step only a human can do). Brings the bound tab forward, shows a Desktop Continue card, and BLOCKS until they click Continue \u2014 then returns so you can browser_snapshot and proceed. Prefer this over chatting and spinning. Never type passwords or solve captchas with browser_type/browser_click. Use when needs_human is set, the page is blocked, or you are unsure.",
1916
+ {
1917
+ prompt: {
1918
+ type: "string",
1919
+ required: true,
1920
+ description: "Short message for the user (their language): what to do in the dedicated browser window."
1921
+ }
1922
+ },
1923
+ async (args, exec) => {
1924
+ guardEnabled();
1925
+ const sessionId = sessionIdOf(exec);
1926
+ const prompt = String(args.prompt ?? "").trim();
1927
+ if (prompt === "") throw new Error("prompt is required");
1928
+ await ensureConnected();
1929
+ await ensureSessionTab(sessionId);
1930
+ let url;
1931
+ let tabId;
1932
+ try {
1933
+ const tab = await driverOf(options).pageStatus();
1934
+ url = tab.url;
1935
+ tabId = tab.tabId;
1936
+ await rememberTab(sessionId, tab.tabId);
1937
+ } catch {
1938
+ }
1939
+ options.sessions.record({
1940
+ sessionId,
1941
+ tool: "browser_ask_user",
1942
+ summary: prompt.slice(0, 160),
1943
+ ...url === void 0 ? {} : { url },
1944
+ outcome: "needs_human"
1945
+ });
1946
+ const status = await pauseForHuman({
1947
+ sessionId,
1948
+ prompt,
1949
+ detail: prompt.slice(0, 240),
1950
+ ...url === void 0 ? {} : { url },
1951
+ ...tabId === void 0 ? {} : { tabId },
1952
+ signal: exec.signal
1953
+ });
1954
+ options.sessions.clearNeedsHuman(sessionId);
1955
+ if (status === "cancelled") {
1956
+ return "user_ack: cancelled\nAction: Ask what the user wants next, or call browser_ask_user again.";
1957
+ }
1958
+ options.sessions.record({
1959
+ sessionId,
1960
+ tool: "browser_ask_user",
1961
+ summary: "User continued",
1962
+ ...url === void 0 ? {} : { url },
1963
+ outcome: "ok"
1964
+ });
1965
+ return [
1966
+ "user_ack: continued",
1967
+ `prompt_was: ${prompt}`,
1968
+ "Action: call browser_snapshot now, then continue the task. If still on login/captcha, call browser_ask_user again."
1969
+ ].join("\n");
1970
+ },
1971
+ HUMAN_WAIT_TIMEOUT_MS
1972
+ )));
1973
+ disposers.push(ctx.tools.register(textTool(
1974
+ "browser_navigate",
1975
+ "Open or navigate the dedicated Desktop browser to an http(s) URL. Prefer this over telling the user to open a browser themselves. Auto-launches when disconnected. Requires approval unless the origin is already allowed. After navigation call browser_snapshot (it will pause for login/captcha if needed).",
1976
+ {
1977
+ url: {
1978
+ type: "string",
1979
+ required: true,
1980
+ description: "Absolute http(s) URL to open in the bound tab."
1981
+ }
1982
+ },
1983
+ async (args, exec) => {
1984
+ guardEnabled();
1985
+ const sessionId = sessionIdOf(exec);
1986
+ const url = String(args.url ?? "").trim();
1987
+ if (url === "") throw new Error("url is required");
1988
+ await ensureConnected(url);
1989
+ await ensureSessionTab(sessionId);
1990
+ await requireMutation(exec, "browser_navigate", `Navigate to ${url}`, url);
1991
+ try {
1992
+ const result = await runBridge(() => driverOf(options).navigate(url));
1993
+ await rememberTab(sessionId, result.tabId);
1994
+ options.sessions.rememberHttpUrl(sessionId, result.url);
1995
+ options.sessions.record({
1996
+ sessionId,
1997
+ tool: "browser_navigate",
1998
+ summary: `Navigate to ${url}`,
1999
+ url: result.url,
2000
+ outcome: "ok"
2001
+ });
2002
+ options.onMutation?.({ sessionId, tool: "browser_navigate", url: result.url });
2003
+ return `navigated
2004
+ url: ${result.url}
2005
+ title: ${result.title}
2006
+ Action: call browser_snapshot next. For long page content use browser_extract after scroll if needed.`;
2007
+ } catch (error) {
2008
+ noteHuman(sessionId, {}, error);
2009
+ options.sessions.record({
2010
+ sessionId,
2011
+ tool: "browser_navigate",
2012
+ summary: `Navigate to ${url}`,
2013
+ url,
2014
+ outcome: "error"
2015
+ });
2016
+ throw error;
2017
+ }
2018
+ }
2019
+ )));
2020
+ disposers.push(ctx.tools.register(textTool(
2021
+ "browser_click",
2022
+ "Click an interactive element by ref from the latest browser_snapshot. Requires approval. If the ref is missing/stale, browser_snapshot first. Dead clicks may follow that same ref\u2019s http(s) href only \u2014 never invent other URLs. Do NOT use this to submit passwords or solve captchas \u2014 call browser_ask_user instead. Auto-launches when disconnected.",
2023
+ {
2024
+ ref: {
2025
+ type: "number",
2026
+ required: true,
2027
+ description: "Element ref from the latest browser_snapshot."
2028
+ }
2029
+ },
2030
+ async (args, exec) => {
2031
+ guardEnabled();
2032
+ const sessionId = sessionIdOf(exec);
2033
+ const ref = Number(args.ref);
2034
+ if (!Number.isFinite(ref)) throw new Error("ref must be a number");
2035
+ await ensureConnected();
2036
+ await ensureSessionTab(sessionId);
2037
+ let url;
2038
+ try {
2039
+ url = (await driverOf(options).pageStatus()).url;
2040
+ } catch {
2041
+ url = void 0;
2042
+ }
2043
+ requireFreshRef(sessionId, ref, "browser_click");
2044
+ if (options.sessions.isDeadClickRef(sessionId, ref)) {
2045
+ throw new Error(
2046
+ `click_blocked: ref ${ref} already failed with no navigation. Do NOT browser_click it again. browser_navigate to a content URL, or browser_snapshot and use a ref that lists href=.`
2047
+ );
2048
+ }
2049
+ const snapshotHref = options.sessions.hrefOfRef(sessionId, ref);
2050
+ await requireMutation(exec, "browser_click", `Click ref ${ref}`, url);
2051
+ try {
2052
+ const beforeUrl = typeof url === "string" ? url : "";
2053
+ let result = await runBridge(() => driverOf(options).click(ref));
2054
+ await rememberTab(sessionId, result.tabId);
2055
+ const href = typeof result.href === "string" && result.href !== "" ? result.href : snapshotHref ?? "";
2056
+ let navigated = beforeUrl !== "" && pathsDiffer(beforeUrl, result.url);
2057
+ let warning = typeof result.warning === "string" ? result.warning : "";
2058
+ let resolvedHref = href;
2059
+ let followTarget = !navigated && resolvedHref !== "" && /^https?:\/\//i.test(resolvedHref) && pathsDiffer(beforeUrl || result.url, resolvedHref) ? resolvedHref : "";
2060
+ if (followTarget !== "") {
2061
+ const followed = await runBridge(() => driverOf(options).navigate(followTarget));
2062
+ await rememberTab(sessionId, followed.tabId);
2063
+ result = { ...followed, href: followTarget, changed: true };
2064
+ resolvedHref = followTarget;
2065
+ navigated = beforeUrl === "" || pathsDiffer(beforeUrl, followed.url);
2066
+ warning = navigated ? "Click left pathname unchanged; opened this ref\u2019s own href via navigate." : "Opened this ref\u2019s href but pathname still looks unchanged.";
2067
+ }
2068
+ const pageLinks = (result.pageLinks ?? []).filter((item) => typeof item.href === "string" && item.href !== "").map((item) => ({ href: item.href, name: item.name || "" }));
2069
+ const preferredName = options.sessions.nameOfRef(sessionId, ref) || "";
2070
+ if (!navigated && followTarget === "") {
2071
+ const autoHref = pickAutoNavigateHref(pageLinks, beforeUrl || result.url, preferredName);
2072
+ if (autoHref !== null) {
2073
+ const followed = await runBridge(() => driverOf(options).navigate(autoHref));
2074
+ await rememberTab(sessionId, followed.tabId);
2075
+ result = { ...followed, href: autoHref, changed: true };
2076
+ resolvedHref = autoHref;
2077
+ followTarget = autoHref;
2078
+ navigated = beforeUrl === "" || pathsDiffer(beforeUrl, followed.url);
2079
+ warning = navigated ? "Click was a no-op; host auto-navigated to a name-matched document link." : "Host tried name-matched auto-navigate after dead click but pathname still unchanged.";
2080
+ }
2081
+ }
2082
+ options.sessions.clearLastRefs(sessionId);
2083
+ if (!navigated) {
2084
+ options.sessions.markDeadClickRef(sessionId, ref);
2085
+ options.sessions.record({
2086
+ sessionId,
2087
+ tool: "browser_click",
2088
+ summary: `Click ref ${ref} (noop)`,
2089
+ url: result.url,
2090
+ outcome: "error"
2091
+ });
2092
+ const matched = pickAutoNavigateHref(pageLinks, beforeUrl || result.url, preferredName);
2093
+ throw new Error(
2094
+ [
2095
+ `click_noop: ref ${ref} did not change the page (no navigable href for this control).`,
2096
+ "Do NOT call browser_click on this ref again.",
2097
+ matched !== null ? `Next: browser_navigate to the matched link: ${matched}` : "Next: browser_wait, browser_snapshot again, and use a ref that lists href=. Do not invent URLs. If still missing, ask the user for a direct content URL.",
2098
+ `url: ${result.url}`
2099
+ ].join(" ")
2100
+ );
2101
+ }
2102
+ options.sessions.record({
2103
+ sessionId,
2104
+ tool: "browser_click",
2105
+ summary: `Click ref ${ref}`,
2106
+ url: result.url,
2107
+ outcome: "ok"
2108
+ });
2109
+ options.onMutation?.({ sessionId, tool: "browser_click", url: result.url });
2110
+ return [
2111
+ `clicked ref ${ref}`,
2112
+ "changed: yes",
2113
+ `url: ${result.url}`,
2114
+ `title: ${result.title}`,
2115
+ resolvedHref !== "" ? `href: ${resolvedHref}` : null,
2116
+ warning !== "" ? `warning: ${warning}` : null,
2117
+ "Action: browser_snapshot, then browser_extract for page content (scroll first if needed). Do not keep opening more pages without a new goal."
2118
+ ].filter((line) => line !== null).join("\n");
2119
+ } catch (error) {
2120
+ noteHuman(sessionId, {}, error);
2121
+ if (!/click_noop:|click_blocked:/i.test(error instanceof Error ? error.message : String(error))) {
2122
+ options.sessions.record({
2123
+ sessionId,
2124
+ tool: "browser_click",
2125
+ summary: `Click ref ${ref}`,
2126
+ url,
2127
+ outcome: "error"
2128
+ });
2129
+ }
2130
+ throw error;
2131
+ }
2132
+ }
2133
+ )));
2134
+ disposers.push(ctx.tools.register(textTool(
2135
+ "browser_type",
2136
+ "Type non-secret text into a ref from the latest browser_snapshot. Requires approval. NEVER type passwords, OTP/2FA codes, payment details, or captcha answers \u2014 call browser_ask_user and let the user type in the dedicated browser. Prefer textbox/input refs; refresh refs with browser_snapshot if stale. Typed values are masked in audit logs.",
2137
+ {
2138
+ ref: {
2139
+ type: "number",
2140
+ required: true,
2141
+ description: "Element ref from the latest browser_snapshot."
2142
+ },
2143
+ text: {
2144
+ type: "string",
2145
+ required: true,
2146
+ description: "Non-secret text to type. Do not pass passwords or OTP codes."
2147
+ }
2148
+ },
2149
+ async (args, exec) => {
2150
+ guardEnabled();
2151
+ const sessionId = sessionIdOf(exec);
2152
+ const ref = Number(args.ref);
2153
+ const text3 = String(args.text ?? "");
2154
+ if (!Number.isFinite(ref)) throw new Error("ref must be a number");
2155
+ await ensureConnected();
2156
+ await ensureSessionTab(sessionId);
2157
+ let url;
2158
+ try {
2159
+ url = (await driverOf(options).pageStatus()).url;
2160
+ } catch {
2161
+ url = void 0;
2162
+ }
2163
+ requireFreshRef(sessionId, ref, "browser_type");
2164
+ await requireMutation(exec, "browser_type", `Type into ref ${ref}: ${maskTypeSummary(text3)}`, url);
2165
+ try {
2166
+ const result = await runBridge(() => driverOf(options).type(ref, text3));
2167
+ await rememberTab(sessionId, result.tabId);
2168
+ options.sessions.clearLastRefs(sessionId);
2169
+ options.sessions.record({
2170
+ sessionId,
2171
+ tool: "browser_type",
2172
+ summary: `Type into ref ${ref}: ${maskTypeSummary(text3)}`,
2173
+ url: result.url,
2174
+ outcome: "ok"
2175
+ });
2176
+ options.onMutation?.({ sessionId, tool: "browser_type", url: result.url });
2177
+ return `typed into ref ${ref}
2178
+ url: ${result.url}
2179
+ title: ${result.title}
2180
+ Action: call browser_snapshot for fresh refs before the next click/type.`;
2181
+ } catch (error) {
2182
+ noteHuman(sessionId, {}, error);
2183
+ options.sessions.record({
2184
+ sessionId,
2185
+ tool: "browser_type",
2186
+ summary: `Type into ref ${ref}`,
2187
+ url,
2188
+ outcome: "error"
2189
+ });
2190
+ throw error;
2191
+ }
2192
+ }
2193
+ )));
2194
+ disposers.push(ctx.tools.register(textTool(
2195
+ "browser_scroll",
2196
+ "Scroll the bound page by dy pixels (positive = down). Use before browser_extract / browser_snapshot for below-the-fold content. Requires approval.",
2197
+ {
2198
+ dy: {
2199
+ type: "number",
2200
+ required: true,
2201
+ description: "Vertical scroll delta in pixels (e.g. 800\u20131400)."
2202
+ }
2203
+ },
2204
+ async (args, exec) => {
2205
+ guardEnabled();
2206
+ const sessionId = sessionIdOf(exec);
2207
+ const dy = Number(args.dy);
2208
+ if (!Number.isFinite(dy)) throw new Error("dy must be a number");
2209
+ await ensureConnected();
2210
+ await ensureSessionTab(sessionId);
2211
+ let url;
2212
+ try {
2213
+ url = (await driverOf(options).pageStatus()).url;
2214
+ } catch {
2215
+ url = void 0;
2216
+ }
2217
+ await requireMutation(exec, "browser_scroll", `Scroll by ${dy}px`, url);
2218
+ try {
2219
+ const result = await runBridge(() => driverOf(options).scroll(dy));
2220
+ await rememberTab(sessionId, result.tabId);
2221
+ options.sessions.record({
2222
+ sessionId,
2223
+ tool: "browser_scroll",
2224
+ summary: `Scroll by ${dy}px`,
2225
+ url: result.url,
2226
+ outcome: "ok"
2227
+ });
2228
+ options.onMutation?.({ sessionId, tool: "browser_scroll", url: result.url });
2229
+ return `scrolled ${dy}px
2230
+ url: ${result.url}
2231
+ title: ${result.title}
2232
+ Action: browser_extract or browser_snapshot next. Do not navigate away unless the user goal requires it.`;
2233
+ } catch (error) {
2234
+ noteHuman(sessionId, {}, error);
2235
+ options.sessions.record({
2236
+ sessionId,
2237
+ tool: "browser_scroll",
2238
+ summary: `Scroll by ${dy}px`,
2239
+ url,
2240
+ outcome: "error"
2241
+ });
2242
+ throw error;
2243
+ }
2244
+ }
2245
+ )));
2246
+ disposers.push(ctx.tools.register(textTool(
2247
+ "browser_extract",
2248
+ "Read visible page text from the dedicated browser (main/article/[role=main]/body). Use for comments, articles, tables, or any long content. Optional focus is echoed as a hint only \u2014 it does not select a site scraper. Prefer this over inventing content. Read-only; no approval. Auto-launches when disconnected.",
2249
+ {
2250
+ focus: {
2251
+ type: "string",
2252
+ description: 'Optional hint for yourself (e.g. "comments", "pricing table"); returned in the tool result, not used to match CSS.'
2253
+ },
2254
+ maxChars: {
2255
+ type: "number",
2256
+ description: "Max characters to return (default 8000, max 20000)."
2257
+ }
2258
+ },
2259
+ async (args, exec) => {
2260
+ guardEnabled();
2261
+ const sessionId = sessionIdOf(exec);
2262
+ const focus = typeof args.focus === "string" ? args.focus.trim() : "";
2263
+ const maxCharsRaw = Number(args.maxChars);
2264
+ const maxChars = Number.isFinite(maxCharsRaw) ? Math.min(Math.max(Math.floor(maxCharsRaw), 500), 2e4) : 8e3;
2265
+ await ensureConnected();
2266
+ await ensureSessionTab(sessionId);
2267
+ try {
2268
+ let result = await runBridge(() => driverOf(options).extract({
2269
+ ...focus === "" ? {} : { focus },
2270
+ maxChars
2271
+ }));
2272
+ await rememberTab(sessionId, result.tabId);
2273
+ const looksLoginGated = (text3) => /sign\s*in\s*to|log\s*in\s*to|请先登录|登录后(?:才能|可以|即可|查看)|captcha|验证码|人机验证/i.test(text3);
2274
+ if (looksLoginGated(result.text)) {
2275
+ options.sessions.record({
2276
+ sessionId,
2277
+ tool: "browser_extract",
2278
+ summary: focus === "" ? "Extract needs human" : `Extract needs human (${focus})`,
2279
+ url: result.url,
2280
+ outcome: "needs_human"
2281
+ });
2282
+ const prompt = [
2283
+ "Login or verification is required to read this page content (e.g. comments).",
2284
+ `Page: ${result.title || "(no title)"}`,
2285
+ `URL: ${result.url}`,
2286
+ "Finish login in the dedicated browser, then click \u201CI\u2019m done \u2014 continue\u201D."
2287
+ ].join(" ");
2288
+ const status = await pauseForHuman({
2289
+ sessionId,
2290
+ prompt,
2291
+ detail: `Login required for page content: ${result.title || result.url}`,
2292
+ url: result.url,
2293
+ tabId: result.tabId,
2294
+ signal: exec.signal
2295
+ });
2296
+ if (status === "cancelled") {
2297
+ throw new Error(
2298
+ "Human login wait was cancelled. Call browser_ask_user again when ready, or ask what they want next."
2299
+ );
2300
+ }
2301
+ options.sessions.clearNeedsHuman(sessionId);
2302
+ result = await runBridge(() => driverOf(options).extract({
2303
+ ...focus === "" ? {} : { focus },
2304
+ maxChars
2305
+ }));
2306
+ await rememberTab(sessionId, result.tabId);
2307
+ }
2308
+ const stillGated = looksLoginGated(result.text);
2309
+ if (stillGated) {
2310
+ options.sessions.setNeedsHuman(sessionId, "Login or captcha required in the bound browser tab");
2311
+ }
2312
+ options.sessions.record({
2313
+ sessionId,
2314
+ tool: "browser_extract",
2315
+ summary: focus === "" ? "Extract page text" : `Extract page text (${focus})`,
2316
+ url: result.url,
2317
+ outcome: stillGated ? "needs_human" : "ok"
2318
+ });
2319
+ const lines = [
2320
+ `url: ${result.url}`,
2321
+ `title: ${result.title}`,
2322
+ focus !== "" ? `focus_hint: ${focus}` : null,
2323
+ `truncated: ${result.truncated ? "yes" : "no"}`,
2324
+ stillGated ? "needs_human: true\nnote: still looks login-gated after human step \u2014 call browser_ask_user again or tell the user what is blocking." : null,
2325
+ "text:",
2326
+ result.text,
2327
+ stillGated ? null : "Action: Answer from this text when possible. If content is missing, browser_scroll then browser_extract again. Do not open unrelated pages."
2328
+ ];
2329
+ return lines.filter((line) => line !== null).join("\n");
2330
+ } catch (error) {
2331
+ noteHuman(sessionId, {}, error);
2332
+ options.sessions.record({
2333
+ sessionId,
2334
+ tool: "browser_extract",
2335
+ summary: "Extract page text",
2336
+ outcome: "error"
2337
+ });
2338
+ throw error;
2339
+ }
2340
+ }
2341
+ )));
2342
+ disposers.push(ctx.tools.register(textTool(
2343
+ "browser_screenshot",
2344
+ "Capture a PNG screenshot of the dedicated browser viewport (base64). Use to show the user a login/captcha wall or when refs are unclear \u2014 then call browser_ask_user so the run pauses until they finish. Prefer browser_snapshot for structure/refs. Read-only; no approval. Auto-launches when disconnected.",
2345
+ {},
2346
+ async (_args, exec) => {
2347
+ guardEnabled();
2348
+ const sessionId = sessionIdOf(exec);
2349
+ await ensureConnected();
2350
+ await ensureSessionTab(sessionId);
2351
+ const shot = await runBridge(() => driverOf(options).screenshot());
2352
+ await rememberTab(sessionId, shot.tabId);
2353
+ const truncated = shot.base64.length > 12e4 ? `${shot.base64.slice(0, 12e4)}\u2026(truncated)` : shot.base64;
2354
+ return [
2355
+ `mime: ${shot.mime}`,
2356
+ `base64_chars: ${shot.base64.length}`,
2357
+ "note: If this shows login/captcha, call browser_ask_user next (do not keep clicking).",
2358
+ "base64:",
2359
+ truncated
2360
+ ].join("\n");
2361
+ }
2362
+ )));
2363
+ disposers.push(ctx.tools.register(textTool(
2364
+ "browser_wait",
2365
+ "Wait until the bound tab finishes loading, or until page text matches (case-insensitive substring). Read-only; no approval. Use after navigate/click on slow pages.",
2366
+ {
2367
+ timeoutMs: {
2368
+ type: "number",
2369
+ description: "Max wait in milliseconds (200\u201360000). Default 8000."
2370
+ },
2371
+ text: {
2372
+ type: "string",
2373
+ description: "Optional substring to wait for in title + body text."
2374
+ }
2375
+ },
2376
+ async (args, exec) => {
2377
+ guardEnabled();
2378
+ const sessionId = sessionIdOf(exec);
2379
+ await ensureConnected();
2380
+ await ensureSessionTab(sessionId);
2381
+ const timeoutMs = args.timeoutMs === void 0 ? void 0 : Number(args.timeoutMs);
2382
+ const text3 = args.text === void 0 ? void 0 : String(args.text);
2383
+ const result = await runBridge(() => driverOf(options).wait({
2384
+ ...timeoutMs === void 0 || !Number.isFinite(timeoutMs) ? {} : { timeoutMs },
2385
+ ...text3 === void 0 || text3.trim() === "" ? {} : { text: text3 }
2386
+ }));
2387
+ await rememberTab(sessionId, result.tabId);
2388
+ return [
2389
+ `matched: ${result.matched ? "yes" : "no"}`,
2390
+ `url: ${result.url}`,
2391
+ `title: ${result.title}`,
2392
+ result.tabId !== void 0 ? `tabId: ${result.tabId}` : null
2393
+ ].filter((line) => line !== null).join("\n");
2394
+ }
2395
+ )));
2396
+ disposers.push(ctx.tools.register(textTool(
2397
+ "browser_list_tabs",
2398
+ "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.",
2399
+ {},
2400
+ async (_args, exec) => {
2401
+ guardEnabled();
2402
+ const sessionId = sessionIdOf(exec);
2403
+ await ensureConnected();
2404
+ const body = await runBridge(() => driverOf(options).listTabs());
2405
+ const sessionBound = options.sessions.tabOf(sessionId);
2406
+ const lines = [
2407
+ `sessionBoundTabId: ${sessionBound ?? "none"}`,
2408
+ `extensionBoundTabId: ${body.boundTabId ?? "none"}`,
2409
+ "tabs:",
2410
+ ...body.tabs.slice(0, 40).map((tab) => `- [${tab.tabId}]${tab.bound ? " (bound)" : ""}${tab.active ? " (active)" : ""} ${JSON.stringify(tab.title)} ${tab.url}`)
2411
+ ];
2412
+ return lines.join("\n");
2413
+ }
2414
+ )));
2415
+ disposers.push(ctx.tools.register(textTool(
2416
+ "browser_follow_tab",
2417
+ "Bind later browser_* tools for this session to a tabId from browser_list_tabs. Does not activate the tab unless activate=true. Requires approval when activating or leaving the previous bound tab.",
2418
+ {
2419
+ tabId: {
2420
+ type: "number",
2421
+ required: true,
2422
+ description: "Tab id from browser_list_tabs."
2423
+ },
2424
+ activate: {
2425
+ type: "boolean",
2426
+ description: "When true, bring the tab to the front."
2427
+ }
2428
+ },
2429
+ async (args, exec) => {
2430
+ guardEnabled();
2431
+ const sessionId = sessionIdOf(exec);
2432
+ const tabId = Number(args.tabId);
2433
+ const activate = args.activate === true;
2434
+ if (!Number.isFinite(tabId)) throw new Error("tabId must be a number");
2435
+ await ensureConnected();
2436
+ let url;
2437
+ try {
2438
+ const listed = await driverOf(options).listTabs();
2439
+ url = listed.tabs.find((tab) => tab.tabId === tabId)?.url;
2440
+ } catch {
2441
+ url = void 0;
2442
+ }
2443
+ await requireMutation(
2444
+ exec,
2445
+ "browser_follow_tab",
2446
+ `Follow tab ${tabId}${activate ? " (activate)" : ""}`,
2447
+ url
2448
+ );
2449
+ const result = await runBridge(() => driverOf(options).followTab(tabId, activate));
2450
+ await rememberTab(sessionId, result.tabId);
2451
+ options.sessions.clearConflict(sessionId);
2452
+ options.sessions.record({
2453
+ sessionId,
2454
+ tool: "browser_follow_tab",
2455
+ summary: `Follow tab ${tabId}`,
2456
+ url: result.url,
2457
+ outcome: "ok"
2458
+ });
2459
+ options.onMutation?.({ sessionId, tool: "browser_follow_tab", url: result.url });
2460
+ return `following tab ${result.tabId}
2461
+ url: ${result.url}
2462
+ title: ${result.title}`;
2463
+ }
2464
+ )));
2465
+ return () => {
2466
+ for (const dispose of disposers.splice(0).reverse()) {
2467
+ try {
2468
+ dispose();
2469
+ } catch {
2470
+ }
2471
+ }
2472
+ };
2473
+ }
2474
+
2475
+ // src/host/browser-agent/install.ts
2476
+ function installBrowserAgent(ctx, options) {
2477
+ const approval = new BrowserApprovalGate();
2478
+ const human = new BrowserHumanGate();
2479
+ const sessions = new BrowserSessionState();
2480
+ let unregisterTools = null;
2481
+ let unregisterPrompt = null;
2482
+ let active = false;
2483
+ let mountedPreference = null;
2484
+ let activeDriver = null;
2485
+ let playwrightDriver = null;
2486
+ let switchGate = Promise.resolve();
2487
+ let switchEpoch = 0;
2488
+ let switchPending = false;
2489
+ const currentProfileDir = () => browserAgentProfileDirFor(
2490
+ options.profileRoot,
2491
+ options.browserPreference()
2492
+ );
2493
+ const stopAllProfileSlots = () => {
2494
+ for (const slot of ["auto", "chrome", "edge"]) {
2495
+ stopAgentBrowserProcesses(browserAgentProfileDirFor(options.profileRoot, slot));
2496
+ }
2497
+ };
2498
+ const enqueueSwitch = (work) => {
2499
+ switchPending = true;
2500
+ const epoch = ++switchEpoch;
2501
+ switchGate = switchGate.then(work).catch((error) => {
2502
+ const detail = error instanceof Error ? error.message : String(error);
2503
+ ctx.logger.warn(`agent-enhancer: browser driver remount failed: ${detail}`);
2504
+ }).finally(() => {
2505
+ if (epoch === switchEpoch) switchPending = false;
2506
+ });
2507
+ };
2508
+ const tearDownDriverAsync = async () => {
2509
+ const previousPreference = mountedPreference;
2510
+ activeDriver = null;
2511
+ mountedPreference = null;
2512
+ const pw = playwrightDriver;
2513
+ playwrightDriver = null;
2514
+ if (pw !== null) {
2515
+ await pw.dispose().catch(() => void 0);
2516
+ }
2517
+ if (previousPreference !== null) {
2518
+ stopAgentBrowserProcesses(browserAgentProfileDirFor(options.profileRoot, previousPreference));
2519
+ }
2520
+ };
2521
+ const tearDownActiveAsync = async () => {
2522
+ unregisterTools?.();
2523
+ unregisterTools = null;
2524
+ unregisterPrompt?.();
2525
+ unregisterPrompt = null;
2526
+ await tearDownDriverAsync();
2527
+ };
2528
+ const requireDriver = () => {
2529
+ if (activeDriver === null) {
2530
+ throw new Error("Browser agent driver is not mounted");
2531
+ }
2532
+ return activeDriver;
2533
+ };
2534
+ const preferenceMatchesRunning = (preference) => {
2535
+ if (activeDriver === null || mountedPreference !== preference) return false;
2536
+ const status = activeDriver.status();
2537
+ if (!status.ready) return true;
2538
+ const want = playwrightChannelOrder(preference, process.platform)[0];
2539
+ return status.endpoint === `playwright:${want}`;
2540
+ };
2541
+ const createDriver = (_preference) => {
2542
+ mountedPreference = options.browserPreference();
2543
+ playwrightDriver = new PlaywrightDriver({
2544
+ profileDir: () => browserAgentProfileDirFor(options.profileRoot, options.browserPreference()),
2545
+ preference: () => options.browserPreference(),
2546
+ profileRoot: options.profileRoot,
2547
+ headless: false
2548
+ });
2549
+ activeDriver = playwrightDriver;
2550
+ };
2551
+ const ensureToolsRegistered = () => {
2552
+ if (unregisterPrompt === null) {
2553
+ unregisterPrompt = registerBrowserAgentPrompt(ctx);
2554
+ }
2555
+ if (unregisterTools === null) {
2556
+ unregisterTools = registerBrowserTools(ctx, {
2557
+ driver: requireDriver,
2558
+ alignPreference: async (startUrl) => {
2559
+ const result = await alignToPreference(startUrl);
2560
+ if (!result.ok) {
2561
+ throw new Error(result.error ?? "Browser agent failed to align preference");
2562
+ }
2563
+ },
2564
+ approval,
2565
+ human,
2566
+ sessions,
2567
+ enabled: () => active && options.enabled(),
2568
+ onMutation: options.onBrowserMutation
2569
+ });
2570
+ }
2571
+ };
2572
+ const alignToPreference = async (startUrl, preferenceOverride) => {
2573
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
2574
+ await switchGate.catch(() => void 0);
2575
+ const preference = preferenceOverride ?? options.browserPreference();
2576
+ try {
2577
+ if (preferenceMatchesRunning(preference)) {
2578
+ await requireDriver().ensureReady(startUrl);
2579
+ active = true;
2580
+ return { ok: true };
2581
+ }
2582
+ active = false;
2583
+ await tearDownDriverAsync();
2584
+ stopAllProfileSlots();
2585
+ if (!options.enabled()) {
2586
+ return { ok: false, error: "Browser agent disabled" };
2587
+ }
2588
+ mountedPreference = preference;
2589
+ playwrightDriver = new PlaywrightDriver({
2590
+ profileDir: browserAgentProfileDirFor(options.profileRoot, preference),
2591
+ preference,
2592
+ profileRoot: options.profileRoot,
2593
+ headless: false
2594
+ });
2595
+ activeDriver = playwrightDriver;
2596
+ ensureToolsRegistered();
2597
+ active = true;
2598
+ await activeDriver.ensureReady(startUrl);
2599
+ mountedPreference = preference;
2600
+ return { ok: true };
2601
+ } catch (error) {
2602
+ activeDriver = null;
2603
+ playwrightDriver = null;
2604
+ mountedPreference = null;
2605
+ active = false;
2606
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2607
+ }
2608
+ };
2609
+ const mount = () => {
2610
+ const preference = options.browserPreference();
2611
+ createDriver(preference);
2612
+ ensureToolsRegistered();
2613
+ };
2614
+ const refresh = () => {
2615
+ const want = options.enabled();
2616
+ if (!want) {
2617
+ if (!active && playwrightDriver === null && !switchPending) return;
2618
+ active = false;
2619
+ approval.clearAll();
2620
+ human.clearAll();
2621
+ enqueueSwitch(() => tearDownActiveAsync());
2622
+ return;
2623
+ }
2624
+ if (active || playwrightDriver !== null || switchPending) return;
2625
+ active = true;
2626
+ mount();
2627
+ };
2628
+ refresh();
113
2629
  return {
114
- instant: {
115
- provider: settings.autoInstantProvider,
116
- model: settings.autoInstantModel,
117
- reasoningEffort: settings.autoInstantReasoningEffort
2630
+ approval,
2631
+ human,
2632
+ sessions,
2633
+ driverStatus() {
2634
+ return activeDriver?.status() ?? null;
118
2635
  },
119
- thinking: {
120
- provider: settings.autoThinkingProvider,
121
- model: settings.autoThinkingModel,
122
- reasoningEffort: settings.autoThinkingReasoningEffort
2636
+ activeProfileDir() {
2637
+ if (mountedPreference !== null) {
2638
+ return browserAgentProfileDirFor(options.profileRoot, mountedPreference);
2639
+ }
2640
+ return currentProfileDir();
123
2641
  },
124
- pro: {
125
- provider: settings.autoProProvider,
126
- model: settings.autoProModel,
127
- reasoningEffort: settings.autoProReasoningEffort
2642
+ async launchDedicated(startUrl, preferenceOverride) {
2643
+ return alignToPreference(startUrl, preferenceOverride);
128
2644
  },
129
- classifier: {
130
- provider: settings.autoClassifierProvider,
131
- model: settings.autoClassifierModel,
132
- reasoningEffort: settings.autoClassifierReasoningEffort
2645
+ alignToPreference(startUrl) {
2646
+ return alignToPreference(startUrl);
2647
+ },
2648
+ refresh,
2649
+ async resolveTabConflict(decision) {
2650
+ const conflict = sessions.currentConflict();
2651
+ if (conflict === null || activeDriver === null) return { ok: false };
2652
+ try {
2653
+ const followed = await activeDriver.followTab(
2654
+ decision === "follow" ? conflict.activeTabId : conflict.boundTabId,
2655
+ true
2656
+ );
2657
+ sessions.bind(conflict.sessionId, followed.tabId);
2658
+ sessions.clearConflict(conflict.sessionId);
2659
+ if (options.softPauseEnabled()) options.softPause.release(conflict.sessionId);
2660
+ return {
2661
+ ok: true,
2662
+ tabId: followed.tabId,
2663
+ url: followed.url,
2664
+ title: followed.title
2665
+ };
2666
+ } catch {
2667
+ return { ok: false };
2668
+ }
2669
+ },
2670
+ async openUrl(input) {
2671
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
2672
+ await switchGate.catch(() => void 0);
2673
+ try {
2674
+ const ready = activeDriver?.status().ready === true;
2675
+ const decision = await approval.requestApproval({
2676
+ sessionId: input.sessionId,
2677
+ tool: "browser_open_url",
2678
+ summary: `Open ${input.url}`,
2679
+ url: input.url,
2680
+ signal: new AbortController().signal,
2681
+ forcePrompt: !ready
2682
+ });
2683
+ if (decision === "deny") return { ok: false, error: "User denied" };
2684
+ const aligned = await alignToPreference(input.url);
2685
+ if (!aligned.ok) return { ok: false, error: aligned.error };
2686
+ const driver = requireDriver();
2687
+ await driver.ensureReady(input.url);
2688
+ const existing = sessions.tabOf(input.sessionId);
2689
+ if (existing !== void 0) {
2690
+ await driver.bind(existing, input.sessionId).catch(() => void 0);
2691
+ }
2692
+ const result = await driver.navigate(input.url);
2693
+ sessions.rememberHttpUrl(input.sessionId, result.url);
2694
+ const tabId = result.tabId;
2695
+ if (typeof tabId === "number") sessions.bind(input.sessionId, tabId);
2696
+ sessions.record({
2697
+ sessionId: input.sessionId,
2698
+ tool: "browser_open_url",
2699
+ summary: `Open ${input.url}`,
2700
+ url: result.url,
2701
+ outcome: "ok"
2702
+ });
2703
+ options.onBrowserMutation?.({
2704
+ sessionId: input.sessionId,
2705
+ tool: "browser_open_url",
2706
+ url: result.url
2707
+ });
2708
+ return { ok: true, url: result.url, title: result.title };
2709
+ } catch (error) {
2710
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2711
+ }
2712
+ },
2713
+ async quotePage(sessionId) {
2714
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
2715
+ await switchGate.catch(() => void 0);
2716
+ try {
2717
+ const aligned = await alignToPreference();
2718
+ if (!aligned.ok) return { ok: false, error: aligned.error };
2719
+ const driver = requireDriver();
2720
+ await driver.ensureReady();
2721
+ const existing = sessions.tabOf(sessionId);
2722
+ if (existing !== void 0) {
2723
+ await driver.bind(existing, sessionId).catch(() => void 0);
2724
+ }
2725
+ const snap = await driver.snapshot();
2726
+ sessions.rememberHttpUrl(sessionId, snap.url);
2727
+ if (typeof snap.tabId === "number") sessions.bind(sessionId, snap.tabId);
2728
+ if (snap.needsHuman === true) {
2729
+ sessions.setNeedsHuman(sessionId, "Login or captcha on page");
2730
+ } else {
2731
+ sessions.clearNeedsHuman(sessionId);
2732
+ }
2733
+ const text3 = [
2734
+ snap.title.trim() === "" ? null : snap.title.trim(),
2735
+ snap.url,
2736
+ snap.textPreview.slice(0, 1200)
2737
+ ].filter((line) => line !== null && line !== "").join("\n");
2738
+ return {
2739
+ ok: true,
2740
+ text: text3,
2741
+ url: snap.url,
2742
+ title: snap.title
2743
+ };
2744
+ } catch (error) {
2745
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2746
+ }
2747
+ },
2748
+ acknowledgeHuman(sessionId) {
2749
+ const sid = typeof sessionId === "string" && sessionId.trim() !== "" ? sessionId.trim() : human.current()?.sessionId ?? sessions.anyNeedsHuman()?.sessionId;
2750
+ if (sid === void 0) return false;
2751
+ const hadBanner = sessions.needsHuman(sid) !== void 0;
2752
+ const resumed = human.acknowledge(sid);
2753
+ sessions.clearNeedsHuman(sid);
2754
+ return resumed || hadBanner;
2755
+ },
2756
+ async dispose() {
2757
+ active = false;
2758
+ approval.clearAll();
2759
+ human.clearAll();
2760
+ await switchGate.catch(() => void 0);
2761
+ await tearDownActiveAsync();
133
2762
  }
134
2763
  };
135
2764
  }
136
- function auxiliaryModelOf(settings, feature) {
137
- switch (feature) {
138
- case "optimize":
139
- return {
140
- provider: settings.optimizeProvider,
141
- model: settings.optimizeModel,
142
- reasoningEffort: settings.optimizeReasoningEffort
143
- };
144
- case "predict":
145
- return {
146
- provider: settings.predictProvider,
147
- model: settings.predictModel,
148
- reasoningEffort: settings.predictReasoningEffort
149
- };
150
- case "compact":
151
- return {
152
- provider: settings.compactProvider,
153
- model: settings.compactModel,
154
- reasoningEffort: settings.compactReasoningEffort
155
- };
156
- default: {
157
- const _exhaustive = feature;
158
- return _exhaustive;
159
- }
160
- }
161
- }
162
- function isFollowSessionModel(selection) {
163
- return selection.provider === "" || selection.model === "";
164
- }
165
2765
 
166
2766
  // src/errors.ts
167
2767
  var MESSAGES = {
@@ -195,7 +2795,7 @@ var AuxiliaryError = class extends Error {
195
2795
  // src/identity.ts
196
2796
  var PACKAGE_NAME = "dsh-agent-enhancer";
197
2797
  var PLUGIN_ID = "agent-enhancer";
198
- var PACKAGE_VERSION = "0.3.8";
2798
+ var PACKAGE_VERSION = "0.3.9";
199
2799
  var LEGACY_PACKAGE_NAME = "dsh-composer-enhancer";
200
2800
  var ROLLBACK_PREFIX = `${PACKAGE_NAME}:rollback:`;
201
2801
  var UNDO_PREFIX = `${PACKAGE_NAME}:undo:`;
@@ -341,7 +2941,7 @@ var DshCheckpointSessions = class {
341
2941
  };
342
2942
 
343
2943
  // src/host/checkpoint/live.ts
344
- import { isAbsolute as isAbsolute2, join as join3, relative, sep as sep2 } from "node:path";
2944
+ import { isAbsolute as isAbsolute2, join as join4, relative, sep as sep2 } from "node:path";
345
2945
 
346
2946
  // src/host/checkpoint/activity.ts
347
2947
  function surfaceMessageId(event) {
@@ -600,7 +3200,7 @@ function synthesizeCheckpoint(options) {
600
3200
  // src/host/checkpoint/files.ts
601
3201
  import { createHash, randomUUID as randomUUID2 } from "node:crypto";
602
3202
  import { chmod, lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
603
- import { basename, isAbsolute, join, resolve, sep, win32 } from "node:path";
3203
+ import { basename, isAbsolute, join as join2, resolve, sep, win32 } from "node:path";
604
3204
  import { TextDecoder } from "node:util";
605
3205
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
606
3206
  var ABSENT_FILE_HASH = "";
@@ -661,7 +3261,7 @@ function segments(path) {
661
3261
  function canonicalSegment(segment) {
662
3262
  return segment.replace(/[. ]+$/g, "").toLowerCase();
663
3263
  }
664
- function pathKey(path) {
3264
+ function pathKey2(path) {
665
3265
  return process.platform === "win32" ? segments(path).map(canonicalSegment).join("/") : path;
666
3266
  }
667
3267
  function unsafePath(path) {
@@ -682,8 +3282,8 @@ async function removeIfPresent(path) {
682
3282
  }
683
3283
  }
684
3284
  async function writeAtomic(path, text3) {
685
- await mkdir(join(path, ".."), { recursive: true });
686
- const temporary = join(join(path, ".."), `.${basename(path)}.${randomUUID2()}.tmp`);
3285
+ await mkdir(join2(path, ".."), { recursive: true });
3286
+ const temporary = join2(join2(path, ".."), `.${basename(path)}.${randomUUID2()}.tmp`);
687
3287
  try {
688
3288
  await writeFile(temporary, text3, { encoding: "utf8", flag: "wx" });
689
3289
  await rename(temporary, path);
@@ -692,8 +3292,8 @@ async function writeAtomic(path, text3) {
692
3292
  }
693
3293
  }
694
3294
  async function writeJournalAtomic(path, value) {
695
- await mkdir(join(path, ".."), { recursive: true, mode: 448 });
696
- const temporary = join(join(path, ".."), `.${basename(path)}.${randomUUID2()}.tmp`);
3295
+ await mkdir(join2(path, ".."), { recursive: true, mode: 448 });
3296
+ const temporary = join2(join2(path, ".."), `.${basename(path)}.${randomUUID2()}.tmp`);
697
3297
  try {
698
3298
  await writeFile(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
699
3299
  await rename(temporary, path);
@@ -707,7 +3307,7 @@ async function readSnapshot(workspaceRoot, path) {
707
3307
  let current = resolve(workspaceRoot);
708
3308
  const target = absolutePath(workspaceRoot, path);
709
3309
  for (const segment of segments(path)) {
710
- current = join(current, segment);
3310
+ current = join2(current, segment);
711
3311
  let stats;
712
3312
  try {
713
3313
  stats = await lstat(current);
@@ -808,7 +3408,7 @@ var DurableRestoreJournal = class {
808
3408
  };
809
3409
  }
810
3410
  sidecarPath() {
811
- return join(this.options.storageRoot, "file-journals", `${digest(this.id)}.json`);
3411
+ return join2(this.options.storageRoot, "file-journals", `${digest(this.id)}.json`);
812
3412
  }
813
3413
  async writeSidecar() {
814
3414
  const value = {
@@ -931,7 +3531,7 @@ var CheckpointFiles = class {
931
3531
  }
932
3532
  }
933
3533
  async loadJournal(metadata) {
934
- const path = join(this.options.storageRoot, "file-journals", `${digest(metadata.id)}.json`);
3534
+ const path = join2(this.options.storageRoot, "file-journals", `${digest(metadata.id)}.json`);
935
3535
  const stored = JSON.parse(await readFile(path, "utf8"));
936
3536
  if (!isRecord(stored) || stored.schemaVersion !== CHECKPOINT_SCHEMA_VERSION || stored.id !== metadata.id || !Array.isArray(stored.snapshots) || !Array.isArray(stored.completed)) {
937
3537
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
@@ -939,7 +3539,7 @@ var CheckpointFiles = class {
939
3539
  const snapshots = [];
940
3540
  const seen = /* @__PURE__ */ new Set();
941
3541
  for (const value of stored.snapshots) {
942
- if (!isRecord(value) || typeof value.path !== "string" || typeof value.exists !== "boolean" || typeof value.afterHash !== "string" || typeof value.beforeHash !== "string" || unsafePath(value.path) || seen.has(pathKey(value.path)) || (value.exists ? typeof value.text !== "string" : value.text !== null)) {
3542
+ if (!isRecord(value) || typeof value.path !== "string" || typeof value.exists !== "boolean" || typeof value.afterHash !== "string" || typeof value.beforeHash !== "string" || unsafePath(value.path) || seen.has(pathKey2(value.path)) || (value.exists ? typeof value.text !== "string" : value.text !== null)) {
943
3543
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
944
3544
  }
945
3545
  if (value.text !== null && (Buffer.byteLength(value.text, "utf8") > MAX_FILE_BYTES || value.text.includes("\0"))) throw new CheckpointFileError("FILE_RESTORE_FAILED");
@@ -954,7 +3554,7 @@ var CheckpointFiles = class {
954
3554
  if (currentHash !== snapshot.afterHash && currentHash !== snapshot.beforeHash) {
955
3555
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
956
3556
  }
957
- seen.add(pathKey(value.path));
3557
+ seen.add(pathKey2(value.path));
958
3558
  snapshots.push(snapshot);
959
3559
  }
960
3560
  const completed = [];
@@ -980,10 +3580,10 @@ var CheckpointFiles = class {
980
3580
  for (const file of files) {
981
3581
  const target = absolutePath(this.options.workspaceRoot, file.path);
982
3582
  let conflict = null;
983
- if (unsafePath(file.path) || seen.has(pathKey(file.path)) || target !== root && !target.startsWith(`${root}${sep}`)) {
3583
+ if (unsafePath(file.path) || seen.has(pathKey2(file.path)) || target !== root && !target.startsWith(`${root}${sep}`)) {
984
3584
  conflict = { path: file.path, reason: "unsafe-path" };
985
3585
  }
986
- seen.add(pathKey(file.path));
3586
+ seen.add(pathKey2(file.path));
987
3587
  if (conflict === null) conflict = this.validateBeforeImage(file) ?? this.validateAfterImage(file);
988
3588
  let snapshot = null;
989
3589
  if (conflict === null) {
@@ -1025,7 +3625,7 @@ var CheckpointFiles = class {
1025
3625
 
1026
3626
  // src/host/checkpoint/workspace-snapshot.ts
1027
3627
  import { readdir } from "node:fs/promises";
1028
- import { join as join2 } from "node:path";
3628
+ import { join as join3 } from "node:path";
1029
3629
  var MAX_WORKSPACE_SCAN_FILES = 2e3;
1030
3630
  var MAX_SHELL_CHANGED_FILES = 200;
1031
3631
  async function scanWorkspace(workspaceRoot, options = {}) {
@@ -1045,7 +3645,7 @@ async function scanWorkspace(workspaceRoot, options = {}) {
1045
3645
  if (truncated) return;
1046
3646
  if (isExcludedSegment(entry.name)) continue;
1047
3647
  const relativePath = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
1048
- const absolutePath2 = join2(absoluteDir, entry.name);
3648
+ const absolutePath2 = join3(absoluteDir, entry.name);
1049
3649
  if (entry.isSymbolicLink()) continue;
1050
3650
  if (entry.isDirectory()) {
1051
3651
  await visit(absolutePath2, relativePath.split("\\").join("/"));
@@ -1325,7 +3925,7 @@ var DshCheckpointCapture = class {
1325
3925
  return;
1326
3926
  }
1327
3927
  try {
1328
- const absolutePath2 = isAbsolute2(path) ? path : join3(workspaceRoot, path);
3928
+ const absolutePath2 = isAbsolute2(path) ? path : join4(workspaceRoot, path);
1329
3929
  await this.captureAbsolutePath(agent, absolutePath2);
1330
3930
  } catch {
1331
3931
  const turn = this.turnOf(agent);
@@ -1530,7 +4130,7 @@ function chainTrackedFiles(checkpoints, fromTurnOrRange, untilTurnExclusive) {
1530
4130
  // src/host/checkpoint/cut-store.ts
1531
4131
  import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
1532
4132
  import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
1533
- import { basename as basename2, join as join4 } from "node:path";
4133
+ import { basename as basename2, join as join5 } from "node:path";
1534
4134
  import { z } from "zod";
1535
4135
  var SCHEMA_VERSION = 1;
1536
4136
  var queues = /* @__PURE__ */ new Map();
@@ -1574,7 +4174,7 @@ async function removeIfPresent2(path) {
1574
4174
  }
1575
4175
  }
1576
4176
  async function writeAtomic2(path, value) {
1577
- const temporary = join4(join4(path, ".."), `.${basename2(path)}.${randomUUID3()}.tmp`);
4177
+ const temporary = join5(join5(path, ".."), `.${basename2(path)}.${randomUUID3()}.tmp`);
1578
4178
  try {
1579
4179
  await writeFile2(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
1580
4180
  await rename2(temporary, path);
@@ -1589,8 +4189,8 @@ function isWithdrawnByCut(cut, seq) {
1589
4189
  var SessionCutStore = class {
1590
4190
  constructor(root) {
1591
4191
  this.root = root;
1592
- this.directory = join4(root, "sessions");
1593
- this.rootKey = join4(root, ".");
4192
+ this.directory = join5(root, "sessions");
4193
+ this.rootKey = join5(root, ".");
1594
4194
  }
1595
4195
  root;
1596
4196
  directory;
@@ -1626,7 +4226,7 @@ var SessionCutStore = class {
1626
4226
  });
1627
4227
  }
1628
4228
  pathOf(sessionId) {
1629
- return join4(this.directory, `${digest2(sessionId)}.json`);
4229
+ return join5(this.directory, `${digest2(sessionId)}.json`);
1630
4230
  }
1631
4231
  };
1632
4232
 
@@ -2497,7 +5097,7 @@ var CheckpointRollbackService = class {
2497
5097
  // src/host/checkpoint/store.ts
2498
5098
  import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";
2499
5099
  import { chmod as chmod3, mkdir as mkdir3, readdir as readdir2, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
2500
- import { basename as basename3, join as join5 } from "node:path";
5100
+ import { basename as basename3, join as join6 } from "node:path";
2501
5101
  import { z as z2 } from "zod";
2502
5102
  var MAX_CHECKPOINTS = 20;
2503
5103
  var checkpointQueues = /* @__PURE__ */ new Map();
@@ -2617,7 +5217,7 @@ async function removeIfPresent3(path) {
2617
5217
  }
2618
5218
  }
2619
5219
  async function writeAtomic3(path, value) {
2620
- const temporary = join5(join5(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
5220
+ const temporary = join6(join6(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
2621
5221
  try {
2622
5222
  await writeFile3(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
2623
5223
  await rename3(temporary, path);
@@ -2629,9 +5229,9 @@ async function writeAtomic3(path, value) {
2629
5229
  var CheckpointStore = class {
2630
5230
  constructor(root) {
2631
5231
  this.root = root;
2632
- this.checkpointDirectory = join5(root, "checkpoints");
2633
- this.journalDirectory = join5(root, "journals");
2634
- this.rootKey = join5(root, ".");
5232
+ this.checkpointDirectory = join6(root, "checkpoints");
5233
+ this.journalDirectory = join6(root, "journals");
5234
+ this.rootKey = join6(root, ".");
2635
5235
  }
2636
5236
  root;
2637
5237
  checkpointDirectory;
@@ -2707,7 +5307,7 @@ var CheckpointStore = class {
2707
5307
  let removed = 0;
2708
5308
  for (const name2 of names) {
2709
5309
  if (!name2.endsWith(".json")) continue;
2710
- const path = join5(this.journalDirectory, name2);
5310
+ const path = join6(this.journalDirectory, name2);
2711
5311
  const stored = await this.readJson(path);
2712
5312
  assertCheckpointSchema(stored);
2713
5313
  const parsed = journalSchema.safeParse(stored);
@@ -2732,13 +5332,13 @@ var CheckpointStore = class {
2732
5332
  if (!parsed.success) throw new CheckpointStoreError("INVALID_JOURNAL");
2733
5333
  await serialize3(journalQueues, this.rootKey, async () => {
2734
5334
  await this.ensureDirectories();
2735
- await writeAtomic3(join5(this.journalDirectory, `${digest3(journal.id)}.json`), parsed.data);
5335
+ await writeAtomic3(join6(this.journalDirectory, `${digest3(journal.id)}.json`), parsed.data);
2736
5336
  });
2737
5337
  }
2738
5338
  async completeJournal(id) {
2739
5339
  await serialize3(journalQueues, this.rootKey, async () => {
2740
5340
  await this.ensureDirectories();
2741
- await removeIfPresent3(join5(this.journalDirectory, `${digest3(id)}.json`));
5341
+ await removeIfPresent3(join6(this.journalDirectory, `${digest3(id)}.json`));
2742
5342
  });
2743
5343
  }
2744
5344
  async listPendingJournals() {
@@ -2762,7 +5362,7 @@ var CheckpointStore = class {
2762
5362
  const journals = [];
2763
5363
  for (const name2 of names.sort()) {
2764
5364
  if (!name2.endsWith(".json")) continue;
2765
- const stored = await this.readJson(join5(this.journalDirectory, name2));
5365
+ const stored = await this.readJson(join6(this.journalDirectory, name2));
2766
5366
  assertCheckpointSchema(stored);
2767
5367
  const parsed = journalSchema.safeParse(stored);
2768
5368
  if (!parsed.success) throw new CheckpointStoreError("INVALID_STORE");
@@ -2774,7 +5374,7 @@ var CheckpointStore = class {
2774
5374
  return `${this.rootKey}\0${sessionId}`;
2775
5375
  }
2776
5376
  checkpointPath(sessionId) {
2777
- return join5(this.checkpointDirectory, `${digest3(sessionId)}.json`);
5377
+ return join6(this.checkpointDirectory, `${digest3(sessionId)}.json`);
2778
5378
  }
2779
5379
  async ensureDirectories() {
2780
5380
  await mkdir3(this.root, { recursive: true, mode: 448 });
@@ -2783,7 +5383,7 @@ var CheckpointStore = class {
2783
5383
  }
2784
5384
  async cleanTemporaryFiles(directory, prefix = "") {
2785
5385
  for (const name2 of await readdir2(directory)) {
2786
- if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink3(join5(directory, name2));
5386
+ if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink3(join6(directory, name2));
2787
5387
  }
2788
5388
  }
2789
5389
  async readJson(path) {
@@ -3339,9 +5939,9 @@ var SessionCleanupRegistry = class {
3339
5939
 
3340
5940
  // src/host/session-delete/plugin-purge.ts
3341
5941
  import { createHash as createHash4 } from "node:crypto";
3342
- import { existsSync } from "node:fs";
5942
+ import { existsSync as existsSync2 } from "node:fs";
3343
5943
  import { readdir as readdir3, readFile as readFile4, rm, unlink as unlink4 } from "node:fs/promises";
3344
- import { join as join6 } from "node:path";
5944
+ import { join as join7 } from "node:path";
3345
5945
  function digest4(value) {
3346
5946
  return createHash4("sha256").update(value).digest("hex");
3347
5947
  }
@@ -3349,7 +5949,7 @@ function shortDigest(value, length = 16) {
3349
5949
  return digest4(value).slice(0, length);
3350
5950
  }
3351
5951
  async function removeIfPresent4(path) {
3352
- if (!existsSync(path)) return false;
5952
+ if (!existsSync2(path)) return false;
3353
5953
  await rm(path, { recursive: true, force: true });
3354
5954
  return true;
3355
5955
  }
@@ -3374,15 +5974,15 @@ function createCheckpointCleaner(options) {
3374
5974
  signal.throwIfAborted();
3375
5975
  await options.cutStore.set(sessionId, null);
3376
5976
  const key = shortDigest(sessionId);
3377
- await removeIfPresent4(join6(options.storageRoot, "shadow", key));
3378
- await removeIfPresent4(join6(options.storageRoot, "shadow-git", key));
3379
- const journalDir = join6(options.storageRoot, "journals");
5977
+ await removeIfPresent4(join7(options.storageRoot, "shadow", key));
5978
+ await removeIfPresent4(join7(options.storageRoot, "shadow-git", key));
5979
+ const journalDir = join7(options.storageRoot, "journals");
3380
5980
  try {
3381
5981
  const names = await readdir3(journalDir);
3382
5982
  for (const name2 of names) {
3383
5983
  signal.throwIfAborted();
3384
5984
  if (!name2.endsWith(".json")) continue;
3385
- const path = join6(journalDir, name2);
5985
+ const path = join7(journalDir, name2);
3386
5986
  try {
3387
5987
  const raw = JSON.parse(await readFile4(path, "utf8"));
3388
5988
  if (raw.sessionId === sessionId) await unlinkIfPresent(path);
@@ -3403,9 +6003,9 @@ function createContextExcludeCleaner(pluginDataRoot) {
3403
6003
  label: "Context exclude rules",
3404
6004
  async purge(sessionId, signal) {
3405
6005
  signal.throwIfAborted();
3406
- const dir = join6(pluginDataRoot, "context-exclude", "sessions");
3407
- const hashed = join6(dir, `${digest4(sessionId)}.json`);
3408
- const raw = join6(dir, `${sessionId}.json`);
6006
+ const dir = join7(pluginDataRoot, "context-exclude", "sessions");
6007
+ const hashed = join7(dir, `${digest4(sessionId)}.json`);
6008
+ const raw = join7(dir, `${sessionId}.json`);
3409
6009
  await unlinkIfPresent(hashed);
3410
6010
  await unlinkIfPresent(raw);
3411
6011
  }
@@ -3414,10 +6014,10 @@ function createContextExcludeCleaner(pluginDataRoot) {
3414
6014
 
3415
6015
  // src/host/session-delete/delete.ts
3416
6016
  import { createHash as createHash5 } from "node:crypto";
3417
- import { existsSync as existsSync2 } from "node:fs";
6017
+ import { existsSync as existsSync3 } from "node:fs";
3418
6018
  import { appendFile, mkdir as mkdir4, readdir as readdir4, rm as rm2 } from "node:fs/promises";
3419
- import { homedir, tmpdir } from "node:os";
3420
- import { join as join7 } from "node:path";
6019
+ import { homedir as homedir2, tmpdir } from "node:os";
6020
+ import { join as join8 } from "node:path";
3421
6021
  var SESSION_ID_RE = /^session-[0-9a-fA-F-]{36}$/;
3422
6022
  var SPILL_ROOT_RE = /^dsh-spill-[A-Za-z0-9_-]{6}$/;
3423
6023
  var SessionDeleteError = class extends Error {
@@ -3429,13 +6029,13 @@ var SessionDeleteError = class extends Error {
3429
6029
  code;
3430
6030
  };
3431
6031
  function dshHome() {
3432
- return process.env.DSH_HOME ?? join7(homedir(), ".dsh");
6032
+ return process.env.DSH_HOME ?? join8(homedir2(), ".dsh");
3433
6033
  }
3434
6034
  function sessionsRoot() {
3435
- return join7(dshHome(), "sessions");
6035
+ return join8(dshHome(), "sessions");
3436
6036
  }
3437
6037
  function projcacheSessionsDir() {
3438
- return join7(dshHome(), "storages", "session_projcache", "sessions");
6038
+ return join8(dshHome(), "storages", "session_projcache", "sessions");
3439
6039
  }
3440
6040
  function spillBase() {
3441
6041
  return process.env.DSH_SESSION_DELETE_TMP ?? tmpdir();
@@ -3459,10 +6059,10 @@ async function noteFailure(ctx, message) {
3459
6059
  } catch {
3460
6060
  }
3461
6061
  try {
3462
- const dir = join7(dshHome(), "profiles", "desktop", "plugin-data", "dsh-agent-enhancer");
6062
+ const dir = join8(dshHome(), "profiles", "desktop", "plugin-data", "dsh-agent-enhancer");
3463
6063
  await mkdir4(dir, { recursive: true });
3464
6064
  await appendFile(
3465
- join7(dir, "session-delete-last-error.log"),
6065
+ join8(dir, "session-delete-last-error.log"),
3466
6066
  `${(/* @__PURE__ */ new Date()).toISOString()} ${message}
3467
6067
  `,
3468
6068
  "utf8"
@@ -3639,7 +6239,7 @@ async function forgetInRegistry(ctx, sessionId, options) {
3639
6239
  return removed;
3640
6240
  }
3641
6241
  async function removePathBestEffort(path) {
3642
- if (!existsSync2(path)) return false;
6242
+ if (!existsSync3(path)) return false;
3643
6243
  for (let attempt = 0; attempt < 3; attempt += 1) {
3644
6244
  try {
3645
6245
  await rm2(path, { recursive: true, force: true });
@@ -3654,10 +6254,10 @@ async function removePathBestEffort(path) {
3654
6254
  async function eraseSessionLog(sessionId) {
3655
6255
  const removed = [];
3656
6256
  const root = sessionsRoot();
3657
- if (!existsSync2(root)) return removed;
6257
+ if (!existsSync3(root)) return removed;
3658
6258
  for (const workspaceDir of await readdir4(root)) {
3659
- const target = join7(root, workspaceDir, sessionId);
3660
- if (!existsSync2(target)) continue;
6259
+ const target = join8(root, workspaceDir, sessionId);
6260
+ if (!existsSync3(target)) continue;
3661
6261
  const normalizedRoot = root.toLowerCase();
3662
6262
  if (!target.toLowerCase().startsWith(normalizedRoot)) continue;
3663
6263
  if (await removePathBestEffort(target)) removed.push(target);
@@ -3675,8 +6275,8 @@ async function eraseSpill(sessionId) {
3675
6275
  const name2 = spillSessionDirName(sessionId);
3676
6276
  for (const entry of entries) {
3677
6277
  if (!SPILL_ROOT_RE.test(entry)) continue;
3678
- const target = join7(spillBase(), entry, name2);
3679
- if (!existsSync2(target)) continue;
6278
+ const target = join8(spillBase(), entry, name2);
6279
+ if (!existsSync3(target)) continue;
3680
6280
  if (await removePathBestEffort(target)) removed.push(target);
3681
6281
  }
3682
6282
  return removed;
@@ -3701,10 +6301,10 @@ async function eraseProjcache(ctx, sessionId) {
3701
6301
  } catch {
3702
6302
  }
3703
6303
  for (const cacheFile of [
3704
- join7(projcacheSessionsDir(), `${sessionId}.json`),
3705
- join7(projcacheSessionsDir(), `${uuid}.json`)
6304
+ join8(projcacheSessionsDir(), `${sessionId}.json`),
6305
+ join8(projcacheSessionsDir(), `${uuid}.json`)
3706
6306
  ]) {
3707
- if (!existsSync2(cacheFile)) continue;
6307
+ if (!existsSync3(cacheFile)) continue;
3708
6308
  if (await removePathBestEffort(cacheFile)) removed.push(cacheFile);
3709
6309
  }
3710
6310
  return removed;
@@ -3776,7 +6376,7 @@ async function deleteSessionNow(options) {
3776
6376
 
3777
6377
  // src/host/extra-folders/io.ts
3778
6378
  import { promises as fsp } from "node:fs";
3779
- import { basename as basename4, join as join8, resolve as resolve3, sep as sep4 } from "node:path";
6379
+ import { basename as basename4, join as join9, resolve as resolve3, sep as sep4 } from "node:path";
3780
6380
 
3781
6381
  // src/host/extra-folders/paths.ts
3782
6382
  import { createHash as createHash6 } from "node:crypto";
@@ -4212,7 +6812,7 @@ async function listExtraFolderEntriesNow(options) {
4212
6812
  throw new ExtraFoldersError("FILE_DENIED", "Root is not the workspace or an attached folder");
4213
6813
  }
4214
6814
  const relativePath = relativeUnderRoot(rootPath, options.request.relativePath);
4215
- const absoluteDir = relativePath === "" ? rootPath : join8(rootPath, relativePath);
6815
+ const absoluteDir = relativePath === "" ? rootPath : join9(rootPath, relativePath);
4216
6816
  assertInsideAllowedRoots(primaryCwd, extraPaths, absoluteDir);
4217
6817
  await assertDirectory(absoluteDir);
4218
6818
  let names;
@@ -4227,14 +6827,14 @@ async function listExtraFolderEntriesNow(options) {
4227
6827
  const entries = [];
4228
6828
  for (const name2 of names) {
4229
6829
  if (name2 === "." || name2 === "..") continue;
4230
- const absolutePath2 = join8(absoluteDir, name2);
6830
+ const absolutePath2 = join9(absoluteDir, name2);
4231
6831
  try {
4232
6832
  assertInsideAllowedRoots(primaryCwd, extraPaths, absolutePath2);
4233
6833
  const stat = await fsp.lstat(absolutePath2);
4234
6834
  if (stat.isSymbolicLink()) continue;
4235
6835
  const kind = stat.isDirectory() ? "directory" : stat.isFile() ? "file" : null;
4236
6836
  if (kind === null) continue;
4237
- const path = relativePath === "" ? name2 : join8(relativePath, name2);
6837
+ const path = relativePath === "" ? name2 : join9(relativePath, name2);
4238
6838
  entries.push({ name: name2, path: path.replace(/\\/g, "/"), absolutePath: absolutePath2, kind });
4239
6839
  } catch {
4240
6840
  }
@@ -4254,8 +6854,8 @@ function loadExtraRootPaths(store, primaryCwd) {
4254
6854
  }
4255
6855
 
4256
6856
  // src/host/extra-folders/store.ts
4257
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4258
- import { dirname, join as join9 } from "node:path";
6857
+ import { mkdirSync as mkdirSync2, readFileSync, renameSync, writeFileSync } from "node:fs";
6858
+ import { dirname, join as join10 } from "node:path";
4259
6859
  function emptyDoc(primaryCwd) {
4260
6860
  return {
4261
6861
  version: EXTRA_FOLDERS_VERSION,
@@ -4287,8 +6887,8 @@ function parseDoc(raw, primaryCwd) {
4287
6887
  }
4288
6888
  }
4289
6889
  function createExtraFoldersStore(rootDir) {
4290
- mkdirSync(rootDir, { recursive: true });
4291
- const fileOf = (primaryCwd) => join9(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
6890
+ mkdirSync2(rootDir, { recursive: true });
6891
+ const fileOf = (primaryCwd) => join10(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
4292
6892
  return {
4293
6893
  rootDir,
4294
6894
  load(primaryCwd) {
@@ -4308,7 +6908,7 @@ function createExtraFoldersStore(rootDir) {
4308
6908
  roots: [...roots]
4309
6909
  };
4310
6910
  const file = fileOf(primaryCwd);
4311
- mkdirSync(dirname(file), { recursive: true });
6911
+ mkdirSync2(dirname(file), { recursive: true });
4312
6912
  const tmp = `${file}.${process.pid}.tmp`;
4313
6913
  writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}
4314
6914
  `, "utf8");
@@ -4496,9 +7096,9 @@ async function writeWorkspaceFileNow(options) {
4496
7096
  }
4497
7097
 
4498
7098
  // src/host/file-edit/monaco.ts
4499
- import { existsSync as existsSync3 } from "node:fs";
7099
+ import { existsSync as existsSync4 } from "node:fs";
4500
7100
  import { promises as fsp2 } from "node:fs";
4501
- import { dirname as dirname2, extname, join as join10, resolve as resolve5, sep as sep5 } from "node:path";
7101
+ import { dirname as dirname2, extname, join as join11, resolve as resolve5, sep as sep5 } from "node:path";
4502
7102
  import { fileURLToPath } from "node:url";
4503
7103
 
4504
7104
  // src/shared/monaco-route.ts
@@ -4516,7 +7116,7 @@ function packageRootCandidates() {
4516
7116
  }
4517
7117
  function resolveMonacoVsDir() {
4518
7118
  for (const candidate of packageRootCandidates()) {
4519
- if (existsSync3(join10(candidate, "loader.js"))) return candidate;
7119
+ if (existsSync4(join11(candidate, "loader.js"))) return candidate;
4520
7120
  }
4521
7121
  return packageRootCandidates()[0];
4522
7122
  }
@@ -4572,7 +7172,7 @@ async function locateFile(vsDir, relativeUnderVs) {
4572
7172
  const parts = relativeUnderVs.split("/");
4573
7173
  let cursor = rootReal;
4574
7174
  for (const part of parts) {
4575
- cursor = join10(cursor, part);
7175
+ cursor = join11(cursor, part);
4576
7176
  if (!isInside(rootReal, cursor)) return null;
4577
7177
  }
4578
7178
  if (!isInside(rootReal, cursor)) return null;
@@ -4653,17 +7253,17 @@ function installMonacoRoute(ctx) {
4653
7253
  }
4654
7254
 
4655
7255
  // src/host/instructions-skills/io.ts
4656
- import { existsSync as existsSync13, readFileSync as readFileSync6, statSync as statSync4 } from "node:fs";
4657
- import { basename as basename13, join as join24, resolve as resolve15, sep as sep7 } from "node:path";
7256
+ import { existsSync as existsSync14, readFileSync as readFileSync6, statSync as statSync4 } from "node:fs";
7257
+ import { basename as basename13, join as join25, resolve as resolve15, sep as sep7 } from "node:path";
4658
7258
 
4659
7259
  // src/host/instructions-skills/create.ts
4660
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
4661
- import { dirname as dirname4, join as join12, resolve as resolve7 } from "node:path";
7260
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
7261
+ import { dirname as dirname4, join as join13, resolve as resolve7 } from "node:path";
4662
7262
 
4663
7263
  // src/host/instructions-skills/paths.ts
4664
- import { existsSync as existsSync4, statSync } from "node:fs";
4665
- import { basename as basename5, dirname as dirname3, join as join11, resolve as resolve6, sep as sep6 } from "node:path";
4666
- import { homedir as homedir2 } from "node:os";
7264
+ import { existsSync as existsSync5, statSync } from "node:fs";
7265
+ import { basename as basename5, dirname as dirname3, join as join12, resolve as resolve6, sep as sep6 } from "node:path";
7266
+ import { homedir as homedir3 } from "node:os";
4667
7267
  var INSTRUCTION_CANDIDATES = [
4668
7268
  "AGENTS.md",
4669
7269
  "CLAUDE.md",
@@ -4674,18 +7274,18 @@ var PROJECT_ROOT_MARKERS = [".git"];
4674
7274
  function dshHomeOf(env = process.env) {
4675
7275
  const fromEnv = env.DSH_HOME;
4676
7276
  if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve6(fromEnv.trim());
4677
- return resolve6(homedir2(), ".dsh");
7277
+ return resolve6(homedir3(), ".dsh");
4678
7278
  }
4679
7279
  function agentsHomeOf(env = process.env) {
4680
7280
  const fromEnv = env.DSH_AGENTS_HOME;
4681
7281
  if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve6(fromEnv.trim());
4682
- return resolve6(homedir2(), ".agents");
7282
+ return resolve6(homedir3(), ".agents");
4683
7283
  }
4684
7284
  function findProjectRoot(cwd, markers = PROJECT_ROOT_MARKERS) {
4685
7285
  let current = resolve6(cwd);
4686
7286
  for (; ; ) {
4687
7287
  for (const marker of markers) {
4688
- if (existsSync4(join11(current, marker))) return current;
7288
+ if (existsSync5(join12(current, marker))) return current;
4689
7289
  }
4690
7290
  const parent = dirname3(current);
4691
7291
  if (parent === current) return resolve6(cwd);
@@ -4711,22 +7311,22 @@ function skillRootsFor(cwd, projectRoot, env = process.env) {
4711
7311
  const root = resolve6(projectRoot);
4712
7312
  const tip = resolve6(cwd);
4713
7313
  return [
4714
- join11(root, ".agents", "skills"),
4715
- join11(root, ".dsh", "skills"),
4716
- join11(tip, ".agents", "skills"),
4717
- join11(tip, ".dsh", "skills"),
4718
- join11(agentsHomeOf(env), "skills"),
4719
- join11(dshHomeOf(env), "skills")
7314
+ join12(root, ".agents", "skills"),
7315
+ join12(root, ".dsh", "skills"),
7316
+ join12(tip, ".agents", "skills"),
7317
+ join12(tip, ".dsh", "skills"),
7318
+ join12(agentsHomeOf(env), "skills"),
7319
+ join12(dshHomeOf(env), "skills")
4720
7320
  ].filter((path, index, all) => all.findIndex((other) => samePath2(other, path)) === index);
4721
7321
  }
4722
7322
  function previewSkillSearchRoots(cwd, projectRoot, env = process.env) {
4723
- const home = resolve6(homedir2());
7323
+ const home = resolve6(homedir3());
4724
7324
  return [
4725
7325
  ...skillRootsFor(cwd, projectRoot, env),
4726
- join11(home, ".cursor", "skills"),
4727
- join11(home, ".cursor", "skills-cursor"),
4728
- join11(home, ".codex", "skills"),
4729
- join11(home, ".claude", "skills")
7326
+ join12(home, ".cursor", "skills"),
7327
+ join12(home, ".cursor", "skills-cursor"),
7328
+ join12(home, ".codex", "skills"),
7329
+ join12(home, ".claude", "skills")
4730
7330
  ].filter((path, index, all) => all.findIndex((other) => samePath2(other, path)) === index);
4731
7331
  }
4732
7332
  function fileBytes(path) {
@@ -4782,10 +7382,10 @@ Instructions for the agent go here.
4782
7382
  }
4783
7383
  function createWorkspaceAgentsFile(projectRoot) {
4784
7384
  const path = resolve7(projectRoot, "AGENTS.md");
4785
- if (existsSync5(path)) {
7385
+ if (existsSync6(path)) {
4786
7386
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
4787
7387
  }
4788
- mkdirSync2(dirname4(path), { recursive: true });
7388
+ mkdirSync3(dirname4(path), { recursive: true });
4789
7389
  writeFileSync2(path, AGENTS_STUB, "utf8");
4790
7390
  return { path, created: true };
4791
7391
  }
@@ -4794,19 +7394,19 @@ function createWorkspaceSkill(projectRoot, rawName) {
4794
7394
  if (!isKebabCaseName(name2)) {
4795
7395
  throw new AuxiliaryError("FILE_DENIED", "Skill name must be kebab-case");
4796
7396
  }
4797
- const dir = join12(resolve7(projectRoot), ".agents", "skills", name2);
4798
- const path = join12(dir, "SKILL.md");
4799
- if (existsSync5(path) || existsSync5(dir)) {
7397
+ const dir = join13(resolve7(projectRoot), ".agents", "skills", name2);
7398
+ const path = join13(dir, "SKILL.md");
7399
+ if (existsSync6(path) || existsSync6(dir)) {
4800
7400
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
4801
7401
  }
4802
- mkdirSync2(dir, { recursive: true });
7402
+ mkdirSync3(dir, { recursive: true });
4803
7403
  writeFileSync2(path, skillStubMarkdown(name2), "utf8");
4804
7404
  return { path, created: true, name: name2 };
4805
7405
  }
4806
7406
 
4807
7407
  // src/host/instructions-skills/discover.ts
4808
- import { existsSync as existsSync9, readdirSync as readdirSync3, readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
4809
- import { basename as basename9, dirname as dirname7, join as join17, resolve as resolve11 } from "node:path";
7408
+ import { existsSync as existsSync10, readdirSync as readdirSync3, readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
7409
+ import { basename as basename9, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
4810
7410
 
4811
7411
  // src/host/instructions-skills/types.ts
4812
7412
  function defaultSkillInstallMeta() {
@@ -4819,9 +7419,9 @@ function defaultSkillInstallMeta() {
4819
7419
  }
4820
7420
 
4821
7421
  // src/host/instructions-skills/transient-paths.ts
4822
- import { existsSync as existsSync6, lstatSync, readdirSync, renameSync as renameSync2, rmSync, unlinkSync } from "node:fs";
7422
+ import { existsSync as existsSync7, lstatSync, readdirSync, renameSync as renameSync2, rmSync, unlinkSync } from "node:fs";
4823
7423
  import { tmpdir as tmpdir2 } from "node:os";
4824
- import { basename as basename6, join as join13, resolve as resolve8 } from "node:path";
7424
+ import { basename as basename6, join as join14, resolve as resolve8 } from "node:path";
4825
7425
  var TRANSIENT_MARK = /\.__ae_(?:removing|installing)_/;
4826
7426
  function isTransientSkillEntryName(name2) {
4827
7427
  const base = basename6(name2.trim());
@@ -4830,7 +7430,7 @@ function isTransientSkillEntryName(name2) {
4830
7430
  }
4831
7431
  function skillTransientWorkPath(kind, skillName) {
4832
7432
  const safe = skillName.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 80) || "skill";
4833
- return join13(tmpdir2(), `ae-skill-${kind}-${safe}-${process.pid}-${Date.now()}`);
7433
+ return join14(tmpdir2(), `ae-skill-${kind}-${safe}-${process.pid}-${Date.now()}`);
4834
7434
  }
4835
7435
  function sweepTransientSkillEntries(skillsRoot) {
4836
7436
  const root = resolve8(skillsRoot);
@@ -4842,7 +7442,7 @@ function sweepTransientSkillEntries(skillsRoot) {
4842
7442
  }
4843
7443
  for (const name2 of names) {
4844
7444
  if (!isTransientSkillEntryName(name2)) continue;
4845
- const full = join13(root, name2);
7445
+ const full = join14(root, name2);
4846
7446
  try {
4847
7447
  rmSync(full, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 });
4848
7448
  } catch {
@@ -4874,7 +7474,7 @@ function removeQuietly(path) {
4874
7474
  } catch {
4875
7475
  return;
4876
7476
  }
4877
- if (!existsSync6(path)) return;
7477
+ if (!existsSync7(path)) return;
4878
7478
  try {
4879
7479
  rmSync(path, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 });
4880
7480
  } catch {
@@ -4883,17 +7483,17 @@ function removeQuietly(path) {
4883
7483
 
4884
7484
  // src/host/instructions-skills/uninstall.ts
4885
7485
  import { lstatSync as lstatSync3 } from "node:fs";
4886
- import { basename as basename8, dirname as dirname6, join as join16, resolve as resolve10 } from "node:path";
7486
+ import { basename as basename8, dirname as dirname6, join as join17, resolve as resolve10 } from "node:path";
4887
7487
 
4888
7488
  // src/host/instructions-skills/install-ledger.ts
4889
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
4890
- import { dirname as dirname5, join as join14 } from "node:path";
7489
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
7490
+ import { dirname as dirname5, join as join15 } from "node:path";
4891
7491
  function ledgerPath(dataRoot) {
4892
- return join14(dataRoot, "skills-install", "registry.json");
7492
+ return join15(dataRoot, "skills-install", "registry.json");
4893
7493
  }
4894
7494
  function writeLedger(dataRoot, ledger) {
4895
7495
  const path = ledgerPath(dataRoot);
4896
- mkdirSync3(dirname5(path), { recursive: true });
7496
+ mkdirSync4(dirname5(path), { recursive: true });
4897
7497
  const tmp = `${path}.${process.pid}.tmp`;
4898
7498
  writeFileSync3(tmp, `${JSON.stringify(ledger, null, 2)}
4899
7499
  `, "utf8");
@@ -4901,7 +7501,7 @@ function writeLedger(dataRoot, ledger) {
4901
7501
  }
4902
7502
  function readInstallLedger(dataRoot) {
4903
7503
  const path = ledgerPath(dataRoot);
4904
- if (!existsSync7(path)) return {};
7504
+ if (!existsSync8(path)) return {};
4905
7505
  try {
4906
7506
  const raw = readFileSync2(path, "utf8").trim();
4907
7507
  if (raw === "") return {};
@@ -4922,18 +7522,18 @@ function removeInstallRecord(dataRoot, name2) {
4922
7522
  }
4923
7523
 
4924
7524
  // src/host/instructions-skills/remove-path.ts
4925
- import { execFileSync } from "node:child_process";
7525
+ import { execFileSync as execFileSync2 } from "node:child_process";
4926
7526
  import {
4927
7527
  chmodSync,
4928
- existsSync as existsSync8,
7528
+ existsSync as existsSync9,
4929
7529
  lstatSync as lstatSync2,
4930
7530
  readdirSync as readdirSync2,
4931
7531
  readlinkSync,
4932
7532
  rmSync as rmSync2,
4933
7533
  unlinkSync as unlinkSync2
4934
7534
  } from "node:fs";
4935
- import { homedir as homedir3 } from "node:os";
4936
- import { basename as basename7, join as join15, resolve as resolve9 } from "node:path";
7535
+ import { homedir as homedir4 } from "node:os";
7536
+ import { basename as basename7, join as join16, resolve as resolve9 } from "node:path";
4937
7537
 
4938
7538
  // src/host/instructions-skills/fs-access.ts
4939
7539
  var ACCESS_DENIED_RE = /eperm|eacces|eio|ebusy|access is denied|operation not permitted|file in use|still present|拒绝访问|¾Ü¾ø·ÃÎÊ/i;
@@ -4964,8 +7564,8 @@ function pathPresent(path) {
4964
7564
  function isManagedSkillEntryPath(target, env = process.env) {
4965
7565
  const absolute = resolve9(target);
4966
7566
  const managedRoots = [
4967
- join15(agentsHomeOf(env), "skills"),
4968
- join15(dshHomeOf(env), "skills")
7567
+ join16(agentsHomeOf(env), "skills"),
7568
+ join16(dshHomeOf(env), "skills")
4969
7569
  ];
4970
7570
  for (const root of managedRoots) {
4971
7571
  if (samePath2(absolute, root) || isInsideOrSame(root, absolute)) return true;
@@ -4975,15 +7575,15 @@ function isManagedSkillEntryPath(target, env = process.env) {
4975
7575
  function isProtectedExternalSkillPath(target, env = process.env) {
4976
7576
  const absolute = resolve9(target);
4977
7577
  if (isManagedSkillEntryPath(absolute, env)) return false;
4978
- const home = resolve9(homedir3());
7578
+ const home = resolve9(homedir4());
4979
7579
  const protectedRoots = [
4980
- join15(home, ".skills-manager"),
4981
- join15(home, ".cursor", "skills"),
4982
- join15(home, ".cursor", "skills-cursor"),
4983
- join15(home, ".codex", "skills"),
4984
- join15(home, ".claude", "skills"),
4985
- join15(home, ".codebuddy", "skills"),
4986
- join15(home, ".workbuddy", "skills")
7580
+ join16(home, ".skills-manager"),
7581
+ join16(home, ".cursor", "skills"),
7582
+ join16(home, ".cursor", "skills-cursor"),
7583
+ join16(home, ".codex", "skills"),
7584
+ join16(home, ".claude", "skills"),
7585
+ join16(home, ".codebuddy", "skills"),
7586
+ join16(home, ".workbuddy", "skills")
4987
7587
  ];
4988
7588
  for (const root of protectedRoots) {
4989
7589
  if (samePath2(absolute, root) || isInsideOrSame(root, absolute)) return true;
@@ -5007,12 +7607,12 @@ function isReparseOrSymlink(path) {
5007
7607
  }
5008
7608
  }
5009
7609
  function effectivelyGone(target) {
5010
- if (!pathPresent(target) && !existsSync8(target)) return true;
7610
+ if (!pathPresent(target) && !existsSync9(target)) return true;
5011
7611
  try {
5012
7612
  const stat = lstatSync2(target);
5013
7613
  if (stat.isSymbolicLink()) return false;
5014
7614
  if (!stat.isDirectory()) return false;
5015
- if (existsSync8(join15(target, "SKILL.md"))) return false;
7615
+ if (existsSync9(join16(target, "SKILL.md"))) return false;
5016
7616
  let names;
5017
7617
  try {
5018
7618
  names = readdirSync2(target);
@@ -5030,7 +7630,7 @@ function unlinkMountOnly(absolute) {
5030
7630
  } catch {
5031
7631
  if (process.platform === "win32") {
5032
7632
  try {
5033
- execFileSync("cmd", ["/d", "/s", "/c", `rmdir "${absolute.replace(/"/g, "")}"`], {
7633
+ execFileSync2("cmd", ["/d", "/s", "/c", `rmdir "${absolute.replace(/"/g, "")}"`], {
5034
7634
  windowsHide: true,
5035
7635
  timeout: 15e3,
5036
7636
  stdio: "ignore"
@@ -5042,7 +7642,7 @@ function unlinkMountOnly(absolute) {
5042
7642
  return false;
5043
7643
  }
5044
7644
  }
5045
- return !pathPresent(absolute) && !existsSync8(absolute);
7645
+ return !pathPresent(absolute) && !existsSync9(absolute);
5046
7646
  }
5047
7647
  function tryUnlinkReparseOrFile(absolute) {
5048
7648
  let preferUnlink = false;
@@ -5062,7 +7662,7 @@ function removePathRobust(target) {
5062
7662
  if (isProtectedExternalSkillPath(absolute)) {
5063
7663
  return;
5064
7664
  }
5065
- if (!pathPresent(absolute) && !existsSync8(absolute)) return;
7665
+ if (!pathPresent(absolute) && !existsSync9(absolute)) return;
5066
7666
  if (isReparseOrSymlink(absolute)) {
5067
7667
  if (unlinkMountOnly(absolute)) return;
5068
7668
  if (effectivelyGone(absolute)) return;
@@ -5080,7 +7680,7 @@ function removePathRobust(target) {
5080
7680
  } catch (error) {
5081
7681
  if (!isWindowsPathBusyError(error) && effectivelyGone(absolute)) return;
5082
7682
  }
5083
- if (!pathPresent(absolute) && !existsSync8(absolute)) return;
7683
+ if (!pathPresent(absolute) && !existsSync9(absolute)) return;
5084
7684
  try {
5085
7685
  const aside = renameAsideToTemp(absolute, "removing");
5086
7686
  removeQuietly(aside);
@@ -5092,7 +7692,7 @@ function removePathRobust(target) {
5092
7692
  if (unlinkMountOnly(absolute)) return;
5093
7693
  } else {
5094
7694
  try {
5095
- execFileSync("cmd", ["/d", "/s", "/c", `rmdir /s /q "${absolute.replace(/"/g, "")}"`], {
7695
+ execFileSync2("cmd", ["/d", "/s", "/c", `rmdir /s /q "${absolute.replace(/"/g, "")}"`], {
5096
7696
  windowsHide: true,
5097
7697
  timeout: 3e4,
5098
7698
  stdio: "ignore"
@@ -5100,10 +7700,10 @@ function removePathRobust(target) {
5100
7700
  } catch {
5101
7701
  }
5102
7702
  }
5103
- if (!pathPresent(absolute) && !existsSync8(absolute)) return;
7703
+ if (!pathPresent(absolute) && !existsSync9(absolute)) return;
5104
7704
  if (effectivelyGone(absolute)) return;
5105
7705
  }
5106
- if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync8(absolute)) return;
7706
+ if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync9(absolute)) return;
5107
7707
  throw new AuxiliaryError("FILE_EDIT_FAILED", busyPathHint(basename7(absolute)));
5108
7708
  }
5109
7709
 
@@ -5126,8 +7726,8 @@ function pathPresent2(path) {
5126
7726
  function managedSkillEntriesForName(root, name2) {
5127
7727
  if (!isKebabCaseName(name2)) return [];
5128
7728
  const out = [];
5129
- const asDir = join16(root, name2);
5130
- const asFile = join16(root, `${name2}.md`);
7729
+ const asDir = join17(root, name2);
7730
+ const asFile = join17(root, `${name2}.md`);
5131
7731
  for (const entry of [asDir, asFile]) {
5132
7732
  if (!pathPresent2(entry)) continue;
5133
7733
  if (!samePath2(dirname6(entry), root)) continue;
@@ -5140,8 +7740,8 @@ function resolveManagedSkillRemovalTarget(path, name2, managedRoots) {
5140
7740
  if (!isKebabCaseName(name2)) return null;
5141
7741
  const entry = skillEntryPath(path);
5142
7742
  for (const root of managedRoots) {
5143
- const asDir = join16(root, name2);
5144
- const asFile = join16(root, `${name2}.md`);
7743
+ const asDir = join17(root, name2);
7744
+ const asFile = join17(root, `${name2}.md`);
5145
7745
  if (samePath2(entry, asDir) || samePath2(entry, asFile)) {
5146
7746
  if (!pathPresent2(entry)) return null;
5147
7747
  if (!samePath2(dirname6(entry), root)) return null;
@@ -5223,40 +7823,40 @@ function discoverInstructionFiles(options) {
5223
7823
  const projectRoot = findProjectRoot(cwd);
5224
7824
  const seen = /* @__PURE__ */ new Set();
5225
7825
  const instructions = [];
5226
- const globalPath = join17(dshHomeOf(env), "AGENTS.md");
7826
+ const globalPath = join18(dshHomeOf(env), "AGENTS.md");
5227
7827
  pushUnique(instructions, seen, {
5228
7828
  id: entryId("global", globalPath),
5229
7829
  scope: "global",
5230
7830
  name: "AGENTS.md",
5231
7831
  path: globalPath,
5232
- exists: existsSync9(globalPath),
7832
+ exists: existsSync10(globalPath),
5233
7833
  bytes: fileBytes(globalPath),
5234
7834
  createable: false
5235
7835
  });
5236
- const sharedPath = join17(agentsHomeOf(env), "AGENTS.md");
7836
+ const sharedPath = join18(agentsHomeOf(env), "AGENTS.md");
5237
7837
  pushUnique(instructions, seen, {
5238
7838
  id: entryId("shared", sharedPath),
5239
7839
  scope: "shared",
5240
7840
  name: "AGENTS.md",
5241
7841
  path: sharedPath,
5242
- exists: existsSync9(sharedPath),
7842
+ exists: existsSync10(sharedPath),
5243
7843
  bytes: fileBytes(sharedPath),
5244
7844
  createable: false
5245
7845
  });
5246
- const rootAgents = join17(projectRoot, "AGENTS.md");
7846
+ const rootAgents = join18(projectRoot, "AGENTS.md");
5247
7847
  pushUnique(instructions, seen, {
5248
7848
  id: entryId("project", rootAgents),
5249
7849
  scope: "project",
5250
7850
  name: "AGENTS.md",
5251
7851
  path: rootAgents,
5252
- exists: existsSync9(rootAgents),
7852
+ exists: existsSync10(rootAgents),
5253
7853
  bytes: fileBytes(rootAgents),
5254
- createable: !existsSync9(rootAgents)
7854
+ createable: !existsSync10(rootAgents)
5255
7855
  });
5256
7856
  for (const dir of projectChainDirs(projectRoot, cwd)) {
5257
7857
  for (const name2 of INSTRUCTION_CANDIDATES) {
5258
- const path = join17(dir, name2);
5259
- if (!existsSync9(path)) continue;
7858
+ const path = join18(dir, name2);
7859
+ if (!existsSync10(path)) continue;
5260
7860
  if (samePath2(path, rootAgents)) continue;
5261
7861
  pushUnique(instructions, seen, {
5262
7862
  id: entryId("project", path),
@@ -5300,8 +7900,8 @@ function discoverFilesystemSkills(options) {
5300
7900
  }
5301
7901
  for (const name2 of names) {
5302
7902
  if (isTransientSkillEntryName(name2)) continue;
5303
- const skillMd = join17(root, name2, "SKILL.md");
5304
- if (!existsSync9(skillMd)) continue;
7903
+ const skillMd = join18(root, name2, "SKILL.md");
7904
+ if (!existsSync10(skillMd)) continue;
5305
7905
  if (byName.has(name2)) continue;
5306
7906
  byName.set(name2, {
5307
7907
  id: `fs:${resolve11(skillMd).toLowerCase()}`,
@@ -5320,10 +7920,10 @@ function discoverFilesystemSkills(options) {
5320
7920
  return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
5321
7921
  }
5322
7922
  function dirnameLabel(root, projectRoot, env) {
5323
- if (samePath2(root, join17(projectRoot, ".agents", "skills"))) return "project";
5324
- if (samePath2(root, join17(projectRoot, ".dsh", "skills"))) return "project-dsh";
5325
- if (samePath2(root, join17(agentsHomeOf(env), "skills"))) return "shared";
5326
- if (samePath2(root, join17(dshHomeOf(env), "skills"))) return "dsh-home";
7923
+ if (samePath2(root, join18(projectRoot, ".agents", "skills"))) return "project";
7924
+ if (samePath2(root, join18(projectRoot, ".dsh", "skills"))) return "project-dsh";
7925
+ if (samePath2(root, join18(agentsHomeOf(env), "skills"))) return "shared";
7926
+ if (samePath2(root, join18(dshHomeOf(env), "skills"))) return "dsh-home";
5327
7927
  const parent = basename9(dirname7(root)).toLowerCase();
5328
7928
  const leaf = basename9(root).toLowerCase();
5329
7929
  if (parent === ".cursor" && leaf === "skills") return "cursor";
@@ -5361,23 +7961,23 @@ function normalizeRegistrySkills(raw) {
5361
7961
  function coerceSkillDocumentPath(path, _name) {
5362
7962
  if (path === null || path.trim() === "") return null;
5363
7963
  const absolute = resolve11(path.trim());
5364
- if (existsSync9(absolute)) {
7964
+ if (existsSync10(absolute)) {
5365
7965
  try {
5366
7966
  if (statSync2(absolute).isFile()) return absolute;
5367
7967
  } catch {
5368
7968
  }
5369
- const asFile = join17(absolute, "SKILL.md");
5370
- if (existsSync9(asFile)) return asFile;
7969
+ const asFile = join18(absolute, "SKILL.md");
7970
+ if (existsSync10(asFile)) return asFile;
5371
7971
  }
5372
7972
  const lower = absolute.toLowerCase();
5373
7973
  if (lower.endsWith("skill.md") || lower.endsWith(".md")) return absolute;
5374
- const nested = join17(absolute, "SKILL.md");
5375
- return existsSync9(nested) ? nested : absolute;
7974
+ const nested = join18(absolute, "SKILL.md");
7975
+ return existsSync10(nested) ? nested : absolute;
5376
7976
  }
5377
7977
  function resolveSkillPathFromRoots(name2, cwd, projectRoot, env) {
5378
7978
  for (const root of previewSkillSearchRoots(cwd, projectRoot, env)) {
5379
- const skillMd = join17(root, name2, "SKILL.md");
5380
- if (existsSync9(skillMd)) return resolve11(skillMd);
7979
+ const skillMd = join18(root, name2, "SKILL.md");
7980
+ if (existsSync10(skillMd)) return resolve11(skillMd);
5381
7981
  }
5382
7982
  return null;
5383
7983
  }
@@ -5538,22 +8138,22 @@ function parseGitSkillSource(raw) {
5538
8138
 
5539
8139
  // src/host/instructions-skills/install.ts
5540
8140
  import { execFile as execFile3, spawn } from "node:child_process";
5541
- import { existsSync as existsSync11, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
8141
+ import { existsSync as existsSync12, mkdtempSync, realpathSync, rmSync as rmSync4 } from "node:fs";
5542
8142
  import { tmpdir as tmpdir3 } from "node:os";
5543
- import { basename as basename11, dirname as dirname9, join as join21, resolve as resolve13 } from "node:path";
8143
+ import { basename as basename11, dirname as dirname9, join as join22, resolve as resolve13 } from "node:path";
5544
8144
  import { promisify as promisify3 } from "node:util";
5545
8145
 
5546
8146
  // src/host/instructions-skills/github-archive.ts
5547
8147
  import { execFile as execFile2 } from "node:child_process";
5548
8148
  import {
5549
8149
  createWriteStream,
5550
- mkdirSync as mkdirSync4,
8150
+ mkdirSync as mkdirSync5,
5551
8151
  readdirSync as readdirSync4,
5552
8152
  renameSync as renameSync4,
5553
8153
  rmSync as rmSync3,
5554
8154
  statSync as statSync3
5555
8155
  } from "node:fs";
5556
- import { join as join18 } from "node:path";
8156
+ import { join as join19 } from "node:path";
5557
8157
  import { Readable } from "node:stream";
5558
8158
  import { pipeline } from "node:stream/promises";
5559
8159
  import { promisify as promisify2 } from "node:util";
@@ -5598,7 +8198,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
5598
8198
  }
5599
8199
  async function extractZip(zipPath, destDir, signal) {
5600
8200
  signal.throwIfAborted();
5601
- mkdirSync4(destDir, { recursive: true });
8201
+ mkdirSync5(destDir, { recursive: true });
5602
8202
  try {
5603
8203
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
5604
8204
  windowsHide: true,
@@ -5617,7 +8217,7 @@ function unwrapArchiveRoot(extractDir) {
5617
8217
  return extractDir;
5618
8218
  }
5619
8219
  if (entries.length !== 1) return extractDir;
5620
- const only = join18(extractDir, entries[0]);
8220
+ const only = join19(extractDir, entries[0]);
5621
8221
  try {
5622
8222
  if (statSync3(only).isDirectory()) return only;
5623
8223
  } catch {
@@ -5656,10 +8256,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
5656
8256
  }
5657
8257
  async function fetchGithubRepoArchive(options) {
5658
8258
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
5659
- mkdirSync4(workDir, { recursive: true });
5660
- const zipPath = join18(workDir, "repo.zip");
5661
- const extractDir = join18(workDir, "extract");
5662
- mkdirSync4(extractDir, { recursive: true });
8259
+ mkdirSync5(workDir, { recursive: true });
8260
+ const zipPath = join19(workDir, "repo.zip");
8261
+ const extractDir = join19(workDir, "extract");
8262
+ mkdirSync5(extractDir, { recursive: true });
5663
8263
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
5664
8264
  const candidates = archiveCandidates(owner, repo, defaultBranch);
5665
8265
  const errors = [];
@@ -5670,7 +8270,7 @@ async function fetchGithubRepoArchive(options) {
5670
8270
  try {
5671
8271
  rmSync3(zipPath, { force: true });
5672
8272
  rmSync3(extractDir, { recursive: true, force: true });
5673
- mkdirSync4(extractDir, { recursive: true });
8273
+ mkdirSync5(extractDir, { recursive: true });
5674
8274
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
5675
8275
  if (!downloadStarted) {
5676
8276
  onStage?.("downloading", detail);
@@ -5682,7 +8282,7 @@ async function fetchGithubRepoArchive(options) {
5682
8282
  onStage?.("extracting", `${owner}/${repo}`);
5683
8283
  await extractZip(zipPath, extractDir, signal);
5684
8284
  const root = unwrapArchiveRoot(extractDir);
5685
- const repoDir = join18(workDir, "repo");
8285
+ const repoDir = join19(workDir, "repo");
5686
8286
  rmSync3(repoDir, { recursive: true, force: true });
5687
8287
  renameSync4(root, repoDir);
5688
8288
  try {
@@ -5712,15 +8312,15 @@ async function fetchGithubRepoArchive(options) {
5712
8312
  // src/host/instructions-skills/install-fs.ts
5713
8313
  import {
5714
8314
  cpSync,
5715
- existsSync as existsSync10,
8315
+ existsSync as existsSync11,
5716
8316
  lstatSync as lstatSync4,
5717
- mkdirSync as mkdirSync5,
8317
+ mkdirSync as mkdirSync6,
5718
8318
  readdirSync as readdirSync5,
5719
8319
  readFileSync as readFileSync4,
5720
8320
  renameSync as renameSync5,
5721
8321
  symlinkSync
5722
8322
  } from "node:fs";
5723
- import { basename as basename10, dirname as dirname8, join as join19, resolve as resolve12 } from "node:path";
8323
+ import { basename as basename10, dirname as dirname8, join as join20, resolve as resolve12 } from "node:path";
5724
8324
  function frontmatterBlock(path) {
5725
8325
  try {
5726
8326
  const text3 = readFileSync4(path, "utf8");
@@ -5740,13 +8340,13 @@ function nameFromSkillPath(path, fallback) {
5740
8340
  return fallback;
5741
8341
  }
5742
8342
  function directoryBundleName(dir, folderName) {
5743
- return nameFromSkillPath(join19(dir, "SKILL.md"), folderName);
8343
+ return nameFromSkillPath(join20(dir, "SKILL.md"), folderName);
5744
8344
  }
5745
8345
  function findSkillBundles(root) {
5746
8346
  const absolute = resolve12(root);
5747
- if (!existsSync10(absolute)) return [];
5748
- const rootSkill = join19(absolute, "SKILL.md");
5749
- if (existsSync10(rootSkill)) {
8347
+ if (!existsSync11(absolute)) return [];
8348
+ const rootSkill = join20(absolute, "SKILL.md");
8349
+ if (existsSync11(rootSkill)) {
5750
8350
  const folderName = basename10(absolute);
5751
8351
  const name2 = directoryBundleName(absolute, folderName);
5752
8352
  if (isKebabCaseName(name2)) {
@@ -5762,8 +8362,8 @@ function findSkillBundles(root) {
5762
8362
  }
5763
8363
  for (const entry of entries) {
5764
8364
  if (isTransientSkillEntryName(entry)) continue;
5765
- const full = join19(absolute, entry);
5766
- if (existsSync10(join19(full, "SKILL.md"))) {
8365
+ const full = join20(absolute, entry);
8366
+ if (existsSync11(join20(full, "SKILL.md"))) {
5767
8367
  const name2 = directoryBundleName(full, entry);
5768
8368
  if (!isKebabCaseName(name2)) continue;
5769
8369
  out.push({ name: name2, sourcePath: full, kind: "directory" });
@@ -5785,10 +8385,10 @@ function findSkillBundles(root) {
5785
8385
  }
5786
8386
  function resolveBundlesFromClone(cloneRoot, subpath) {
5787
8387
  const base = subpath === null || subpath === "" ? resolve12(cloneRoot) : resolve12(cloneRoot, subpath);
5788
- if (!existsSync10(base)) {
8388
+ if (!existsSync11(base)) {
5789
8389
  throw new AuxiliaryError("FILE_NOT_FOUND", `Path not found in repository: ${subpath ?? "."}`);
5790
8390
  }
5791
- if (base.toLowerCase().endsWith("skill.md") && existsSync10(base)) {
8391
+ if (base.toLowerCase().endsWith("skill.md") && existsSync11(base)) {
5792
8392
  const dir = dirname8(base);
5793
8393
  const name2 = directoryBundleName(dir, basename10(dir));
5794
8394
  if (!isKebabCaseName(name2)) {
@@ -5798,8 +8398,8 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
5798
8398
  }
5799
8399
  const direct = findSkillBundles(base);
5800
8400
  if (direct.length > 0) return direct;
5801
- for (const rel of ["skills", join19(".agents", "skills"), join19(".dsh", "skills")]) {
5802
- const nested = join19(base, rel);
8401
+ for (const rel of ["skills", join20(".agents", "skills"), join20(".dsh", "skills")]) {
8402
+ const nested = join20(base, rel);
5803
8403
  const found = findSkillBundles(nested);
5804
8404
  if (found.length > 0) return found;
5805
8405
  }
@@ -5808,13 +8408,13 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
5808
8408
  function installTargetDir(target, projectRoot, agentsHome, dshHome2) {
5809
8409
  switch (target) {
5810
8410
  case "user":
5811
- return join19(resolve12(agentsHome), "skills");
8411
+ return join20(resolve12(agentsHome), "skills");
5812
8412
  case "user-dsh":
5813
- return join19(resolve12(dshHome2), "skills");
8413
+ return join20(resolve12(dshHome2), "skills");
5814
8414
  case "project":
5815
- return join19(resolve12(projectRoot), ".agents", "skills");
8415
+ return join20(resolve12(projectRoot), ".agents", "skills");
5816
8416
  case "project-dsh":
5817
- return join19(resolve12(projectRoot), ".dsh", "skills");
8417
+ return join20(resolve12(projectRoot), ".dsh", "skills");
5818
8418
  default: {
5819
8419
  const _exhaustive = target;
5820
8420
  return _exhaustive;
@@ -5822,7 +8422,7 @@ function installTargetDir(target, projectRoot, agentsHome, dshHome2) {
5822
8422
  }
5823
8423
  }
5824
8424
  function destinationForBundle(targetDir, bundle) {
5825
- return bundle.kind === "directory" ? join19(targetDir, bundle.name) : join19(targetDir, `${bundle.name}.md`);
8425
+ return bundle.kind === "directory" ? join20(targetDir, bundle.name) : join20(targetDir, `${bundle.name}.md`);
5826
8426
  }
5827
8427
  function removeDestination(dest) {
5828
8428
  removePathRobust(dest);
@@ -5840,13 +8440,13 @@ function isStaleSkillDestination(dest, kind) {
5840
8440
  if (kind === "file") {
5841
8441
  try {
5842
8442
  const stat = lstatSync4(dest);
5843
- if (stat.isSymbolicLink()) return !existsSync10(dest);
8443
+ if (stat.isSymbolicLink()) return !existsSync11(dest);
5844
8444
  return !stat.isFile();
5845
8445
  } catch {
5846
8446
  return true;
5847
8447
  }
5848
8448
  }
5849
- return !existsSync10(join19(dest, "SKILL.md"));
8449
+ return !existsSync11(join20(dest, "SKILL.md"));
5850
8450
  }
5851
8451
  function copySkillTree(source, dest) {
5852
8452
  try {
@@ -5863,7 +8463,7 @@ function copySkillTree(source, dest) {
5863
8463
  }
5864
8464
  }
5865
8465
  function copySkillTreeAtomic(source, dest, kind) {
5866
- mkdirSync5(dirname8(dest), { recursive: true });
8466
+ mkdirSync6(dirname8(dest), { recursive: true });
5867
8467
  if (kind === "file") {
5868
8468
  if (destinationPresent(dest)) removeDestination(dest);
5869
8469
  copySkillTree(source, dest);
@@ -5891,7 +8491,7 @@ function copySkillTreeAtomic(source, dest, kind) {
5891
8491
  }
5892
8492
  }
5893
8493
  function linkOrCopy(source, dest, mode, kind) {
5894
- mkdirSync5(dirname8(dest), { recursive: true });
8494
+ mkdirSync6(dirname8(dest), { recursive: true });
5895
8495
  if (mode === "copy") {
5896
8496
  copySkillTreeAtomic(source, dest, kind);
5897
8497
  return "copy";
@@ -5899,7 +8499,7 @@ function linkOrCopy(source, dest, mode, kind) {
5899
8499
  try {
5900
8500
  if (process.platform === "win32") {
5901
8501
  const stat = lstatSync4(source);
5902
- if (stat.isDirectory() || stat.isSymbolicLink() && existsSync10(join19(source, "SKILL.md"))) {
8502
+ if (stat.isDirectory() || stat.isSymbolicLink() && existsSync11(join20(source, "SKILL.md"))) {
5903
8503
  symlinkSync(source, dest, "junction");
5904
8504
  return "link";
5905
8505
  }
@@ -5930,12 +8530,12 @@ function installBundle(options) {
5930
8530
  // src/host/instructions-skills/content-revision.ts
5931
8531
  import { createHash as createHash7 } from "node:crypto";
5932
8532
  import { readdirSync as readdirSync6, readFileSync as readFileSync5 } from "node:fs";
5933
- import { join as join20, relative as relative3 } from "node:path";
8533
+ import { join as join21, relative as relative3 } from "node:path";
5934
8534
  function listRelativeFiles(dir, root) {
5935
8535
  const entries = [];
5936
8536
  for (const entry of readdirSync6(dir, { withFileTypes: true })) {
5937
8537
  if (entry.name.startsWith(".")) continue;
5938
- const abs = join20(dir, entry.name);
8538
+ const abs = join21(dir, entry.name);
5939
8539
  if (entry.isDirectory()) {
5940
8540
  entries.push(...listRelativeFiles(abs, root));
5941
8541
  } else if (entry.isFile()) {
@@ -5948,7 +8548,7 @@ function contentRevisionOfDir(dir) {
5948
8548
  const paths = listRelativeFiles(dir, dir).sort();
5949
8549
  const aggregate = createHash7("sha256");
5950
8550
  for (const relPath of paths) {
5951
- const contents = readFileSync5(join20(dir, relPath));
8551
+ const contents = readFileSync5(join21(dir, relPath));
5952
8552
  const fileDigest = createHash7("sha256").update(`${relPath}\0`).update(contents).digest();
5953
8553
  aggregate.update(fileDigest);
5954
8554
  }
@@ -6057,7 +8657,7 @@ function tempWorkDir(prefix) {
6057
8657
  base = realpathSync(base);
6058
8658
  } catch {
6059
8659
  }
6060
- return mkdtempSync(join21(base, prefix));
8660
+ return mkdtempSync(join22(base, prefix));
6061
8661
  }
6062
8662
  function execDetail(error) {
6063
8663
  if (!(error instanceof Error)) return String(error);
@@ -6159,7 +8759,7 @@ async function materializeSkillGitTreeFromSource(source, workDir, signal, progre
6159
8759
  return { rootDir, parsed };
6160
8760
  }
6161
8761
  async function materializeRepo(parsed, workDir, signal, progressSessionId) {
6162
- const cloneDir = join21(workDir, "repo");
8762
+ const cloneDir = join22(workDir, "repo");
6163
8763
  const archiveErrors = [];
6164
8764
  const sessionId = progressSessionId?.trim() ?? "";
6165
8765
  if (parsed.github !== null) {
@@ -6300,14 +8900,14 @@ async function installSkillsFromGit(options) {
6300
8900
  // src/host/instructions-skills/update-check.ts
6301
8901
  import { mkdtempSync as mkdtempSync2, realpathSync as realpathSync2, rmSync as rmSync5 } from "node:fs";
6302
8902
  import { tmpdir as tmpdir4 } from "node:os";
6303
- import { join as join22 } from "node:path";
8903
+ import { join as join23 } from "node:path";
6304
8904
  function tempWorkDir2(prefix) {
6305
8905
  let base = tmpdir4();
6306
8906
  try {
6307
8907
  base = realpathSync2(base);
6308
8908
  } catch {
6309
8909
  }
6310
- return mkdtempSync2(join22(base, prefix));
8910
+ return mkdtempSync2(join23(base, prefix));
6311
8911
  }
6312
8912
  function revisionPathForBundle(bundle) {
6313
8913
  return bundle.kind === "directory" ? bundle.sourcePath : bundle.sourcePath;
@@ -6366,9 +8966,9 @@ async function checkGithubSkillUpdate(record2, options) {
6366
8966
 
6367
8967
  // src/host/instructions-skills/zip-install.ts
6368
8968
  import { execFile as execFile4 } from "node:child_process";
6369
- import { existsSync as existsSync12, mkdirSync as mkdirSync6, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
8969
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
6370
8970
  import { tmpdir as tmpdir5 } from "node:os";
6371
- import { basename as basename12, join as join23, resolve as resolve14 } from "node:path";
8971
+ import { basename as basename12, join as join24, resolve as resolve14 } from "node:path";
6372
8972
  import { promisify as promisify4 } from "node:util";
6373
8973
  var execFileAsync4 = promisify4(execFile4);
6374
8974
  function tempWorkDir3(prefix) {
@@ -6377,11 +8977,11 @@ function tempWorkDir3(prefix) {
6377
8977
  base = realpathSync3(base);
6378
8978
  } catch {
6379
8979
  }
6380
- return mkdtempSync3(join23(base, prefix));
8980
+ return mkdtempSync3(join24(base, prefix));
6381
8981
  }
6382
8982
  async function extractZipArchive(zipPath, destDir, signal) {
6383
8983
  signal.throwIfAborted();
6384
- mkdirSync6(destDir, { recursive: true });
8984
+ mkdirSync7(destDir, { recursive: true });
6385
8985
  try {
6386
8986
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
6387
8987
  windowsHide: true,
@@ -6395,14 +8995,14 @@ async function extractZipArchive(zipPath, destDir, signal) {
6395
8995
  }
6396
8996
  async function installSkillsFromZipFile(options) {
6397
8997
  const zipPath = resolve14(options.zipPath);
6398
- if (!existsSync12(zipPath)) {
8998
+ if (!existsSync13(zipPath)) {
6399
8999
  throw new AuxiliaryError("FILE_NOT_FOUND", `Zip not found: ${zipPath}`);
6400
9000
  }
6401
9001
  if (!zipPath.toLowerCase().endsWith(".zip")) {
6402
9002
  throw new AuxiliaryError("FILE_DENIED", `Expected a .zip archive: ${basename12(zipPath)}`);
6403
9003
  }
6404
9004
  const workDir = tempWorkDir3("ae-skill-zip-");
6405
- const extractDir = join23(workDir, "extract");
9005
+ const extractDir = join24(workDir, "extract");
6406
9006
  try {
6407
9007
  await extractZipArchive(zipPath, extractDir, options.signal);
6408
9008
  const root = unwrapArchiveRoot(extractDir);
@@ -6565,12 +9165,12 @@ async function enrichSkillsFromLedger(skills, options) {
6565
9165
  }
6566
9166
  function inferSkillInstallTarget(name2, cwd, projectRoot, env = process.env) {
6567
9167
  const roots = skillRootsFor(cwd, projectRoot, env);
6568
- const projectAgents = join24(resolve15(projectRoot), ".agents", "skills");
6569
- const projectDsh = join24(resolve15(projectRoot), ".dsh", "skills");
6570
- const userAgents = join24(agentsHomeOf(env), "skills");
6571
- const userDsh = join24(dshHomeOf(env), "skills");
9168
+ const projectAgents = join25(resolve15(projectRoot), ".agents", "skills");
9169
+ const projectDsh = join25(resolve15(projectRoot), ".dsh", "skills");
9170
+ const userAgents = join25(agentsHomeOf(env), "skills");
9171
+ const userDsh = join25(dshHomeOf(env), "skills");
6572
9172
  for (const root of roots) {
6573
- const present = existsSync13(join24(root, name2, "SKILL.md")) || existsSync13(join24(root, `${name2}.md`));
9173
+ const present = existsSync14(join25(root, name2, "SKILL.md")) || existsSync14(join25(root, `${name2}.md`));
6574
9174
  if (!present) continue;
6575
9175
  if (samePath2(root, projectAgents)) return "project";
6576
9176
  if (samePath2(root, projectDsh)) return "project-dsh";
@@ -6808,7 +9408,7 @@ async function readSkillDocumentNow(options) {
6808
9408
  throw new AuxiliaryError("FILE_DENIED", "Only SKILL.md may be previewed");
6809
9409
  }
6810
9410
  options.signal.throwIfAborted();
6811
- if (!existsSync13(absolutePath2)) {
9411
+ if (!existsSync14(absolutePath2)) {
6812
9412
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
6813
9413
  }
6814
9414
  try {
@@ -6843,7 +9443,7 @@ async function readSkillDocumentNow(options) {
6843
9443
  }
6844
9444
 
6845
9445
  // src/host/mcp-connectors/io.ts
6846
- import { existsSync as existsSync15 } from "node:fs";
9446
+ import { existsSync as existsSync16 } from "node:fs";
6847
9447
 
6848
9448
  // src/host/mcp-connectors/validate.ts
6849
9449
  var MCP_SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
@@ -6965,22 +9565,22 @@ function parseMcpJsonText(jsonText) {
6965
9565
  }
6966
9566
 
6967
9567
  // src/host/mcp-connectors/install-git.ts
6968
- import { existsSync as existsSync14, mkdirSync as mkdirSync7, readFileSync as readFileSync7, renameSync as renameSync6, rmSync as rmSync7 } from "node:fs";
6969
- import { join as join26 } from "node:path";
9568
+ import { existsSync as existsSync15, mkdirSync as mkdirSync8, readFileSync as readFileSync7, renameSync as renameSync6, rmSync as rmSync7 } from "node:fs";
9569
+ import { join as join27 } from "node:path";
6970
9570
 
6971
9571
  // src/host/mcp-connectors/paths.ts
6972
- import { join as join25 } from "node:path";
9572
+ import { join as join26 } from "node:path";
6973
9573
  function mcpConnectorsRoot(pluginDataPackageRoot) {
6974
- return join25(pluginDataPackageRoot, "mcp-connectors");
9574
+ return join26(pluginDataPackageRoot, "mcp-connectors");
6975
9575
  }
6976
9576
  function mcpConnectorsLedgerPath(root) {
6977
- return join25(root, "mcp-connectors.json");
9577
+ return join26(root, "mcp-connectors.json");
6978
9578
  }
6979
9579
  function mcpServersRoot(root) {
6980
- return join25(root, "mcp-servers");
9580
+ return join26(root, "mcp-servers");
6981
9581
  }
6982
9582
  function mcpServerInstallDir(root, id) {
6983
- return join25(mcpServersRoot(root), id);
9583
+ return join26(mcpServersRoot(root), id);
6984
9584
  }
6985
9585
 
6986
9586
  // src/host/mcp-connectors/install-git.ts
@@ -6997,8 +9597,8 @@ function inferStdioFromPackageJson(installDir, override) {
6997
9597
  cwd: installDir
6998
9598
  };
6999
9599
  }
7000
- const pkgPath = join26(installDir, "package.json");
7001
- if (!existsSync14(pkgPath)) {
9600
+ const pkgPath = join27(installDir, "package.json");
9601
+ if (!existsSync15(pkgPath)) {
7002
9602
  return {
7003
9603
  transport: "stdio",
7004
9604
  command: "npx",
@@ -7015,7 +9615,7 @@ function inferStdioFromPackageJson(installDir, override) {
7015
9615
  return {
7016
9616
  transport: "stdio",
7017
9617
  command: process.execPath,
7018
- args: [join26(installDir, bin)],
9618
+ args: [join27(installDir, bin)],
7019
9619
  env: {},
7020
9620
  cwd: installDir
7021
9621
  };
@@ -7028,7 +9628,7 @@ function inferStdioFromPackageJson(installDir, override) {
7028
9628
  return {
7029
9629
  transport: "stdio",
7030
9630
  command: process.execPath,
7031
- args: [join26(installDir, first)],
9631
+ args: [join27(installDir, first)],
7032
9632
  env: {},
7033
9633
  cwd: installDir
7034
9634
  };
@@ -7038,7 +9638,7 @@ function inferStdioFromPackageJson(installDir, override) {
7038
9638
  return {
7039
9639
  transport: "stdio",
7040
9640
  command: process.execPath,
7041
- args: [join26(installDir, pkg.main)],
9641
+ args: [join27(installDir, pkg.main)],
7042
9642
  env: {},
7043
9643
  cwd: installDir
7044
9644
  };
@@ -7057,17 +9657,17 @@ function inferStdioFromPackageJson(installDir, override) {
7057
9657
  async function installMcpServerFromGit(options) {
7058
9658
  const parsed = parseGitSkillSource(options.source);
7059
9659
  const installDir = mcpServerInstallDir(options.rootDir, options.id);
7060
- if (existsSync14(installDir)) {
9660
+ if (existsSync15(installDir)) {
7061
9661
  if (!options.force) {
7062
9662
  throw new AuxiliaryError("FILE_EDIT_FAILED", `MCP install dir already exists: ${installDir}`);
7063
9663
  }
7064
9664
  removePathRobust(installDir);
7065
9665
  }
7066
- mkdirSync7(join26(options.rootDir, "mcp-servers"), { recursive: true });
9666
+ mkdirSync8(join27(options.rootDir, "mcp-servers"), { recursive: true });
7067
9667
  const staging = `${installDir}.staging.${process.pid}`;
7068
9668
  try {
7069
- if (existsSync14(staging)) removePathRobust(staging);
7070
- mkdirSync7(staging, { recursive: true });
9669
+ if (existsSync15(staging)) removePathRobust(staging);
9670
+ mkdirSync8(staging, { recursive: true });
7071
9671
  if (parsed.github === null) {
7072
9672
  throw new AuxiliaryError(
7073
9673
  "FILE_EDIT_FAILED",
@@ -7083,13 +9683,13 @@ async function installMcpServerFromGit(options) {
7083
9683
  options.signal.throwIfAborted();
7084
9684
  let contentRoot = repoDir;
7085
9685
  if (parsed.subpath !== null) {
7086
- const nested = join26(repoDir, parsed.subpath);
7087
- if (!existsSync14(nested)) {
9686
+ const nested = join27(repoDir, parsed.subpath);
9687
+ if (!existsSync15(nested)) {
7088
9688
  throw new AuxiliaryError("FILE_EDIT_FAILED", `Subpath not found in repo: ${parsed.subpath}`);
7089
9689
  }
7090
9690
  contentRoot = nested;
7091
9691
  }
7092
- mkdirSync7(join26(options.rootDir, "mcp-servers"), { recursive: true });
9692
+ mkdirSync8(join27(options.rootDir, "mcp-servers"), { recursive: true });
7093
9693
  if (contentRoot !== repoDir) {
7094
9694
  const nestedStaging = `${installDir}.nested.${process.pid}`;
7095
9695
  renameSync6(contentRoot, nestedStaging);
@@ -7104,11 +9704,11 @@ async function installMcpServerFromGit(options) {
7104
9704
  }
7105
9705
  } catch (error) {
7106
9706
  try {
7107
- if (existsSync14(staging)) rmSync7(staging, { recursive: true, force: true });
9707
+ if (existsSync15(staging)) rmSync7(staging, { recursive: true, force: true });
7108
9708
  } catch {
7109
9709
  }
7110
9710
  try {
7111
- if (existsSync14(installDir)) removePathRobust(installDir);
9711
+ if (existsSync15(installDir)) removePathRobust(installDir);
7112
9712
  } catch {
7113
9713
  }
7114
9714
  if (error instanceof AuxiliaryError) throw error;
@@ -7206,7 +9806,7 @@ async function uninstallMcpConnectorNow(host, request) {
7206
9806
  }
7207
9807
  const next = doc.connectors.filter((entry) => entry.id !== request.id);
7208
9808
  const installDir = mcpServerInstallDir(host.store.rootDir, request.id);
7209
- if (existsSync15(installDir)) {
9809
+ if (existsSync16(installDir)) {
7210
9810
  try {
7211
9811
  removePathRobust(installDir);
7212
9812
  } catch (error) {
@@ -7338,7 +9938,7 @@ function listMcpConnectorToolsNow(host, request) {
7338
9938
  }
7339
9939
 
7340
9940
  // src/host/mcp-connectors/store.ts
7341
- import { mkdirSync as mkdirSync8, readFileSync as readFileSync8, renameSync as renameSync7, writeFileSync as writeFileSync4 } from "node:fs";
9941
+ import { mkdirSync as mkdirSync9, readFileSync as readFileSync8, renameSync as renameSync7, writeFileSync as writeFileSync4 } from "node:fs";
7342
9942
  import { dirname as dirname10 } from "node:path";
7343
9943
 
7344
9944
  // src/host/mcp-connectors/types.ts
@@ -7421,7 +10021,7 @@ function parseDoc2(raw) {
7421
10021
  }
7422
10022
  }
7423
10023
  function createMcpConnectorsStore(rootDir) {
7424
- mkdirSync8(rootDir, { recursive: true });
10024
+ mkdirSync9(rootDir, { recursive: true });
7425
10025
  const file = mcpConnectorsLedgerPath(rootDir);
7426
10026
  return {
7427
10027
  rootDir,
@@ -7440,7 +10040,7 @@ function createMcpConnectorsStore(rootDir) {
7440
10040
  version: MCP_CONNECTORS_VERSION,
7441
10041
  connectors: [...connectors]
7442
10042
  };
7443
- mkdirSync8(dirname10(file), { recursive: true });
10043
+ mkdirSync9(dirname10(file), { recursive: true });
7444
10044
  const tmp = `${file}.${process.pid}.tmp`;
7445
10045
  writeFileSync4(tmp, `${JSON.stringify(doc, null, 2)}
7446
10046
  `, "utf8");
@@ -9351,7 +11951,7 @@ function mergeUsageCalls(stored, history) {
9351
11951
  // src/host/usage/ledger.ts
9352
11952
  import { randomUUID as randomUUID6 } from "node:crypto";
9353
11953
  import { chmod as chmod4, mkdir as mkdir5, readFile as readFile5, rename as rename4, unlink as unlink5, writeFile as writeFile4 } from "node:fs/promises";
9354
- import { basename as basename14, join as join27 } from "node:path";
11954
+ import { basename as basename14, join as join28 } from "node:path";
9355
11955
  import { z as z3 } from "zod";
9356
11956
  var callSchema = z3.object({
9357
11957
  at: z3.number().int().nonnegative(),
@@ -9381,7 +11981,7 @@ async function removeIfPresent5(path) {
9381
11981
  }
9382
11982
  }
9383
11983
  async function writeAtomic4(path, value) {
9384
- const temporary = join27(join27(path, ".."), `.${basename14(path)}.${randomUUID6()}.tmp`);
11984
+ const temporary = join28(join28(path, ".."), `.${basename14(path)}.${randomUUID6()}.tmp`);
9385
11985
  try {
9386
11986
  await writeFile4(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
9387
11987
  await rename4(temporary, path);
@@ -9395,7 +11995,7 @@ var UsageLedger = class {
9395
11995
  }) {
9396
11996
  this.root = root;
9397
11997
  this.warn = warn;
9398
- this.file = join27(root, "ledger.json");
11998
+ this.file = join28(root, "ledger.json");
9399
11999
  }
9400
12000
  root;
9401
12001
  warn;
@@ -9935,6 +12535,179 @@ var showOsNotificationResultCodec = codec(
9935
12535
  "dsh-agent-enhancer#ShowOsNotificationResult",
9936
12536
  showOsNotificationResultSchema
9937
12537
  );
12538
+ var browserAgentApprovalDecisionSchema = z4.enum(["allow-once", "allow-origin", "deny"]);
12539
+ var browserAgentPendingSchema = z4.strictObject({
12540
+ id: z4.string().min(1),
12541
+ sessionId: z4.string().min(1),
12542
+ tool: z4.string().min(1),
12543
+ summary: z4.string().min(1),
12544
+ url: z4.string().optional(),
12545
+ origin: z4.string().optional()
12546
+ });
12547
+ var browserAgentTabConflictSchema = z4.strictObject({
12548
+ sessionId: z4.string().min(1),
12549
+ boundTabId: z4.number().int(),
12550
+ activeTabId: z4.number().int()
12551
+ });
12552
+ var browserAgentNeedsHumanSchema = z4.strictObject({
12553
+ sessionId: z4.string().min(1),
12554
+ detail: z4.string().min(1)
12555
+ });
12556
+ var browserAgentAuditEntrySchema = z4.strictObject({
12557
+ at: z4.number(),
12558
+ sessionId: z4.string().min(1),
12559
+ tool: z4.string().min(1),
12560
+ summary: z4.string().min(1),
12561
+ url: z4.string().optional(),
12562
+ outcome: z4.enum(["ok", "denied", "error", "needs_human"])
12563
+ });
12564
+ var browserAgentSnapshotSchema = z4.strictObject({
12565
+ enabled: z4.boolean(),
12566
+ /** Settings preference (auto / chrome / edge). */
12567
+ browser: z4.enum(["auto", "chrome", "edge"]),
12568
+ /** Actually launched channel once ready; null when not running. */
12569
+ launchedBrowser: z4.enum(["chrome", "edge"]).nullable(),
12570
+ /** Shipping driver (Playwright only after MV3 retirement). */
12571
+ driver: z4.literal("playwright"),
12572
+ allowedOrigins: z4.array(z4.string()),
12573
+ /** Connection status (field name kept for client compatibility). */
12574
+ bridge: z4.strictObject({
12575
+ listening: z4.boolean(),
12576
+ port: z4.number().int(),
12577
+ extensionConnected: z4.boolean(),
12578
+ lastError: z4.string().nullable()
12579
+ }),
12580
+ pending: browserAgentPendingSchema.nullable(),
12581
+ tabConflict: browserAgentTabConflictSchema.nullable(),
12582
+ needsHuman: browserAgentNeedsHumanSchema.nullable(),
12583
+ boundTabId: z4.number().int().nullable(),
12584
+ audit: z4.array(browserAgentAuditEntrySchema),
12585
+ /** Dedicated Chromium profile used by one-click launch (user-level). */
12586
+ profileDir: z4.string().min(1)
12587
+ });
12588
+ var browserAgentSnapshotCodec = codec(
12589
+ "dsh-agent-enhancer#BrowserAgentSnapshot",
12590
+ browserAgentSnapshotSchema
12591
+ );
12592
+ var browserAgentResolveRequestSchema = z4.strictObject({
12593
+ id: z4.string().min(1),
12594
+ decision: browserAgentApprovalDecisionSchema
12595
+ });
12596
+ var browserAgentResolveRequestCodec = codec(
12597
+ "dsh-agent-enhancer#BrowserAgentResolveRequest",
12598
+ browserAgentResolveRequestSchema
12599
+ );
12600
+ var browserAgentResolveResultSchema = z4.strictObject({
12601
+ ok: z4.boolean(),
12602
+ snapshot: browserAgentSnapshotSchema
12603
+ });
12604
+ var browserAgentResolveResultCodec = codec(
12605
+ "dsh-agent-enhancer#BrowserAgentResolveResult",
12606
+ browserAgentResolveResultSchema
12607
+ );
12608
+ var browserAgentResolveTabConflictRequestSchema = z4.strictObject({
12609
+ decision: z4.enum(["follow", "stay"])
12610
+ });
12611
+ var browserAgentResolveTabConflictRequestCodec = codec(
12612
+ "dsh-agent-enhancer#BrowserAgentResolveTabConflictRequest",
12613
+ browserAgentResolveTabConflictRequestSchema
12614
+ );
12615
+ var browserAgentResolveTabConflictResultSchema = z4.strictObject({
12616
+ ok: z4.boolean(),
12617
+ snapshot: browserAgentSnapshotSchema
12618
+ });
12619
+ var browserAgentResolveTabConflictResultCodec = codec(
12620
+ "dsh-agent-enhancer#BrowserAgentResolveTabConflictResult",
12621
+ browserAgentResolveTabConflictResultSchema
12622
+ );
12623
+ var browserAgentAcknowledgeHumanRequestSchema = z4.strictObject({
12624
+ sessionId: z4.string().min(1).optional()
12625
+ });
12626
+ var browserAgentAcknowledgeHumanRequestCodec = codec(
12627
+ "dsh-agent-enhancer#BrowserAgentAcknowledgeHumanRequest",
12628
+ browserAgentAcknowledgeHumanRequestSchema
12629
+ );
12630
+ var browserAgentAcknowledgeHumanResultSchema = z4.strictObject({
12631
+ ok: z4.boolean(),
12632
+ snapshot: browserAgentSnapshotSchema
12633
+ });
12634
+ var browserAgentAcknowledgeHumanResultCodec = codec(
12635
+ "dsh-agent-enhancer#BrowserAgentAcknowledgeHumanResult",
12636
+ browserAgentAcknowledgeHumanResultSchema
12637
+ );
12638
+ var browserAgentOpenUrlRequestSchema = z4.strictObject({
12639
+ sessionId: z4.string().min(1),
12640
+ url: z4.string().min(1)
12641
+ });
12642
+ var browserAgentOpenUrlRequestCodec = codec(
12643
+ "dsh-agent-enhancer#BrowserAgentOpenUrlRequest",
12644
+ browserAgentOpenUrlRequestSchema
12645
+ );
12646
+ var browserAgentOpenUrlResultSchema = z4.strictObject({
12647
+ ok: z4.boolean(),
12648
+ url: z4.string().optional(),
12649
+ title: z4.string().optional(),
12650
+ error: z4.string().optional(),
12651
+ snapshot: browserAgentSnapshotSchema
12652
+ });
12653
+ var browserAgentOpenUrlResultCodec = codec(
12654
+ "dsh-agent-enhancer#BrowserAgentOpenUrlResult",
12655
+ browserAgentOpenUrlResultSchema
12656
+ );
12657
+ var browserAgentQuotePageRequestSchema = z4.strictObject({
12658
+ sessionId: z4.string().min(1)
12659
+ });
12660
+ var browserAgentQuotePageRequestCodec = codec(
12661
+ "dsh-agent-enhancer#BrowserAgentQuotePageRequest",
12662
+ browserAgentQuotePageRequestSchema
12663
+ );
12664
+ var browserAgentQuotePageResultSchema = z4.strictObject({
12665
+ ok: z4.boolean(),
12666
+ text: z4.string().optional(),
12667
+ url: z4.string().optional(),
12668
+ title: z4.string().optional(),
12669
+ error: z4.string().optional(),
12670
+ snapshot: browserAgentSnapshotSchema
12671
+ });
12672
+ var browserAgentQuotePageResultCodec = codec(
12673
+ "dsh-agent-enhancer#BrowserAgentQuotePageResult",
12674
+ browserAgentQuotePageResultSchema
12675
+ );
12676
+ var browserAgentLaunchBrowserRequestSchema = z4.strictObject({
12677
+ browser: z4.enum(["auto", "chrome", "edge"]).optional()
12678
+ });
12679
+ var browserAgentLaunchBrowserRequestCodec = codec(
12680
+ "dsh-agent-enhancer#BrowserAgentLaunchBrowserRequest",
12681
+ browserAgentLaunchBrowserRequestSchema
12682
+ );
12683
+ var browserAgentLaunchBrowserResultSchema = z4.strictObject({
12684
+ ok: z4.boolean(),
12685
+ browser: z4.enum(["chrome", "edge"]).optional(),
12686
+ executable: z4.string().optional(),
12687
+ profileDir: z4.string().min(1),
12688
+ error: z4.string().optional(),
12689
+ snapshot: browserAgentSnapshotSchema
12690
+ });
12691
+ var browserAgentLaunchBrowserResultCodec = codec(
12692
+ "dsh-agent-enhancer#BrowserAgentLaunchBrowserResult",
12693
+ browserAgentLaunchBrowserResultSchema
12694
+ );
12695
+ var browserAgentSetBrowserRequestSchema = z4.strictObject({
12696
+ browser: z4.enum(["auto", "chrome", "edge"])
12697
+ });
12698
+ var browserAgentSetBrowserRequestCodec = codec(
12699
+ "dsh-agent-enhancer#BrowserAgentSetBrowserRequest",
12700
+ browserAgentSetBrowserRequestSchema
12701
+ );
12702
+ var browserAgentSetBrowserResultSchema = z4.strictObject({
12703
+ ok: z4.boolean(),
12704
+ browser: z4.enum(["auto", "chrome", "edge"]),
12705
+ snapshot: browserAgentSnapshotSchema
12706
+ });
12707
+ var browserAgentSetBrowserResultCodec = codec(
12708
+ "dsh-agent-enhancer#BrowserAgentSetBrowserResult",
12709
+ browserAgentSetBrowserResultSchema
12710
+ );
9938
12711
  var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
9939
12712
  var instructionFileEntrySchema = z4.strictObject({
9940
12713
  id: z4.string().min(1),
@@ -10527,6 +13300,97 @@ var remoteInfo = createTypertRemoteInfo({
10527
13300
  }],
10528
13301
  result: showOsNotificationResultCodec
10529
13302
  },
13303
+ "agentEnhancer/browserAgentSnapshot": {
13304
+ service: "agentEnhancer",
13305
+ implementation: "browserAgentSnapshot",
13306
+ invocation: { kind: "direct" },
13307
+ parameters: [],
13308
+ result: browserAgentSnapshotCodec
13309
+ },
13310
+ "agentEnhancer/browserAgentResolve": {
13311
+ service: "agentEnhancer",
13312
+ implementation: "browserAgentResolve",
13313
+ invocation: { kind: "direct" },
13314
+ parameters: [{
13315
+ name: "request",
13316
+ source: "json",
13317
+ codec: browserAgentResolveRequestCodec,
13318
+ strictCodec: browserAgentResolveRequestCodec
13319
+ }],
13320
+ result: browserAgentResolveResultCodec
13321
+ },
13322
+ "agentEnhancer/browserAgentResolveTabConflict": {
13323
+ service: "agentEnhancer",
13324
+ implementation: "browserAgentResolveTabConflict",
13325
+ invocation: { kind: "direct" },
13326
+ parameters: [{
13327
+ name: "request",
13328
+ source: "json",
13329
+ codec: browserAgentResolveTabConflictRequestCodec,
13330
+ strictCodec: browserAgentResolveTabConflictRequestCodec
13331
+ }],
13332
+ result: browserAgentResolveTabConflictResultCodec
13333
+ },
13334
+ "agentEnhancer/browserAgentAcknowledgeHuman": {
13335
+ service: "agentEnhancer",
13336
+ implementation: "browserAgentAcknowledgeHuman",
13337
+ invocation: { kind: "direct" },
13338
+ parameters: [{
13339
+ name: "request",
13340
+ source: "json",
13341
+ codec: browserAgentAcknowledgeHumanRequestCodec,
13342
+ strictCodec: browserAgentAcknowledgeHumanRequestCodec
13343
+ }],
13344
+ result: browserAgentAcknowledgeHumanResultCodec
13345
+ },
13346
+ "agentEnhancer/browserAgentOpenUrl": {
13347
+ service: "agentEnhancer",
13348
+ implementation: "browserAgentOpenUrl",
13349
+ invocation: { kind: "direct" },
13350
+ parameters: [{
13351
+ name: "request",
13352
+ source: "json",
13353
+ codec: browserAgentOpenUrlRequestCodec,
13354
+ strictCodec: browserAgentOpenUrlRequestCodec
13355
+ }],
13356
+ result: browserAgentOpenUrlResultCodec
13357
+ },
13358
+ "agentEnhancer/browserAgentQuotePage": {
13359
+ service: "agentEnhancer",
13360
+ implementation: "browserAgentQuotePage",
13361
+ invocation: { kind: "direct" },
13362
+ parameters: [{
13363
+ name: "request",
13364
+ source: "json",
13365
+ codec: browserAgentQuotePageRequestCodec,
13366
+ strictCodec: browserAgentQuotePageRequestCodec
13367
+ }],
13368
+ result: browserAgentQuotePageResultCodec
13369
+ },
13370
+ "agentEnhancer/browserAgentLaunchBrowser": {
13371
+ service: "agentEnhancer",
13372
+ implementation: "browserAgentLaunchBrowser",
13373
+ invocation: { kind: "direct" },
13374
+ parameters: [{
13375
+ name: "request",
13376
+ source: "json",
13377
+ codec: browserAgentLaunchBrowserRequestCodec,
13378
+ strictCodec: browserAgentLaunchBrowserRequestCodec
13379
+ }],
13380
+ result: browserAgentLaunchBrowserResultCodec
13381
+ },
13382
+ "agentEnhancer/browserAgentSetBrowser": {
13383
+ service: "agentEnhancer",
13384
+ implementation: "browserAgentSetBrowser",
13385
+ invocation: { kind: "direct" },
13386
+ parameters: [{
13387
+ name: "request",
13388
+ source: "json",
13389
+ codec: browserAgentSetBrowserRequestCodec,
13390
+ strictCodec: browserAgentSetBrowserRequestCodec
13391
+ }],
13392
+ result: browserAgentSetBrowserResultCodec
13393
+ },
10530
13394
  "agentEnhancer/listInstructionsSkills": {
10531
13395
  service: "agentEnhancer",
10532
13396
  implementation: "listInstructionsSkills",
@@ -11016,6 +13880,7 @@ async function showOsNotificationNow(input) {
11016
13880
  const title = input.title.trim();
11017
13881
  const body = input.body.trim();
11018
13882
  if (title === "" || body === "") return { shown: false, channel: "none" };
13883
+ if (process.env.VITEST === "true") return { shown: false, channel: "none" };
11019
13884
  const payload = {
11020
13885
  title: title.slice(0, 120),
11021
13886
  body: body.slice(0, 240),
@@ -11030,8 +13895,8 @@ async function showOsNotificationNow(input) {
11030
13895
  }
11031
13896
 
11032
13897
  // src/host/update/check.ts
11033
- import { homedir as homedir4 } from "node:os";
11034
- import { join as join29 } from "node:path";
13898
+ import { homedir as homedir5 } from "node:os";
13899
+ import { join as join30 } from "node:path";
11035
13900
 
11036
13901
  // src/host/update/cli.ts
11037
13902
  import { spawn as nodeSpawn } from "node:child_process";
@@ -11102,9 +13967,9 @@ async function runPluginAdd(latest, spawnFn = defaultSpawn) {
11102
13967
 
11103
13968
  // src/host/update/install-kind.ts
11104
13969
  import { lstatSync as lstatSync5 } from "node:fs";
11105
- import { join as join28 } from "node:path";
13970
+ import { join as join29 } from "node:path";
11106
13971
  function detectInstallKind(profileDir) {
11107
- const pkgPath = join28(profileDir, "node_modules", PACKAGE_NAME);
13972
+ const pkgPath = join29(profileDir, "node_modules", PACKAGE_NAME);
11108
13973
  try {
11109
13974
  const stat = lstatSync5(pkgPath);
11110
13975
  if (stat.isSymbolicLink()) return "link";
@@ -11234,9 +14099,9 @@ function isNewerVersion(latest, current) {
11234
14099
  }
11235
14100
 
11236
14101
  // src/host/update/check.ts
11237
- function resolveDesktopProfileDir(env = process.env, home = homedir4()) {
11238
- const dshHome2 = env.DSH_HOME ?? join29(home, ".dsh");
11239
- return join29(dshHome2, "profiles", "desktop");
14102
+ function resolveDesktopProfileDir(env = process.env, home = homedir5()) {
14103
+ const dshHome2 = env.DSH_HOME ?? join30(home, ".dsh");
14104
+ return join30(dshHome2, "profiles", "desktop");
11240
14105
  }
11241
14106
  async function checkPluginUpdate(deps) {
11242
14107
  const latest = await deps.fetchLatest();
@@ -11325,6 +14190,9 @@ var Config = z5.object({
11325
14190
  runAlertsEnabled: z5.boolean().default(true).volatile(),
11326
14191
  /** Coerced via resolveRunAlertsLevel in readSettings (`hidden` | `unfocused` | `always`). */
11327
14192
  runAlertsLevel: z5.string().default("unfocused").volatile(),
14193
+ /** High-risk; default off. */
14194
+ browserAgentEnabled: z5.boolean().default(false).volatile(),
14195
+ browserAgentBrowser: z5.string().default("auto").volatile(),
11328
14196
  instructionsSkillsEnabled: z5.boolean().default(true).volatile(),
11329
14197
  mcpConnectorsEnabled: z5.boolean().default(true).volatile(),
11330
14198
  // Empty provider/model = follow the current Desktop session model.
@@ -11371,8 +14239,13 @@ var AgentEnhancerService = class extends TypertRemoteService {
11371
14239
  };
11372
14240
  }
11373
14241
  }, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
11374
- join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
11375
- ), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null) {
14242
+ join31(homedir6(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
14243
+ ), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null, browserAgent = null, browserAgentSettings = () => ({
14244
+ enabled: false,
14245
+ browser: "auto"
14246
+ }), setBrowserAgentBrowser = () => void 0, browserAgentProfileDir = defaultBrowserAgentProfileDir(
14247
+ join31(homedir6(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
14248
+ )) {
11376
14249
  super(ctx, "agentEnhancer");
11377
14250
  this.models = models;
11378
14251
  this.usage = usage;
@@ -11383,6 +14256,10 @@ var AgentEnhancerService = class extends TypertRemoteService {
11383
14256
  this.softPauseEnabled = softPauseEnabled;
11384
14257
  this.installLedgerRoot = installLedgerRoot;
11385
14258
  this.mcpHost = mcpHost;
14259
+ this.browserAgent = browserAgent;
14260
+ this.browserAgentSettings = browserAgentSettings;
14261
+ this.setBrowserAgentBrowser = setBrowserAgentBrowser;
14262
+ this.browserAgentProfileDir = browserAgentProfileDir;
11386
14263
  }
11387
14264
  models;
11388
14265
  usage;
@@ -11393,6 +14270,52 @@ var AgentEnhancerService = class extends TypertRemoteService {
11393
14270
  softPauseEnabled;
11394
14271
  installLedgerRoot;
11395
14272
  mcpHost;
14273
+ browserAgent;
14274
+ browserAgentSettings;
14275
+ setBrowserAgentBrowser;
14276
+ browserAgentProfileDir;
14277
+ browserSnapshotNow() {
14278
+ const settings = this.browserAgentSettings();
14279
+ const driverStatus = this.browserAgent?.driverStatus();
14280
+ const pending = this.browserAgent?.approval.current() ?? null;
14281
+ const conflict = this.browserAgent?.sessions.currentConflict() ?? null;
14282
+ const waiting = this.browserAgent?.human.current() ?? null;
14283
+ const needsHuman = waiting !== null ? {
14284
+ sessionId: waiting.sessionId,
14285
+ detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail
14286
+ } : this.browserAgent?.sessions.anyNeedsHuman() ?? null;
14287
+ const boundTabId = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
14288
+ const connected = driverStatus?.ready === true;
14289
+ const endpoint = driverStatus?.endpoint ?? "playwright:unlaunched";
14290
+ const launched = endpoint === "playwright:msedge" ? "edge" : endpoint === "playwright:chrome" ? "chrome" : null;
14291
+ return {
14292
+ enabled: settings.enabled,
14293
+ browser: settings.browser,
14294
+ launchedBrowser: launched,
14295
+ driver: "playwright",
14296
+ allowedOrigins: [...this.browserAgent?.approval.allowedOriginList() ?? []],
14297
+ // Wire field kept as `bridge` for client compatibility; values come from Playwright.
14298
+ bridge: {
14299
+ listening: driverStatus?.listening === true,
14300
+ port: 0,
14301
+ extensionConnected: connected,
14302
+ lastError: driverStatus?.lastError ?? (this.browserAgent === null ? "runtime unavailable" : null)
14303
+ },
14304
+ pending: pending === null ? null : {
14305
+ id: pending.id,
14306
+ sessionId: pending.sessionId,
14307
+ tool: pending.tool,
14308
+ summary: pending.summary,
14309
+ ...pending.url === void 0 ? {} : { url: pending.url },
14310
+ ...pending.origin === void 0 ? {} : { origin: pending.origin }
14311
+ },
14312
+ tabConflict: conflict,
14313
+ needsHuman,
14314
+ boundTabId,
14315
+ audit: [...this.browserAgent?.sessions.recentAudit(12) ?? []],
14316
+ profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir
14317
+ };
14318
+ }
11396
14319
  requireMcpHost() {
11397
14320
  if (this.mcpHost === null) {
11398
14321
  throw new RemoteError("agent-enhancer/failed", "MCP connectors host is unavailable", {
@@ -11872,6 +14795,87 @@ var AgentEnhancerService = class extends TypertRemoteService {
11872
14795
  this.assertOwner();
11873
14796
  return await showOsNotificationNow(request);
11874
14797
  }
14798
+ async browserAgentSnapshot() {
14799
+ this.assertOwner();
14800
+ return this.browserSnapshotNow();
14801
+ }
14802
+ async browserAgentResolve(request) {
14803
+ this.assertOwner();
14804
+ const ok = this.browserAgent?.approval.resolve(request.id, request.decision) ?? false;
14805
+ return { ok, snapshot: this.browserSnapshotNow() };
14806
+ }
14807
+ async browserAgentResolveTabConflict(request) {
14808
+ this.assertOwner();
14809
+ const result = await this.browserAgent?.resolveTabConflict(request.decision);
14810
+ return { ok: result?.ok === true, snapshot: this.browserSnapshotNow() };
14811
+ }
14812
+ async browserAgentAcknowledgeHuman(request) {
14813
+ this.assertOwner();
14814
+ const ok = this.browserAgent?.acknowledgeHuman(request.sessionId) === true;
14815
+ return { ok, snapshot: this.browserSnapshotNow() };
14816
+ }
14817
+ async browserAgentOpenUrl(request) {
14818
+ this.assertOwner();
14819
+ const result = await this.browserAgent?.openUrl({
14820
+ sessionId: request.sessionId,
14821
+ url: request.url
14822
+ });
14823
+ return {
14824
+ ok: result?.ok === true,
14825
+ ...result?.url === void 0 ? {} : { url: result.url },
14826
+ ...result?.title === void 0 ? {} : { title: result.title },
14827
+ ...result?.error === void 0 ? {} : { error: result.error },
14828
+ snapshot: this.browserSnapshotNow()
14829
+ };
14830
+ }
14831
+ async browserAgentQuotePage(request) {
14832
+ this.assertOwner();
14833
+ const result = await this.browserAgent?.quotePage(request.sessionId);
14834
+ return {
14835
+ ok: result?.ok === true,
14836
+ ...result?.text === void 0 ? {} : { text: result.text },
14837
+ ...result?.url === void 0 ? {} : { url: result.url },
14838
+ ...result?.title === void 0 ? {} : { title: result.title },
14839
+ ...result?.error === void 0 ? {} : { error: result.error },
14840
+ snapshot: this.browserSnapshotNow()
14841
+ };
14842
+ }
14843
+ async browserAgentLaunchBrowser(request) {
14844
+ this.assertOwner();
14845
+ const settings = this.browserAgentSettings();
14846
+ if (!settings.enabled) {
14847
+ return {
14848
+ ok: false,
14849
+ profileDir: this.browserAgentProfileDir,
14850
+ error: "Browser agent is disabled in settings.",
14851
+ snapshot: this.browserSnapshotNow()
14852
+ };
14853
+ }
14854
+ const preference = request.browser ?? settings.browser;
14855
+ this.setBrowserAgentBrowser(preference);
14856
+ const launched = await this.browserAgent?.launchDedicated(void 0, preference);
14857
+ const snapshot = this.browserSnapshotNow();
14858
+ return {
14859
+ ok: launched?.ok === true,
14860
+ profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir,
14861
+ ...snapshot.launchedBrowser === null ? {} : { browser: snapshot.launchedBrowser },
14862
+ ...launched?.error === void 0 ? {} : { error: launched.error },
14863
+ snapshot
14864
+ };
14865
+ }
14866
+ async browserAgentSetBrowser(request) {
14867
+ this.assertOwner();
14868
+ this.setBrowserAgentBrowser(request.browser);
14869
+ const settings = this.browserAgentSettings();
14870
+ if (settings.enabled && this.browserAgent?.driverStatus()?.ready === true) {
14871
+ await this.browserAgent.alignToPreference();
14872
+ }
14873
+ return {
14874
+ ok: true,
14875
+ browser: request.browser,
14876
+ snapshot: this.browserSnapshotNow()
14877
+ };
14878
+ }
11875
14879
  async applyUpdate() {
11876
14880
  this.assertOwner();
11877
14881
  return applyPluginUpdateForHost({
@@ -11884,16 +14888,16 @@ var AgentEnhancerService = class extends TypertRemoteService {
11884
14888
  }
11885
14889
  };
11886
14890
  function resolveCheckpointRoot(dshHome2) {
11887
- const base = join30(dshHome2, "profiles", "desktop", "plugin-data");
11888
- const nextPkg = join30(base, PACKAGE_NAME);
11889
- const next = join30(nextPkg, "checkpoint");
11890
- const prev = join30(base, LEGACY_PACKAGE_NAME, "checkpoint");
11891
- if (!existsSync16(next) && existsSync16(prev)) {
11892
- mkdirSync9(nextPkg, { recursive: true });
14891
+ const base = join31(dshHome2, "profiles", "desktop", "plugin-data");
14892
+ const nextPkg = join31(base, PACKAGE_NAME);
14893
+ const next = join31(nextPkg, "checkpoint");
14894
+ const prev = join31(base, LEGACY_PACKAGE_NAME, "checkpoint");
14895
+ if (!existsSync17(next) && existsSync17(prev)) {
14896
+ mkdirSync10(nextPkg, { recursive: true });
11893
14897
  renameSync8(prev, next);
11894
- const prevPkg = join30(base, LEGACY_PACKAGE_NAME);
14898
+ const prevPkg = join31(base, LEGACY_PACKAGE_NAME);
11895
14899
  try {
11896
- if (existsSync16(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
14900
+ if (existsSync17(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
11897
14901
  } catch {
11898
14902
  }
11899
14903
  }
@@ -11963,6 +14967,8 @@ function readSettings(config) {
11963
14967
  softPauseEnabled: config.softPauseEnabled.get(),
11964
14968
  runAlertsEnabled: config.runAlertsEnabled.get(),
11965
14969
  runAlertsLevel: resolveRunAlertsLevel(config.runAlertsLevel.get()),
14970
+ browserAgentEnabled: config.browserAgentEnabled.get(),
14971
+ browserAgentBrowser: resolveBrowserAgentBrowser(config.browserAgentBrowser.get()),
11966
14972
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
11967
14973
  mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
11968
14974
  optimizeProvider: config.optimizeProvider.get(),
@@ -11993,9 +14999,9 @@ function apply(ctx, config) {
11993
14999
  const settings = () => readSettings(config);
11994
15000
  const models = new AuxiliaryModels(ctx, settings);
11995
15001
  installAutoSessionRoute(ctx, { settings });
11996
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join30(homedir5(), ".dsh"));
11997
- const pluginDataPackageRoot = join30(storageRoot, "..");
11998
- const usage = new UsageLedger(join30(storageRoot, "..", "usage"), (message) => {
15002
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join31(homedir6(), ".dsh"));
15003
+ const pluginDataPackageRoot = join31(storageRoot, "..");
15004
+ const usage = new UsageLedger(join31(storageRoot, "..", "usage"), (message) => {
11999
15005
  ctx.logger.warn(message);
12000
15006
  });
12001
15007
  const balancesFacade = (() => {
@@ -12025,12 +15031,12 @@ function apply(ctx, config) {
12025
15031
  })();
12026
15032
  installUsageObserver(ctx, usage);
12027
15033
  const store = new CheckpointStore(storageRoot);
12028
- const cutStore = new SessionCutStore(join30(storageRoot, "cuts"));
15034
+ const cutStore = new SessionCutStore(join31(storageRoot, "cuts"));
12029
15035
  const cutCache = /* @__PURE__ */ new Map();
12030
15036
  const sessionCleanup = new SessionCleanupRegistry();
12031
15037
  sessionCleanup.register(createCheckpointCleaner({ store, cutStore, storageRoot }));
12032
- sessionCleanup.register(createContextExcludeCleaner(join30(storageRoot, "..")));
12033
- const extraFoldersStore = createExtraFoldersStore(join30(storageRoot, "..", "extra-folders"));
15038
+ sessionCleanup.register(createContextExcludeCleaner(join31(storageRoot, "..")));
15039
+ const extraFoldersStore = createExtraFoldersStore(join31(storageRoot, "..", "extra-folders"));
12034
15040
  const softPauseGate = new SoftPauseGate();
12035
15041
  const mcpStore = createMcpConnectorsStore(mcpConnectorsRoot(pluginDataPackageRoot));
12036
15042
  const mcpRuntime = new McpConnectorRuntime(ctx, mcpStore);
@@ -12040,6 +15046,34 @@ function apply(ctx, config) {
12040
15046
  const detail = error instanceof Error ? error.message : String(error);
12041
15047
  ctx.logger.warn(`agent-enhancer: initial MCP connector sync failed: ${detail}`);
12042
15048
  });
15049
+ const browserAgentProfileDir = defaultBrowserAgentProfileDir(pluginDataPackageRoot);
15050
+ const browserAgentLive = {
15051
+ enabled: settings().browserAgentEnabled,
15052
+ browser: settings().browserAgentBrowser
15053
+ };
15054
+ const browserAgent = installBrowserAgent(ctx, {
15055
+ enabled: () => browserAgentLive.enabled,
15056
+ browserPreference: () => browserAgentLive.browser,
15057
+ profileRoot: pluginDataPackageRoot,
15058
+ softPause: softPauseGate,
15059
+ softPauseEnabled: () => settings().softPauseEnabled,
15060
+ onBrowserMutation: (info) => {
15061
+ try {
15062
+ ctx.emit("agent-enhancer/browser-agent/mutation", info);
15063
+ } catch {
15064
+ }
15065
+ }
15066
+ });
15067
+ sessionCleanup.register({
15068
+ id: "browser-agent",
15069
+ label: "Browser agent session memory",
15070
+ async purge(sessionId) {
15071
+ browserAgent.approval.clearSession(sessionId);
15072
+ browserAgent.human.clearSession(sessionId);
15073
+ browserAgent.sessions.clearSession(sessionId);
15074
+ softPauseGate.release(sessionId);
15075
+ }
15076
+ });
12043
15077
  new AgentEnhancerService(
12044
15078
  ctx,
12045
15079
  models,
@@ -12062,21 +15096,44 @@ function apply(ctx, config) {
12062
15096
  softPauseGate,
12063
15097
  () => settings().softPauseEnabled,
12064
15098
  pluginDataPackageRoot,
12065
- mcpHost
15099
+ mcpHost,
15100
+ browserAgent,
15101
+ () => ({
15102
+ enabled: browserAgentLive.enabled,
15103
+ browser: browserAgentLive.browser
15104
+ }),
15105
+ (browser) => {
15106
+ browserAgentLive.browser = resolveBrowserAgentBrowser(browser);
15107
+ },
15108
+ browserAgentProfileDir
12066
15109
  );
12067
15110
  ctx.effect(() => {
12068
15111
  const unsubscribe = ctx.on("internal/update", (resolvedConfig, next) => {
12069
- const enabled = resolvedConfig.mcpConnectorsEnabled.get();
15112
+ const cfg = resolvedConfig;
15113
+ const enabled = cfg.mcpConnectorsEnabled.get();
12070
15114
  mcpRuntime.setFeatureEnabled(enabled);
12071
15115
  void mcpRuntime.sync().catch((error) => {
12072
15116
  const detail = error instanceof Error ? error.message : String(error);
12073
15117
  ctx.logger.warn(`agent-enhancer: MCP connector sync after settings update failed: ${detail}`);
12074
15118
  });
15119
+ const prevEnabled = browserAgentLive.enabled;
15120
+ const prevBrowser = browserAgentLive.browser;
15121
+ browserAgentLive.enabled = cfg.browserAgentEnabled.get();
15122
+ browserAgentLive.browser = resolveBrowserAgentBrowser(cfg.browserAgentBrowser.get());
15123
+ if (prevEnabled !== browserAgentLive.enabled) {
15124
+ browserAgent.refresh();
15125
+ } else if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
15126
+ void browserAgent.alignToPreference().catch((error) => {
15127
+ const detail = error instanceof Error ? error.message : String(error);
15128
+ ctx.logger.warn(`agent-enhancer: browser preference align after settings failed: ${detail}`);
15129
+ });
15130
+ }
12075
15131
  return next();
12076
15132
  });
12077
15133
  return async () => {
12078
15134
  unsubscribe();
12079
15135
  await mcpRuntime.disposeAll();
15136
+ await browserAgent.dispose();
12080
15137
  };
12081
15138
  });
12082
15139
  installSoftPause(ctx, {