dsh-agent-enhancer 0.3.7 → 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 (93) hide show
  1. package/README.en.md +9 -5
  2. package/README.md +9 -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 +3 -2
  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 +105 -1
  21. package/lib/client/locales.d.ts.map +1 -1
  22. package/lib/client/remote.d.ts +31 -1
  23. package/lib/client/remote.d.ts.map +1 -1
  24. package/lib/client/run-alerts/copy.d.ts +4 -0
  25. package/lib/client/run-alerts/copy.d.ts.map +1 -0
  26. package/lib/client/run-alerts/dedupe.d.ts +14 -0
  27. package/lib/client/run-alerts/dedupe.d.ts.map +1 -0
  28. package/lib/client/run-alerts/deliver.d.ts +16 -0
  29. package/lib/client/run-alerts/deliver.d.ts.map +1 -0
  30. package/lib/client/run-alerts/detect.d.ts +12 -0
  31. package/lib/client/run-alerts/detect.d.ts.map +1 -0
  32. package/lib/client/run-alerts/gate.d.ts +25 -0
  33. package/lib/client/run-alerts/gate.d.ts.map +1 -0
  34. package/lib/client/run-alerts/host.d.ts +31 -0
  35. package/lib/client/run-alerts/host.d.ts.map +1 -0
  36. package/lib/client/run-alerts/pending-kind.d.ts +4 -0
  37. package/lib/client/run-alerts/pending-kind.d.ts.map +1 -0
  38. package/lib/client/run-alerts/types.d.ts +21 -0
  39. package/lib/client/run-alerts/types.d.ts.map +1 -0
  40. package/lib/client.js +4981 -3484
  41. package/lib/client.js.map +1 -1
  42. package/lib/config.d.ts +12 -1
  43. package/lib/config.d.ts.map +1 -1
  44. package/lib/host/browser-agent/approval.d.ts +38 -0
  45. package/lib/host/browser-agent/approval.d.ts.map +1 -0
  46. package/lib/host/browser-agent/auto-nav.d.ts +16 -0
  47. package/lib/host/browser-agent/auto-nav.d.ts.map +1 -0
  48. package/lib/host/browser-agent/auto-nav.test.d.ts +2 -0
  49. package/lib/host/browser-agent/auto-nav.test.d.ts.map +1 -0
  50. package/lib/host/browser-agent/driver.d.ts +76 -0
  51. package/lib/host/browser-agent/driver.d.ts.map +1 -0
  52. package/lib/host/browser-agent/extract.test.d.ts +2 -0
  53. package/lib/host/browser-agent/extract.test.d.ts.map +1 -0
  54. package/lib/host/browser-agent/human-gate.d.ts +36 -0
  55. package/lib/host/browser-agent/human-gate.d.ts.map +1 -0
  56. package/lib/host/browser-agent/human-gate.test.d.ts +2 -0
  57. package/lib/host/browser-agent/human-gate.test.d.ts.map +1 -0
  58. package/lib/host/browser-agent/install.d.ts +71 -0
  59. package/lib/host/browser-agent/install.d.ts.map +1 -0
  60. package/lib/host/browser-agent/launch.d.ts +38 -0
  61. package/lib/host/browser-agent/launch.d.ts.map +1 -0
  62. package/lib/host/browser-agent/page-links.d.ts +12 -0
  63. package/lib/host/browser-agent/page-links.d.ts.map +1 -0
  64. package/lib/host/browser-agent/page-links.test.d.ts +2 -0
  65. package/lib/host/browser-agent/page-links.test.d.ts.map +1 -0
  66. package/lib/host/browser-agent/path-key.test.d.ts +2 -0
  67. package/lib/host/browser-agent/path-key.test.d.ts.map +1 -0
  68. package/lib/host/browser-agent/pick-auto-nav.test.d.ts +2 -0
  69. package/lib/host/browser-agent/pick-auto-nav.test.d.ts.map +1 -0
  70. package/lib/host/browser-agent/playwright-driver.d.ts +81 -0
  71. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -0
  72. package/lib/host/browser-agent/playwright-snapshot.d.ts +50 -0
  73. package/lib/host/browser-agent/playwright-snapshot.d.ts.map +1 -0
  74. package/lib/host/browser-agent/prompt.d.ts +7 -0
  75. package/lib/host/browser-agent/prompt.d.ts.map +1 -0
  76. package/lib/host/browser-agent/protocol.d.ts +139 -0
  77. package/lib/host/browser-agent/protocol.d.ts.map +1 -0
  78. package/lib/host/browser-agent/proximity.d.ts +27 -0
  79. package/lib/host/browser-agent/proximity.d.ts.map +1 -0
  80. package/lib/host/browser-agent/session-state.d.ts +60 -0
  81. package/lib/host/browser-agent/session-state.d.ts.map +1 -0
  82. package/lib/host/browser-agent/tools.d.ts +29 -0
  83. package/lib/host/browser-agent/tools.d.ts.map +1 -0
  84. package/lib/host/index.d.ts +36 -2
  85. package/lib/host/index.d.ts.map +1 -1
  86. package/lib/host/rpc.d.ts +565 -0
  87. package/lib/host/rpc.d.ts.map +1 -1
  88. package/lib/host/run-alerts/notify.d.ts +39 -0
  89. package/lib/host/run-alerts/notify.d.ts.map +1 -0
  90. package/lib/identity.d.ts +1 -1
  91. package/lib/index.js +3514 -303
  92. package/lib/index.js.map +4 -4
  93. 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
 
@@ -10,6 +10,26 @@ var AUTO_PROVIDER = "agent-enhancer";
10
10
  var AUTO_MODEL = "auto";
11
11
 
12
12
  // src/config.ts
13
+ function resolveRunAlertsLevel(value) {
14
+ switch (value) {
15
+ case "hidden":
16
+ case "unfocused":
17
+ case "always":
18
+ return value;
19
+ default:
20
+ return "unfocused";
21
+ }
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
+ }
13
33
  var DEFAULT_AUXILIARY_MODEL = {
14
34
  provider: "",
15
35
  model: "",
@@ -26,6 +46,10 @@ var DEFAULT_SETTINGS = {
26
46
  sessionDeleteEnabled: true,
27
47
  fileEditEnabled: true,
28
48
  softPauseEnabled: true,
49
+ runAlertsEnabled: true,
50
+ runAlertsLevel: "unfocused",
51
+ browserAgentEnabled: false,
52
+ browserAgentBrowser: "auto",
29
53
  instructionsSkillsEnabled: true,
30
54
  mcpConnectorsEnabled: true,
31
55
  optimizeProvider: "",
@@ -66,6 +90,10 @@ function resolveSettings(value) {
66
90
  sessionDeleteEnabled: value?.sessionDeleteEnabled ?? true,
67
91
  fileEditEnabled: value?.fileEditEnabled ?? true,
68
92
  softPauseEnabled: value?.softPauseEnabled ?? true,
93
+ runAlertsEnabled: value?.runAlertsEnabled ?? true,
94
+ runAlertsLevel: resolveRunAlertsLevel(value?.runAlertsLevel),
95
+ browserAgentEnabled: value?.browserAgentEnabled ?? false,
96
+ browserAgentBrowser: resolveBrowserAgentBrowser(value?.browserAgentBrowser),
69
97
  instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
70
98
  mcpConnectorsEnabled: value?.mcpConnectorsEnabled ?? true,
71
99
  optimizeProvider: text(value?.optimizeProvider),
@@ -119,35 +147,2621 @@ function autoRouteMapOf(settings) {
119
147
  }
120
148
  };
121
149
  }
122
- function auxiliaryModelOf(settings, feature) {
123
- switch (feature) {
124
- case "optimize":
125
- return {
126
- provider: settings.optimizeProvider,
127
- model: settings.optimizeModel,
128
- reasoningEffort: settings.optimizeReasoningEffort
129
- };
130
- case "predict":
131
- return {
132
- provider: settings.predictProvider,
133
- model: settings.predictModel,
134
- reasoningEffort: settings.predictReasoningEffort
135
- };
136
- case "compact":
137
- return {
138
- provider: settings.compactProvider,
139
- model: settings.compactModel,
140
- reasoningEffort: settings.compactReasoningEffort
141
- };
142
- default: {
143
- const _exhaustive = feature;
144
- return _exhaustive;
145
- }
146
- }
147
- }
148
- function isFollowSessionModel(selection) {
149
- return selection.provider === "" || selection.model === "";
150
- }
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();
2629
+ return {
2630
+ approval,
2631
+ human,
2632
+ sessions,
2633
+ driverStatus() {
2634
+ return activeDriver?.status() ?? null;
2635
+ },
2636
+ activeProfileDir() {
2637
+ if (mountedPreference !== null) {
2638
+ return browserAgentProfileDirFor(options.profileRoot, mountedPreference);
2639
+ }
2640
+ return currentProfileDir();
2641
+ },
2642
+ async launchDedicated(startUrl, preferenceOverride) {
2643
+ return alignToPreference(startUrl, preferenceOverride);
2644
+ },
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();
2762
+ }
2763
+ };
2764
+ }
151
2765
 
152
2766
  // src/errors.ts
153
2767
  var MESSAGES = {
@@ -181,7 +2795,7 @@ var AuxiliaryError = class extends Error {
181
2795
  // src/identity.ts
182
2796
  var PACKAGE_NAME = "dsh-agent-enhancer";
183
2797
  var PLUGIN_ID = "agent-enhancer";
184
- var PACKAGE_VERSION = "0.3.7";
2798
+ var PACKAGE_VERSION = "0.3.9";
185
2799
  var LEGACY_PACKAGE_NAME = "dsh-composer-enhancer";
186
2800
  var ROLLBACK_PREFIX = `${PACKAGE_NAME}:rollback:`;
187
2801
  var UNDO_PREFIX = `${PACKAGE_NAME}:undo:`;
@@ -327,7 +2941,7 @@ var DshCheckpointSessions = class {
327
2941
  };
328
2942
 
329
2943
  // src/host/checkpoint/live.ts
330
- 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";
331
2945
 
332
2946
  // src/host/checkpoint/activity.ts
333
2947
  function surfaceMessageId(event) {
@@ -586,7 +3200,7 @@ function synthesizeCheckpoint(options) {
586
3200
  // src/host/checkpoint/files.ts
587
3201
  import { createHash, randomUUID as randomUUID2 } from "node:crypto";
588
3202
  import { chmod, lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
589
- import { basename, isAbsolute, join, resolve, sep, win32 } from "node:path";
3203
+ import { basename, isAbsolute, join as join2, resolve, sep, win32 } from "node:path";
590
3204
  import { TextDecoder } from "node:util";
591
3205
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
592
3206
  var ABSENT_FILE_HASH = "";
@@ -647,7 +3261,7 @@ function segments(path) {
647
3261
  function canonicalSegment(segment) {
648
3262
  return segment.replace(/[. ]+$/g, "").toLowerCase();
649
3263
  }
650
- function pathKey(path) {
3264
+ function pathKey2(path) {
651
3265
  return process.platform === "win32" ? segments(path).map(canonicalSegment).join("/") : path;
652
3266
  }
653
3267
  function unsafePath(path) {
@@ -668,8 +3282,8 @@ async function removeIfPresent(path) {
668
3282
  }
669
3283
  }
670
3284
  async function writeAtomic(path, text3) {
671
- await mkdir(join(path, ".."), { recursive: true });
672
- 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`);
673
3287
  try {
674
3288
  await writeFile(temporary, text3, { encoding: "utf8", flag: "wx" });
675
3289
  await rename(temporary, path);
@@ -678,8 +3292,8 @@ async function writeAtomic(path, text3) {
678
3292
  }
679
3293
  }
680
3294
  async function writeJournalAtomic(path, value) {
681
- await mkdir(join(path, ".."), { recursive: true, mode: 448 });
682
- 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`);
683
3297
  try {
684
3298
  await writeFile(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
685
3299
  await rename(temporary, path);
@@ -693,7 +3307,7 @@ async function readSnapshot(workspaceRoot, path) {
693
3307
  let current = resolve(workspaceRoot);
694
3308
  const target = absolutePath(workspaceRoot, path);
695
3309
  for (const segment of segments(path)) {
696
- current = join(current, segment);
3310
+ current = join2(current, segment);
697
3311
  let stats;
698
3312
  try {
699
3313
  stats = await lstat(current);
@@ -794,7 +3408,7 @@ var DurableRestoreJournal = class {
794
3408
  };
795
3409
  }
796
3410
  sidecarPath() {
797
- return join(this.options.storageRoot, "file-journals", `${digest(this.id)}.json`);
3411
+ return join2(this.options.storageRoot, "file-journals", `${digest(this.id)}.json`);
798
3412
  }
799
3413
  async writeSidecar() {
800
3414
  const value = {
@@ -917,7 +3531,7 @@ var CheckpointFiles = class {
917
3531
  }
918
3532
  }
919
3533
  async loadJournal(metadata) {
920
- 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`);
921
3535
  const stored = JSON.parse(await readFile(path, "utf8"));
922
3536
  if (!isRecord(stored) || stored.schemaVersion !== CHECKPOINT_SCHEMA_VERSION || stored.id !== metadata.id || !Array.isArray(stored.snapshots) || !Array.isArray(stored.completed)) {
923
3537
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
@@ -925,7 +3539,7 @@ var CheckpointFiles = class {
925
3539
  const snapshots = [];
926
3540
  const seen = /* @__PURE__ */ new Set();
927
3541
  for (const value of stored.snapshots) {
928
- 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)) {
929
3543
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
930
3544
  }
931
3545
  if (value.text !== null && (Buffer.byteLength(value.text, "utf8") > MAX_FILE_BYTES || value.text.includes("\0"))) throw new CheckpointFileError("FILE_RESTORE_FAILED");
@@ -940,7 +3554,7 @@ var CheckpointFiles = class {
940
3554
  if (currentHash !== snapshot.afterHash && currentHash !== snapshot.beforeHash) {
941
3555
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
942
3556
  }
943
- seen.add(pathKey(value.path));
3557
+ seen.add(pathKey2(value.path));
944
3558
  snapshots.push(snapshot);
945
3559
  }
946
3560
  const completed = [];
@@ -966,10 +3580,10 @@ var CheckpointFiles = class {
966
3580
  for (const file of files) {
967
3581
  const target = absolutePath(this.options.workspaceRoot, file.path);
968
3582
  let conflict = null;
969
- 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}`)) {
970
3584
  conflict = { path: file.path, reason: "unsafe-path" };
971
3585
  }
972
- seen.add(pathKey(file.path));
3586
+ seen.add(pathKey2(file.path));
973
3587
  if (conflict === null) conflict = this.validateBeforeImage(file) ?? this.validateAfterImage(file);
974
3588
  let snapshot = null;
975
3589
  if (conflict === null) {
@@ -1011,7 +3625,7 @@ var CheckpointFiles = class {
1011
3625
 
1012
3626
  // src/host/checkpoint/workspace-snapshot.ts
1013
3627
  import { readdir } from "node:fs/promises";
1014
- import { join as join2 } from "node:path";
3628
+ import { join as join3 } from "node:path";
1015
3629
  var MAX_WORKSPACE_SCAN_FILES = 2e3;
1016
3630
  var MAX_SHELL_CHANGED_FILES = 200;
1017
3631
  async function scanWorkspace(workspaceRoot, options = {}) {
@@ -1031,7 +3645,7 @@ async function scanWorkspace(workspaceRoot, options = {}) {
1031
3645
  if (truncated) return;
1032
3646
  if (isExcludedSegment(entry.name)) continue;
1033
3647
  const relativePath = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
1034
- const absolutePath2 = join2(absoluteDir, entry.name);
3648
+ const absolutePath2 = join3(absoluteDir, entry.name);
1035
3649
  if (entry.isSymbolicLink()) continue;
1036
3650
  if (entry.isDirectory()) {
1037
3651
  await visit(absolutePath2, relativePath.split("\\").join("/"));
@@ -1311,7 +3925,7 @@ var DshCheckpointCapture = class {
1311
3925
  return;
1312
3926
  }
1313
3927
  try {
1314
- const absolutePath2 = isAbsolute2(path) ? path : join3(workspaceRoot, path);
3928
+ const absolutePath2 = isAbsolute2(path) ? path : join4(workspaceRoot, path);
1315
3929
  await this.captureAbsolutePath(agent, absolutePath2);
1316
3930
  } catch {
1317
3931
  const turn = this.turnOf(agent);
@@ -1516,7 +4130,7 @@ function chainTrackedFiles(checkpoints, fromTurnOrRange, untilTurnExclusive) {
1516
4130
  // src/host/checkpoint/cut-store.ts
1517
4131
  import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
1518
4132
  import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
1519
- import { basename as basename2, join as join4 } from "node:path";
4133
+ import { basename as basename2, join as join5 } from "node:path";
1520
4134
  import { z } from "zod";
1521
4135
  var SCHEMA_VERSION = 1;
1522
4136
  var queues = /* @__PURE__ */ new Map();
@@ -1560,7 +4174,7 @@ async function removeIfPresent2(path) {
1560
4174
  }
1561
4175
  }
1562
4176
  async function writeAtomic2(path, value) {
1563
- const temporary = join4(join4(path, ".."), `.${basename2(path)}.${randomUUID3()}.tmp`);
4177
+ const temporary = join5(join5(path, ".."), `.${basename2(path)}.${randomUUID3()}.tmp`);
1564
4178
  try {
1565
4179
  await writeFile2(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
1566
4180
  await rename2(temporary, path);
@@ -1575,8 +4189,8 @@ function isWithdrawnByCut(cut, seq) {
1575
4189
  var SessionCutStore = class {
1576
4190
  constructor(root) {
1577
4191
  this.root = root;
1578
- this.directory = join4(root, "sessions");
1579
- this.rootKey = join4(root, ".");
4192
+ this.directory = join5(root, "sessions");
4193
+ this.rootKey = join5(root, ".");
1580
4194
  }
1581
4195
  root;
1582
4196
  directory;
@@ -1612,7 +4226,7 @@ var SessionCutStore = class {
1612
4226
  });
1613
4227
  }
1614
4228
  pathOf(sessionId) {
1615
- return join4(this.directory, `${digest2(sessionId)}.json`);
4229
+ return join5(this.directory, `${digest2(sessionId)}.json`);
1616
4230
  }
1617
4231
  };
1618
4232
 
@@ -2483,7 +5097,7 @@ var CheckpointRollbackService = class {
2483
5097
  // src/host/checkpoint/store.ts
2484
5098
  import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";
2485
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";
2486
- import { basename as basename3, join as join5 } from "node:path";
5100
+ import { basename as basename3, join as join6 } from "node:path";
2487
5101
  import { z as z2 } from "zod";
2488
5102
  var MAX_CHECKPOINTS = 20;
2489
5103
  var checkpointQueues = /* @__PURE__ */ new Map();
@@ -2603,7 +5217,7 @@ async function removeIfPresent3(path) {
2603
5217
  }
2604
5218
  }
2605
5219
  async function writeAtomic3(path, value) {
2606
- const temporary = join5(join5(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
5220
+ const temporary = join6(join6(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
2607
5221
  try {
2608
5222
  await writeFile3(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
2609
5223
  await rename3(temporary, path);
@@ -2615,9 +5229,9 @@ async function writeAtomic3(path, value) {
2615
5229
  var CheckpointStore = class {
2616
5230
  constructor(root) {
2617
5231
  this.root = root;
2618
- this.checkpointDirectory = join5(root, "checkpoints");
2619
- this.journalDirectory = join5(root, "journals");
2620
- this.rootKey = join5(root, ".");
5232
+ this.checkpointDirectory = join6(root, "checkpoints");
5233
+ this.journalDirectory = join6(root, "journals");
5234
+ this.rootKey = join6(root, ".");
2621
5235
  }
2622
5236
  root;
2623
5237
  checkpointDirectory;
@@ -2693,7 +5307,7 @@ var CheckpointStore = class {
2693
5307
  let removed = 0;
2694
5308
  for (const name2 of names) {
2695
5309
  if (!name2.endsWith(".json")) continue;
2696
- const path = join5(this.journalDirectory, name2);
5310
+ const path = join6(this.journalDirectory, name2);
2697
5311
  const stored = await this.readJson(path);
2698
5312
  assertCheckpointSchema(stored);
2699
5313
  const parsed = journalSchema.safeParse(stored);
@@ -2718,13 +5332,13 @@ var CheckpointStore = class {
2718
5332
  if (!parsed.success) throw new CheckpointStoreError("INVALID_JOURNAL");
2719
5333
  await serialize3(journalQueues, this.rootKey, async () => {
2720
5334
  await this.ensureDirectories();
2721
- await writeAtomic3(join5(this.journalDirectory, `${digest3(journal.id)}.json`), parsed.data);
5335
+ await writeAtomic3(join6(this.journalDirectory, `${digest3(journal.id)}.json`), parsed.data);
2722
5336
  });
2723
5337
  }
2724
5338
  async completeJournal(id) {
2725
5339
  await serialize3(journalQueues, this.rootKey, async () => {
2726
5340
  await this.ensureDirectories();
2727
- await removeIfPresent3(join5(this.journalDirectory, `${digest3(id)}.json`));
5341
+ await removeIfPresent3(join6(this.journalDirectory, `${digest3(id)}.json`));
2728
5342
  });
2729
5343
  }
2730
5344
  async listPendingJournals() {
@@ -2748,7 +5362,7 @@ var CheckpointStore = class {
2748
5362
  const journals = [];
2749
5363
  for (const name2 of names.sort()) {
2750
5364
  if (!name2.endsWith(".json")) continue;
2751
- const stored = await this.readJson(join5(this.journalDirectory, name2));
5365
+ const stored = await this.readJson(join6(this.journalDirectory, name2));
2752
5366
  assertCheckpointSchema(stored);
2753
5367
  const parsed = journalSchema.safeParse(stored);
2754
5368
  if (!parsed.success) throw new CheckpointStoreError("INVALID_STORE");
@@ -2760,7 +5374,7 @@ var CheckpointStore = class {
2760
5374
  return `${this.rootKey}\0${sessionId}`;
2761
5375
  }
2762
5376
  checkpointPath(sessionId) {
2763
- return join5(this.checkpointDirectory, `${digest3(sessionId)}.json`);
5377
+ return join6(this.checkpointDirectory, `${digest3(sessionId)}.json`);
2764
5378
  }
2765
5379
  async ensureDirectories() {
2766
5380
  await mkdir3(this.root, { recursive: true, mode: 448 });
@@ -2769,7 +5383,7 @@ var CheckpointStore = class {
2769
5383
  }
2770
5384
  async cleanTemporaryFiles(directory, prefix = "") {
2771
5385
  for (const name2 of await readdir2(directory)) {
2772
- 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));
2773
5387
  }
2774
5388
  }
2775
5389
  async readJson(path) {
@@ -3325,9 +5939,9 @@ var SessionCleanupRegistry = class {
3325
5939
 
3326
5940
  // src/host/session-delete/plugin-purge.ts
3327
5941
  import { createHash as createHash4 } from "node:crypto";
3328
- import { existsSync } from "node:fs";
5942
+ import { existsSync as existsSync2 } from "node:fs";
3329
5943
  import { readdir as readdir3, readFile as readFile4, rm, unlink as unlink4 } from "node:fs/promises";
3330
- import { join as join6 } from "node:path";
5944
+ import { join as join7 } from "node:path";
3331
5945
  function digest4(value) {
3332
5946
  return createHash4("sha256").update(value).digest("hex");
3333
5947
  }
@@ -3335,7 +5949,7 @@ function shortDigest(value, length = 16) {
3335
5949
  return digest4(value).slice(0, length);
3336
5950
  }
3337
5951
  async function removeIfPresent4(path) {
3338
- if (!existsSync(path)) return false;
5952
+ if (!existsSync2(path)) return false;
3339
5953
  await rm(path, { recursive: true, force: true });
3340
5954
  return true;
3341
5955
  }
@@ -3360,15 +5974,15 @@ function createCheckpointCleaner(options) {
3360
5974
  signal.throwIfAborted();
3361
5975
  await options.cutStore.set(sessionId, null);
3362
5976
  const key = shortDigest(sessionId);
3363
- await removeIfPresent4(join6(options.storageRoot, "shadow", key));
3364
- await removeIfPresent4(join6(options.storageRoot, "shadow-git", key));
3365
- 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");
3366
5980
  try {
3367
5981
  const names = await readdir3(journalDir);
3368
5982
  for (const name2 of names) {
3369
5983
  signal.throwIfAborted();
3370
5984
  if (!name2.endsWith(".json")) continue;
3371
- const path = join6(journalDir, name2);
5985
+ const path = join7(journalDir, name2);
3372
5986
  try {
3373
5987
  const raw = JSON.parse(await readFile4(path, "utf8"));
3374
5988
  if (raw.sessionId === sessionId) await unlinkIfPresent(path);
@@ -3389,9 +6003,9 @@ function createContextExcludeCleaner(pluginDataRoot) {
3389
6003
  label: "Context exclude rules",
3390
6004
  async purge(sessionId, signal) {
3391
6005
  signal.throwIfAborted();
3392
- const dir = join6(pluginDataRoot, "context-exclude", "sessions");
3393
- const hashed = join6(dir, `${digest4(sessionId)}.json`);
3394
- 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`);
3395
6009
  await unlinkIfPresent(hashed);
3396
6010
  await unlinkIfPresent(raw);
3397
6011
  }
@@ -3400,10 +6014,10 @@ function createContextExcludeCleaner(pluginDataRoot) {
3400
6014
 
3401
6015
  // src/host/session-delete/delete.ts
3402
6016
  import { createHash as createHash5 } from "node:crypto";
3403
- import { existsSync as existsSync2 } from "node:fs";
6017
+ import { existsSync as existsSync3 } from "node:fs";
3404
6018
  import { appendFile, mkdir as mkdir4, readdir as readdir4, rm as rm2 } from "node:fs/promises";
3405
- import { homedir, tmpdir } from "node:os";
3406
- import { join as join7 } from "node:path";
6019
+ import { homedir as homedir2, tmpdir } from "node:os";
6020
+ import { join as join8 } from "node:path";
3407
6021
  var SESSION_ID_RE = /^session-[0-9a-fA-F-]{36}$/;
3408
6022
  var SPILL_ROOT_RE = /^dsh-spill-[A-Za-z0-9_-]{6}$/;
3409
6023
  var SessionDeleteError = class extends Error {
@@ -3415,13 +6029,13 @@ var SessionDeleteError = class extends Error {
3415
6029
  code;
3416
6030
  };
3417
6031
  function dshHome() {
3418
- return process.env.DSH_HOME ?? join7(homedir(), ".dsh");
6032
+ return process.env.DSH_HOME ?? join8(homedir2(), ".dsh");
3419
6033
  }
3420
6034
  function sessionsRoot() {
3421
- return join7(dshHome(), "sessions");
6035
+ return join8(dshHome(), "sessions");
3422
6036
  }
3423
6037
  function projcacheSessionsDir() {
3424
- return join7(dshHome(), "storages", "session_projcache", "sessions");
6038
+ return join8(dshHome(), "storages", "session_projcache", "sessions");
3425
6039
  }
3426
6040
  function spillBase() {
3427
6041
  return process.env.DSH_SESSION_DELETE_TMP ?? tmpdir();
@@ -3445,10 +6059,10 @@ async function noteFailure(ctx, message) {
3445
6059
  } catch {
3446
6060
  }
3447
6061
  try {
3448
- const dir = join7(dshHome(), "profiles", "desktop", "plugin-data", "dsh-agent-enhancer");
6062
+ const dir = join8(dshHome(), "profiles", "desktop", "plugin-data", "dsh-agent-enhancer");
3449
6063
  await mkdir4(dir, { recursive: true });
3450
6064
  await appendFile(
3451
- join7(dir, "session-delete-last-error.log"),
6065
+ join8(dir, "session-delete-last-error.log"),
3452
6066
  `${(/* @__PURE__ */ new Date()).toISOString()} ${message}
3453
6067
  `,
3454
6068
  "utf8"
@@ -3625,7 +6239,7 @@ async function forgetInRegistry(ctx, sessionId, options) {
3625
6239
  return removed;
3626
6240
  }
3627
6241
  async function removePathBestEffort(path) {
3628
- if (!existsSync2(path)) return false;
6242
+ if (!existsSync3(path)) return false;
3629
6243
  for (let attempt = 0; attempt < 3; attempt += 1) {
3630
6244
  try {
3631
6245
  await rm2(path, { recursive: true, force: true });
@@ -3640,10 +6254,10 @@ async function removePathBestEffort(path) {
3640
6254
  async function eraseSessionLog(sessionId) {
3641
6255
  const removed = [];
3642
6256
  const root = sessionsRoot();
3643
- if (!existsSync2(root)) return removed;
6257
+ if (!existsSync3(root)) return removed;
3644
6258
  for (const workspaceDir of await readdir4(root)) {
3645
- const target = join7(root, workspaceDir, sessionId);
3646
- if (!existsSync2(target)) continue;
6259
+ const target = join8(root, workspaceDir, sessionId);
6260
+ if (!existsSync3(target)) continue;
3647
6261
  const normalizedRoot = root.toLowerCase();
3648
6262
  if (!target.toLowerCase().startsWith(normalizedRoot)) continue;
3649
6263
  if (await removePathBestEffort(target)) removed.push(target);
@@ -3661,8 +6275,8 @@ async function eraseSpill(sessionId) {
3661
6275
  const name2 = spillSessionDirName(sessionId);
3662
6276
  for (const entry of entries) {
3663
6277
  if (!SPILL_ROOT_RE.test(entry)) continue;
3664
- const target = join7(spillBase(), entry, name2);
3665
- if (!existsSync2(target)) continue;
6278
+ const target = join8(spillBase(), entry, name2);
6279
+ if (!existsSync3(target)) continue;
3666
6280
  if (await removePathBestEffort(target)) removed.push(target);
3667
6281
  }
3668
6282
  return removed;
@@ -3687,10 +6301,10 @@ async function eraseProjcache(ctx, sessionId) {
3687
6301
  } catch {
3688
6302
  }
3689
6303
  for (const cacheFile of [
3690
- join7(projcacheSessionsDir(), `${sessionId}.json`),
3691
- join7(projcacheSessionsDir(), `${uuid}.json`)
6304
+ join8(projcacheSessionsDir(), `${sessionId}.json`),
6305
+ join8(projcacheSessionsDir(), `${uuid}.json`)
3692
6306
  ]) {
3693
- if (!existsSync2(cacheFile)) continue;
6307
+ if (!existsSync3(cacheFile)) continue;
3694
6308
  if (await removePathBestEffort(cacheFile)) removed.push(cacheFile);
3695
6309
  }
3696
6310
  return removed;
@@ -3762,7 +6376,7 @@ async function deleteSessionNow(options) {
3762
6376
 
3763
6377
  // src/host/extra-folders/io.ts
3764
6378
  import { promises as fsp } from "node:fs";
3765
- 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";
3766
6380
 
3767
6381
  // src/host/extra-folders/paths.ts
3768
6382
  import { createHash as createHash6 } from "node:crypto";
@@ -4198,7 +6812,7 @@ async function listExtraFolderEntriesNow(options) {
4198
6812
  throw new ExtraFoldersError("FILE_DENIED", "Root is not the workspace or an attached folder");
4199
6813
  }
4200
6814
  const relativePath = relativeUnderRoot(rootPath, options.request.relativePath);
4201
- const absoluteDir = relativePath === "" ? rootPath : join8(rootPath, relativePath);
6815
+ const absoluteDir = relativePath === "" ? rootPath : join9(rootPath, relativePath);
4202
6816
  assertInsideAllowedRoots(primaryCwd, extraPaths, absoluteDir);
4203
6817
  await assertDirectory(absoluteDir);
4204
6818
  let names;
@@ -4213,14 +6827,14 @@ async function listExtraFolderEntriesNow(options) {
4213
6827
  const entries = [];
4214
6828
  for (const name2 of names) {
4215
6829
  if (name2 === "." || name2 === "..") continue;
4216
- const absolutePath2 = join8(absoluteDir, name2);
6830
+ const absolutePath2 = join9(absoluteDir, name2);
4217
6831
  try {
4218
6832
  assertInsideAllowedRoots(primaryCwd, extraPaths, absolutePath2);
4219
6833
  const stat = await fsp.lstat(absolutePath2);
4220
6834
  if (stat.isSymbolicLink()) continue;
4221
6835
  const kind = stat.isDirectory() ? "directory" : stat.isFile() ? "file" : null;
4222
6836
  if (kind === null) continue;
4223
- const path = relativePath === "" ? name2 : join8(relativePath, name2);
6837
+ const path = relativePath === "" ? name2 : join9(relativePath, name2);
4224
6838
  entries.push({ name: name2, path: path.replace(/\\/g, "/"), absolutePath: absolutePath2, kind });
4225
6839
  } catch {
4226
6840
  }
@@ -4240,8 +6854,8 @@ function loadExtraRootPaths(store, primaryCwd) {
4240
6854
  }
4241
6855
 
4242
6856
  // src/host/extra-folders/store.ts
4243
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4244
- 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";
4245
6859
  function emptyDoc(primaryCwd) {
4246
6860
  return {
4247
6861
  version: EXTRA_FOLDERS_VERSION,
@@ -4273,8 +6887,8 @@ function parseDoc(raw, primaryCwd) {
4273
6887
  }
4274
6888
  }
4275
6889
  function createExtraFoldersStore(rootDir) {
4276
- mkdirSync(rootDir, { recursive: true });
4277
- const fileOf = (primaryCwd) => join9(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
6890
+ mkdirSync2(rootDir, { recursive: true });
6891
+ const fileOf = (primaryCwd) => join10(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
4278
6892
  return {
4279
6893
  rootDir,
4280
6894
  load(primaryCwd) {
@@ -4294,7 +6908,7 @@ function createExtraFoldersStore(rootDir) {
4294
6908
  roots: [...roots]
4295
6909
  };
4296
6910
  const file = fileOf(primaryCwd);
4297
- mkdirSync(dirname(file), { recursive: true });
6911
+ mkdirSync2(dirname(file), { recursive: true });
4298
6912
  const tmp = `${file}.${process.pid}.tmp`;
4299
6913
  writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}
4300
6914
  `, "utf8");
@@ -4482,9 +7096,9 @@ async function writeWorkspaceFileNow(options) {
4482
7096
  }
4483
7097
 
4484
7098
  // src/host/file-edit/monaco.ts
4485
- import { existsSync as existsSync3 } from "node:fs";
7099
+ import { existsSync as existsSync4 } from "node:fs";
4486
7100
  import { promises as fsp2 } from "node:fs";
4487
- 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";
4488
7102
  import { fileURLToPath } from "node:url";
4489
7103
 
4490
7104
  // src/shared/monaco-route.ts
@@ -4502,7 +7116,7 @@ function packageRootCandidates() {
4502
7116
  }
4503
7117
  function resolveMonacoVsDir() {
4504
7118
  for (const candidate of packageRootCandidates()) {
4505
- if (existsSync3(join10(candidate, "loader.js"))) return candidate;
7119
+ if (existsSync4(join11(candidate, "loader.js"))) return candidate;
4506
7120
  }
4507
7121
  return packageRootCandidates()[0];
4508
7122
  }
@@ -4558,7 +7172,7 @@ async function locateFile(vsDir, relativeUnderVs) {
4558
7172
  const parts = relativeUnderVs.split("/");
4559
7173
  let cursor = rootReal;
4560
7174
  for (const part of parts) {
4561
- cursor = join10(cursor, part);
7175
+ cursor = join11(cursor, part);
4562
7176
  if (!isInside(rootReal, cursor)) return null;
4563
7177
  }
4564
7178
  if (!isInside(rootReal, cursor)) return null;
@@ -4639,17 +7253,17 @@ function installMonacoRoute(ctx) {
4639
7253
  }
4640
7254
 
4641
7255
  // src/host/instructions-skills/io.ts
4642
- import { existsSync as existsSync13, readFileSync as readFileSync6, statSync as statSync4 } from "node:fs";
4643
- 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";
4644
7258
 
4645
7259
  // src/host/instructions-skills/create.ts
4646
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
4647
- 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";
4648
7262
 
4649
7263
  // src/host/instructions-skills/paths.ts
4650
- import { existsSync as existsSync4, statSync } from "node:fs";
4651
- import { basename as basename5, dirname as dirname3, join as join11, resolve as resolve6, sep as sep6 } from "node:path";
4652
- 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";
4653
7267
  var INSTRUCTION_CANDIDATES = [
4654
7268
  "AGENTS.md",
4655
7269
  "CLAUDE.md",
@@ -4660,18 +7274,18 @@ var PROJECT_ROOT_MARKERS = [".git"];
4660
7274
  function dshHomeOf(env = process.env) {
4661
7275
  const fromEnv = env.DSH_HOME;
4662
7276
  if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve6(fromEnv.trim());
4663
- return resolve6(homedir2(), ".dsh");
7277
+ return resolve6(homedir3(), ".dsh");
4664
7278
  }
4665
7279
  function agentsHomeOf(env = process.env) {
4666
7280
  const fromEnv = env.DSH_AGENTS_HOME;
4667
7281
  if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve6(fromEnv.trim());
4668
- return resolve6(homedir2(), ".agents");
7282
+ return resolve6(homedir3(), ".agents");
4669
7283
  }
4670
7284
  function findProjectRoot(cwd, markers = PROJECT_ROOT_MARKERS) {
4671
7285
  let current = resolve6(cwd);
4672
7286
  for (; ; ) {
4673
7287
  for (const marker of markers) {
4674
- if (existsSync4(join11(current, marker))) return current;
7288
+ if (existsSync5(join12(current, marker))) return current;
4675
7289
  }
4676
7290
  const parent = dirname3(current);
4677
7291
  if (parent === current) return resolve6(cwd);
@@ -4697,22 +7311,22 @@ function skillRootsFor(cwd, projectRoot, env = process.env) {
4697
7311
  const root = resolve6(projectRoot);
4698
7312
  const tip = resolve6(cwd);
4699
7313
  return [
4700
- join11(root, ".agents", "skills"),
4701
- join11(root, ".dsh", "skills"),
4702
- join11(tip, ".agents", "skills"),
4703
- join11(tip, ".dsh", "skills"),
4704
- join11(agentsHomeOf(env), "skills"),
4705
- 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")
4706
7320
  ].filter((path, index, all) => all.findIndex((other) => samePath2(other, path)) === index);
4707
7321
  }
4708
7322
  function previewSkillSearchRoots(cwd, projectRoot, env = process.env) {
4709
- const home = resolve6(homedir2());
7323
+ const home = resolve6(homedir3());
4710
7324
  return [
4711
7325
  ...skillRootsFor(cwd, projectRoot, env),
4712
- join11(home, ".cursor", "skills"),
4713
- join11(home, ".cursor", "skills-cursor"),
4714
- join11(home, ".codex", "skills"),
4715
- 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")
4716
7330
  ].filter((path, index, all) => all.findIndex((other) => samePath2(other, path)) === index);
4717
7331
  }
4718
7332
  function fileBytes(path) {
@@ -4768,10 +7382,10 @@ Instructions for the agent go here.
4768
7382
  }
4769
7383
  function createWorkspaceAgentsFile(projectRoot) {
4770
7384
  const path = resolve7(projectRoot, "AGENTS.md");
4771
- if (existsSync5(path)) {
7385
+ if (existsSync6(path)) {
4772
7386
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
4773
7387
  }
4774
- mkdirSync2(dirname4(path), { recursive: true });
7388
+ mkdirSync3(dirname4(path), { recursive: true });
4775
7389
  writeFileSync2(path, AGENTS_STUB, "utf8");
4776
7390
  return { path, created: true };
4777
7391
  }
@@ -4780,19 +7394,19 @@ function createWorkspaceSkill(projectRoot, rawName) {
4780
7394
  if (!isKebabCaseName(name2)) {
4781
7395
  throw new AuxiliaryError("FILE_DENIED", "Skill name must be kebab-case");
4782
7396
  }
4783
- const dir = join12(resolve7(projectRoot), ".agents", "skills", name2);
4784
- const path = join12(dir, "SKILL.md");
4785
- 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)) {
4786
7400
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
4787
7401
  }
4788
- mkdirSync2(dir, { recursive: true });
7402
+ mkdirSync3(dir, { recursive: true });
4789
7403
  writeFileSync2(path, skillStubMarkdown(name2), "utf8");
4790
7404
  return { path, created: true, name: name2 };
4791
7405
  }
4792
7406
 
4793
7407
  // src/host/instructions-skills/discover.ts
4794
- import { existsSync as existsSync9, readdirSync as readdirSync3, readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
4795
- 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";
4796
7410
 
4797
7411
  // src/host/instructions-skills/types.ts
4798
7412
  function defaultSkillInstallMeta() {
@@ -4805,9 +7419,9 @@ function defaultSkillInstallMeta() {
4805
7419
  }
4806
7420
 
4807
7421
  // src/host/instructions-skills/transient-paths.ts
4808
- 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";
4809
7423
  import { tmpdir as tmpdir2 } from "node:os";
4810
- 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";
4811
7425
  var TRANSIENT_MARK = /\.__ae_(?:removing|installing)_/;
4812
7426
  function isTransientSkillEntryName(name2) {
4813
7427
  const base = basename6(name2.trim());
@@ -4816,7 +7430,7 @@ function isTransientSkillEntryName(name2) {
4816
7430
  }
4817
7431
  function skillTransientWorkPath(kind, skillName) {
4818
7432
  const safe = skillName.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 80) || "skill";
4819
- return join13(tmpdir2(), `ae-skill-${kind}-${safe}-${process.pid}-${Date.now()}`);
7433
+ return join14(tmpdir2(), `ae-skill-${kind}-${safe}-${process.pid}-${Date.now()}`);
4820
7434
  }
4821
7435
  function sweepTransientSkillEntries(skillsRoot) {
4822
7436
  const root = resolve8(skillsRoot);
@@ -4828,7 +7442,7 @@ function sweepTransientSkillEntries(skillsRoot) {
4828
7442
  }
4829
7443
  for (const name2 of names) {
4830
7444
  if (!isTransientSkillEntryName(name2)) continue;
4831
- const full = join13(root, name2);
7445
+ const full = join14(root, name2);
4832
7446
  try {
4833
7447
  rmSync(full, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 });
4834
7448
  } catch {
@@ -4860,7 +7474,7 @@ function removeQuietly(path) {
4860
7474
  } catch {
4861
7475
  return;
4862
7476
  }
4863
- if (!existsSync6(path)) return;
7477
+ if (!existsSync7(path)) return;
4864
7478
  try {
4865
7479
  rmSync(path, { recursive: true, force: true, maxRetries: 2, retryDelay: 20 });
4866
7480
  } catch {
@@ -4869,17 +7483,17 @@ function removeQuietly(path) {
4869
7483
 
4870
7484
  // src/host/instructions-skills/uninstall.ts
4871
7485
  import { lstatSync as lstatSync3 } from "node:fs";
4872
- 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";
4873
7487
 
4874
7488
  // src/host/instructions-skills/install-ledger.ts
4875
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
4876
- 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";
4877
7491
  function ledgerPath(dataRoot) {
4878
- return join14(dataRoot, "skills-install", "registry.json");
7492
+ return join15(dataRoot, "skills-install", "registry.json");
4879
7493
  }
4880
7494
  function writeLedger(dataRoot, ledger) {
4881
7495
  const path = ledgerPath(dataRoot);
4882
- mkdirSync3(dirname5(path), { recursive: true });
7496
+ mkdirSync4(dirname5(path), { recursive: true });
4883
7497
  const tmp = `${path}.${process.pid}.tmp`;
4884
7498
  writeFileSync3(tmp, `${JSON.stringify(ledger, null, 2)}
4885
7499
  `, "utf8");
@@ -4887,7 +7501,7 @@ function writeLedger(dataRoot, ledger) {
4887
7501
  }
4888
7502
  function readInstallLedger(dataRoot) {
4889
7503
  const path = ledgerPath(dataRoot);
4890
- if (!existsSync7(path)) return {};
7504
+ if (!existsSync8(path)) return {};
4891
7505
  try {
4892
7506
  const raw = readFileSync2(path, "utf8").trim();
4893
7507
  if (raw === "") return {};
@@ -4908,18 +7522,18 @@ function removeInstallRecord(dataRoot, name2) {
4908
7522
  }
4909
7523
 
4910
7524
  // src/host/instructions-skills/remove-path.ts
4911
- import { execFileSync } from "node:child_process";
7525
+ import { execFileSync as execFileSync2 } from "node:child_process";
4912
7526
  import {
4913
7527
  chmodSync,
4914
- existsSync as existsSync8,
7528
+ existsSync as existsSync9,
4915
7529
  lstatSync as lstatSync2,
4916
7530
  readdirSync as readdirSync2,
4917
7531
  readlinkSync,
4918
7532
  rmSync as rmSync2,
4919
7533
  unlinkSync as unlinkSync2
4920
7534
  } from "node:fs";
4921
- import { homedir as homedir3 } from "node:os";
4922
- 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";
4923
7537
 
4924
7538
  // src/host/instructions-skills/fs-access.ts
4925
7539
  var ACCESS_DENIED_RE = /eperm|eacces|eio|ebusy|access is denied|operation not permitted|file in use|still present|拒绝访问|¾Ü¾ø·ÃÎÊ/i;
@@ -4950,8 +7564,8 @@ function pathPresent(path) {
4950
7564
  function isManagedSkillEntryPath(target, env = process.env) {
4951
7565
  const absolute = resolve9(target);
4952
7566
  const managedRoots = [
4953
- join15(agentsHomeOf(env), "skills"),
4954
- join15(dshHomeOf(env), "skills")
7567
+ join16(agentsHomeOf(env), "skills"),
7568
+ join16(dshHomeOf(env), "skills")
4955
7569
  ];
4956
7570
  for (const root of managedRoots) {
4957
7571
  if (samePath2(absolute, root) || isInsideOrSame(root, absolute)) return true;
@@ -4961,15 +7575,15 @@ function isManagedSkillEntryPath(target, env = process.env) {
4961
7575
  function isProtectedExternalSkillPath(target, env = process.env) {
4962
7576
  const absolute = resolve9(target);
4963
7577
  if (isManagedSkillEntryPath(absolute, env)) return false;
4964
- const home = resolve9(homedir3());
7578
+ const home = resolve9(homedir4());
4965
7579
  const protectedRoots = [
4966
- join15(home, ".skills-manager"),
4967
- join15(home, ".cursor", "skills"),
4968
- join15(home, ".cursor", "skills-cursor"),
4969
- join15(home, ".codex", "skills"),
4970
- join15(home, ".claude", "skills"),
4971
- join15(home, ".codebuddy", "skills"),
4972
- 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")
4973
7587
  ];
4974
7588
  for (const root of protectedRoots) {
4975
7589
  if (samePath2(absolute, root) || isInsideOrSame(root, absolute)) return true;
@@ -4993,12 +7607,12 @@ function isReparseOrSymlink(path) {
4993
7607
  }
4994
7608
  }
4995
7609
  function effectivelyGone(target) {
4996
- if (!pathPresent(target) && !existsSync8(target)) return true;
7610
+ if (!pathPresent(target) && !existsSync9(target)) return true;
4997
7611
  try {
4998
7612
  const stat = lstatSync2(target);
4999
7613
  if (stat.isSymbolicLink()) return false;
5000
7614
  if (!stat.isDirectory()) return false;
5001
- if (existsSync8(join15(target, "SKILL.md"))) return false;
7615
+ if (existsSync9(join16(target, "SKILL.md"))) return false;
5002
7616
  let names;
5003
7617
  try {
5004
7618
  names = readdirSync2(target);
@@ -5016,7 +7630,7 @@ function unlinkMountOnly(absolute) {
5016
7630
  } catch {
5017
7631
  if (process.platform === "win32") {
5018
7632
  try {
5019
- execFileSync("cmd", ["/d", "/s", "/c", `rmdir "${absolute.replace(/"/g, "")}"`], {
7633
+ execFileSync2("cmd", ["/d", "/s", "/c", `rmdir "${absolute.replace(/"/g, "")}"`], {
5020
7634
  windowsHide: true,
5021
7635
  timeout: 15e3,
5022
7636
  stdio: "ignore"
@@ -5028,7 +7642,7 @@ function unlinkMountOnly(absolute) {
5028
7642
  return false;
5029
7643
  }
5030
7644
  }
5031
- return !pathPresent(absolute) && !existsSync8(absolute);
7645
+ return !pathPresent(absolute) && !existsSync9(absolute);
5032
7646
  }
5033
7647
  function tryUnlinkReparseOrFile(absolute) {
5034
7648
  let preferUnlink = false;
@@ -5048,7 +7662,7 @@ function removePathRobust(target) {
5048
7662
  if (isProtectedExternalSkillPath(absolute)) {
5049
7663
  return;
5050
7664
  }
5051
- if (!pathPresent(absolute) && !existsSync8(absolute)) return;
7665
+ if (!pathPresent(absolute) && !existsSync9(absolute)) return;
5052
7666
  if (isReparseOrSymlink(absolute)) {
5053
7667
  if (unlinkMountOnly(absolute)) return;
5054
7668
  if (effectivelyGone(absolute)) return;
@@ -5066,7 +7680,7 @@ function removePathRobust(target) {
5066
7680
  } catch (error) {
5067
7681
  if (!isWindowsPathBusyError(error) && effectivelyGone(absolute)) return;
5068
7682
  }
5069
- if (!pathPresent(absolute) && !existsSync8(absolute)) return;
7683
+ if (!pathPresent(absolute) && !existsSync9(absolute)) return;
5070
7684
  try {
5071
7685
  const aside = renameAsideToTemp(absolute, "removing");
5072
7686
  removeQuietly(aside);
@@ -5078,7 +7692,7 @@ function removePathRobust(target) {
5078
7692
  if (unlinkMountOnly(absolute)) return;
5079
7693
  } else {
5080
7694
  try {
5081
- execFileSync("cmd", ["/d", "/s", "/c", `rmdir /s /q "${absolute.replace(/"/g, "")}"`], {
7695
+ execFileSync2("cmd", ["/d", "/s", "/c", `rmdir /s /q "${absolute.replace(/"/g, "")}"`], {
5082
7696
  windowsHide: true,
5083
7697
  timeout: 3e4,
5084
7698
  stdio: "ignore"
@@ -5086,10 +7700,10 @@ function removePathRobust(target) {
5086
7700
  } catch {
5087
7701
  }
5088
7702
  }
5089
- if (!pathPresent(absolute) && !existsSync8(absolute)) return;
7703
+ if (!pathPresent(absolute) && !existsSync9(absolute)) return;
5090
7704
  if (effectivelyGone(absolute)) return;
5091
7705
  }
5092
- if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync8(absolute)) return;
7706
+ if (effectivelyGone(absolute) || !pathPresent(absolute) && !existsSync9(absolute)) return;
5093
7707
  throw new AuxiliaryError("FILE_EDIT_FAILED", busyPathHint(basename7(absolute)));
5094
7708
  }
5095
7709
 
@@ -5112,8 +7726,8 @@ function pathPresent2(path) {
5112
7726
  function managedSkillEntriesForName(root, name2) {
5113
7727
  if (!isKebabCaseName(name2)) return [];
5114
7728
  const out = [];
5115
- const asDir = join16(root, name2);
5116
- const asFile = join16(root, `${name2}.md`);
7729
+ const asDir = join17(root, name2);
7730
+ const asFile = join17(root, `${name2}.md`);
5117
7731
  for (const entry of [asDir, asFile]) {
5118
7732
  if (!pathPresent2(entry)) continue;
5119
7733
  if (!samePath2(dirname6(entry), root)) continue;
@@ -5126,8 +7740,8 @@ function resolveManagedSkillRemovalTarget(path, name2, managedRoots) {
5126
7740
  if (!isKebabCaseName(name2)) return null;
5127
7741
  const entry = skillEntryPath(path);
5128
7742
  for (const root of managedRoots) {
5129
- const asDir = join16(root, name2);
5130
- const asFile = join16(root, `${name2}.md`);
7743
+ const asDir = join17(root, name2);
7744
+ const asFile = join17(root, `${name2}.md`);
5131
7745
  if (samePath2(entry, asDir) || samePath2(entry, asFile)) {
5132
7746
  if (!pathPresent2(entry)) return null;
5133
7747
  if (!samePath2(dirname6(entry), root)) return null;
@@ -5209,40 +7823,40 @@ function discoverInstructionFiles(options) {
5209
7823
  const projectRoot = findProjectRoot(cwd);
5210
7824
  const seen = /* @__PURE__ */ new Set();
5211
7825
  const instructions = [];
5212
- const globalPath = join17(dshHomeOf(env), "AGENTS.md");
7826
+ const globalPath = join18(dshHomeOf(env), "AGENTS.md");
5213
7827
  pushUnique(instructions, seen, {
5214
7828
  id: entryId("global", globalPath),
5215
7829
  scope: "global",
5216
7830
  name: "AGENTS.md",
5217
7831
  path: globalPath,
5218
- exists: existsSync9(globalPath),
7832
+ exists: existsSync10(globalPath),
5219
7833
  bytes: fileBytes(globalPath),
5220
7834
  createable: false
5221
7835
  });
5222
- const sharedPath = join17(agentsHomeOf(env), "AGENTS.md");
7836
+ const sharedPath = join18(agentsHomeOf(env), "AGENTS.md");
5223
7837
  pushUnique(instructions, seen, {
5224
7838
  id: entryId("shared", sharedPath),
5225
7839
  scope: "shared",
5226
7840
  name: "AGENTS.md",
5227
7841
  path: sharedPath,
5228
- exists: existsSync9(sharedPath),
7842
+ exists: existsSync10(sharedPath),
5229
7843
  bytes: fileBytes(sharedPath),
5230
7844
  createable: false
5231
7845
  });
5232
- const rootAgents = join17(projectRoot, "AGENTS.md");
7846
+ const rootAgents = join18(projectRoot, "AGENTS.md");
5233
7847
  pushUnique(instructions, seen, {
5234
7848
  id: entryId("project", rootAgents),
5235
7849
  scope: "project",
5236
7850
  name: "AGENTS.md",
5237
7851
  path: rootAgents,
5238
- exists: existsSync9(rootAgents),
7852
+ exists: existsSync10(rootAgents),
5239
7853
  bytes: fileBytes(rootAgents),
5240
- createable: !existsSync9(rootAgents)
7854
+ createable: !existsSync10(rootAgents)
5241
7855
  });
5242
7856
  for (const dir of projectChainDirs(projectRoot, cwd)) {
5243
7857
  for (const name2 of INSTRUCTION_CANDIDATES) {
5244
- const path = join17(dir, name2);
5245
- if (!existsSync9(path)) continue;
7858
+ const path = join18(dir, name2);
7859
+ if (!existsSync10(path)) continue;
5246
7860
  if (samePath2(path, rootAgents)) continue;
5247
7861
  pushUnique(instructions, seen, {
5248
7862
  id: entryId("project", path),
@@ -5286,8 +7900,8 @@ function discoverFilesystemSkills(options) {
5286
7900
  }
5287
7901
  for (const name2 of names) {
5288
7902
  if (isTransientSkillEntryName(name2)) continue;
5289
- const skillMd = join17(root, name2, "SKILL.md");
5290
- if (!existsSync9(skillMd)) continue;
7903
+ const skillMd = join18(root, name2, "SKILL.md");
7904
+ if (!existsSync10(skillMd)) continue;
5291
7905
  if (byName.has(name2)) continue;
5292
7906
  byName.set(name2, {
5293
7907
  id: `fs:${resolve11(skillMd).toLowerCase()}`,
@@ -5306,10 +7920,10 @@ function discoverFilesystemSkills(options) {
5306
7920
  return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
5307
7921
  }
5308
7922
  function dirnameLabel(root, projectRoot, env) {
5309
- if (samePath2(root, join17(projectRoot, ".agents", "skills"))) return "project";
5310
- if (samePath2(root, join17(projectRoot, ".dsh", "skills"))) return "project-dsh";
5311
- if (samePath2(root, join17(agentsHomeOf(env), "skills"))) return "shared";
5312
- 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";
5313
7927
  const parent = basename9(dirname7(root)).toLowerCase();
5314
7928
  const leaf = basename9(root).toLowerCase();
5315
7929
  if (parent === ".cursor" && leaf === "skills") return "cursor";
@@ -5347,23 +7961,23 @@ function normalizeRegistrySkills(raw) {
5347
7961
  function coerceSkillDocumentPath(path, _name) {
5348
7962
  if (path === null || path.trim() === "") return null;
5349
7963
  const absolute = resolve11(path.trim());
5350
- if (existsSync9(absolute)) {
7964
+ if (existsSync10(absolute)) {
5351
7965
  try {
5352
7966
  if (statSync2(absolute).isFile()) return absolute;
5353
7967
  } catch {
5354
7968
  }
5355
- const asFile = join17(absolute, "SKILL.md");
5356
- if (existsSync9(asFile)) return asFile;
7969
+ const asFile = join18(absolute, "SKILL.md");
7970
+ if (existsSync10(asFile)) return asFile;
5357
7971
  }
5358
7972
  const lower = absolute.toLowerCase();
5359
7973
  if (lower.endsWith("skill.md") || lower.endsWith(".md")) return absolute;
5360
- const nested = join17(absolute, "SKILL.md");
5361
- return existsSync9(nested) ? nested : absolute;
7974
+ const nested = join18(absolute, "SKILL.md");
7975
+ return existsSync10(nested) ? nested : absolute;
5362
7976
  }
5363
7977
  function resolveSkillPathFromRoots(name2, cwd, projectRoot, env) {
5364
7978
  for (const root of previewSkillSearchRoots(cwd, projectRoot, env)) {
5365
- const skillMd = join17(root, name2, "SKILL.md");
5366
- if (existsSync9(skillMd)) return resolve11(skillMd);
7979
+ const skillMd = join18(root, name2, "SKILL.md");
7980
+ if (existsSync10(skillMd)) return resolve11(skillMd);
5367
7981
  }
5368
7982
  return null;
5369
7983
  }
@@ -5524,22 +8138,22 @@ function parseGitSkillSource(raw) {
5524
8138
 
5525
8139
  // src/host/instructions-skills/install.ts
5526
8140
  import { execFile as execFile3, spawn } from "node:child_process";
5527
- 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";
5528
8142
  import { tmpdir as tmpdir3 } from "node:os";
5529
- 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";
5530
8144
  import { promisify as promisify3 } from "node:util";
5531
8145
 
5532
8146
  // src/host/instructions-skills/github-archive.ts
5533
8147
  import { execFile as execFile2 } from "node:child_process";
5534
8148
  import {
5535
8149
  createWriteStream,
5536
- mkdirSync as mkdirSync4,
8150
+ mkdirSync as mkdirSync5,
5537
8151
  readdirSync as readdirSync4,
5538
8152
  renameSync as renameSync4,
5539
8153
  rmSync as rmSync3,
5540
8154
  statSync as statSync3
5541
8155
  } from "node:fs";
5542
- import { join as join18 } from "node:path";
8156
+ import { join as join19 } from "node:path";
5543
8157
  import { Readable } from "node:stream";
5544
8158
  import { pipeline } from "node:stream/promises";
5545
8159
  import { promisify as promisify2 } from "node:util";
@@ -5584,7 +8198,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
5584
8198
  }
5585
8199
  async function extractZip(zipPath, destDir, signal) {
5586
8200
  signal.throwIfAborted();
5587
- mkdirSync4(destDir, { recursive: true });
8201
+ mkdirSync5(destDir, { recursive: true });
5588
8202
  try {
5589
8203
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
5590
8204
  windowsHide: true,
@@ -5603,7 +8217,7 @@ function unwrapArchiveRoot(extractDir) {
5603
8217
  return extractDir;
5604
8218
  }
5605
8219
  if (entries.length !== 1) return extractDir;
5606
- const only = join18(extractDir, entries[0]);
8220
+ const only = join19(extractDir, entries[0]);
5607
8221
  try {
5608
8222
  if (statSync3(only).isDirectory()) return only;
5609
8223
  } catch {
@@ -5642,10 +8256,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
5642
8256
  }
5643
8257
  async function fetchGithubRepoArchive(options) {
5644
8258
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
5645
- mkdirSync4(workDir, { recursive: true });
5646
- const zipPath = join18(workDir, "repo.zip");
5647
- const extractDir = join18(workDir, "extract");
5648
- 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 });
5649
8263
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
5650
8264
  const candidates = archiveCandidates(owner, repo, defaultBranch);
5651
8265
  const errors = [];
@@ -5656,7 +8270,7 @@ async function fetchGithubRepoArchive(options) {
5656
8270
  try {
5657
8271
  rmSync3(zipPath, { force: true });
5658
8272
  rmSync3(extractDir, { recursive: true, force: true });
5659
- mkdirSync4(extractDir, { recursive: true });
8273
+ mkdirSync5(extractDir, { recursive: true });
5660
8274
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
5661
8275
  if (!downloadStarted) {
5662
8276
  onStage?.("downloading", detail);
@@ -5668,7 +8282,7 @@ async function fetchGithubRepoArchive(options) {
5668
8282
  onStage?.("extracting", `${owner}/${repo}`);
5669
8283
  await extractZip(zipPath, extractDir, signal);
5670
8284
  const root = unwrapArchiveRoot(extractDir);
5671
- const repoDir = join18(workDir, "repo");
8285
+ const repoDir = join19(workDir, "repo");
5672
8286
  rmSync3(repoDir, { recursive: true, force: true });
5673
8287
  renameSync4(root, repoDir);
5674
8288
  try {
@@ -5698,15 +8312,15 @@ async function fetchGithubRepoArchive(options) {
5698
8312
  // src/host/instructions-skills/install-fs.ts
5699
8313
  import {
5700
8314
  cpSync,
5701
- existsSync as existsSync10,
8315
+ existsSync as existsSync11,
5702
8316
  lstatSync as lstatSync4,
5703
- mkdirSync as mkdirSync5,
8317
+ mkdirSync as mkdirSync6,
5704
8318
  readdirSync as readdirSync5,
5705
8319
  readFileSync as readFileSync4,
5706
8320
  renameSync as renameSync5,
5707
8321
  symlinkSync
5708
8322
  } from "node:fs";
5709
- 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";
5710
8324
  function frontmatterBlock(path) {
5711
8325
  try {
5712
8326
  const text3 = readFileSync4(path, "utf8");
@@ -5726,13 +8340,13 @@ function nameFromSkillPath(path, fallback) {
5726
8340
  return fallback;
5727
8341
  }
5728
8342
  function directoryBundleName(dir, folderName) {
5729
- return nameFromSkillPath(join19(dir, "SKILL.md"), folderName);
8343
+ return nameFromSkillPath(join20(dir, "SKILL.md"), folderName);
5730
8344
  }
5731
8345
  function findSkillBundles(root) {
5732
8346
  const absolute = resolve12(root);
5733
- if (!existsSync10(absolute)) return [];
5734
- const rootSkill = join19(absolute, "SKILL.md");
5735
- if (existsSync10(rootSkill)) {
8347
+ if (!existsSync11(absolute)) return [];
8348
+ const rootSkill = join20(absolute, "SKILL.md");
8349
+ if (existsSync11(rootSkill)) {
5736
8350
  const folderName = basename10(absolute);
5737
8351
  const name2 = directoryBundleName(absolute, folderName);
5738
8352
  if (isKebabCaseName(name2)) {
@@ -5748,8 +8362,8 @@ function findSkillBundles(root) {
5748
8362
  }
5749
8363
  for (const entry of entries) {
5750
8364
  if (isTransientSkillEntryName(entry)) continue;
5751
- const full = join19(absolute, entry);
5752
- if (existsSync10(join19(full, "SKILL.md"))) {
8365
+ const full = join20(absolute, entry);
8366
+ if (existsSync11(join20(full, "SKILL.md"))) {
5753
8367
  const name2 = directoryBundleName(full, entry);
5754
8368
  if (!isKebabCaseName(name2)) continue;
5755
8369
  out.push({ name: name2, sourcePath: full, kind: "directory" });
@@ -5771,10 +8385,10 @@ function findSkillBundles(root) {
5771
8385
  }
5772
8386
  function resolveBundlesFromClone(cloneRoot, subpath) {
5773
8387
  const base = subpath === null || subpath === "" ? resolve12(cloneRoot) : resolve12(cloneRoot, subpath);
5774
- if (!existsSync10(base)) {
8388
+ if (!existsSync11(base)) {
5775
8389
  throw new AuxiliaryError("FILE_NOT_FOUND", `Path not found in repository: ${subpath ?? "."}`);
5776
8390
  }
5777
- if (base.toLowerCase().endsWith("skill.md") && existsSync10(base)) {
8391
+ if (base.toLowerCase().endsWith("skill.md") && existsSync11(base)) {
5778
8392
  const dir = dirname8(base);
5779
8393
  const name2 = directoryBundleName(dir, basename10(dir));
5780
8394
  if (!isKebabCaseName(name2)) {
@@ -5784,8 +8398,8 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
5784
8398
  }
5785
8399
  const direct = findSkillBundles(base);
5786
8400
  if (direct.length > 0) return direct;
5787
- for (const rel of ["skills", join19(".agents", "skills"), join19(".dsh", "skills")]) {
5788
- const nested = join19(base, rel);
8401
+ for (const rel of ["skills", join20(".agents", "skills"), join20(".dsh", "skills")]) {
8402
+ const nested = join20(base, rel);
5789
8403
  const found = findSkillBundles(nested);
5790
8404
  if (found.length > 0) return found;
5791
8405
  }
@@ -5794,13 +8408,13 @@ function resolveBundlesFromClone(cloneRoot, subpath) {
5794
8408
  function installTargetDir(target, projectRoot, agentsHome, dshHome2) {
5795
8409
  switch (target) {
5796
8410
  case "user":
5797
- return join19(resolve12(agentsHome), "skills");
8411
+ return join20(resolve12(agentsHome), "skills");
5798
8412
  case "user-dsh":
5799
- return join19(resolve12(dshHome2), "skills");
8413
+ return join20(resolve12(dshHome2), "skills");
5800
8414
  case "project":
5801
- return join19(resolve12(projectRoot), ".agents", "skills");
8415
+ return join20(resolve12(projectRoot), ".agents", "skills");
5802
8416
  case "project-dsh":
5803
- return join19(resolve12(projectRoot), ".dsh", "skills");
8417
+ return join20(resolve12(projectRoot), ".dsh", "skills");
5804
8418
  default: {
5805
8419
  const _exhaustive = target;
5806
8420
  return _exhaustive;
@@ -5808,7 +8422,7 @@ function installTargetDir(target, projectRoot, agentsHome, dshHome2) {
5808
8422
  }
5809
8423
  }
5810
8424
  function destinationForBundle(targetDir, bundle) {
5811
- 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`);
5812
8426
  }
5813
8427
  function removeDestination(dest) {
5814
8428
  removePathRobust(dest);
@@ -5826,13 +8440,13 @@ function isStaleSkillDestination(dest, kind) {
5826
8440
  if (kind === "file") {
5827
8441
  try {
5828
8442
  const stat = lstatSync4(dest);
5829
- if (stat.isSymbolicLink()) return !existsSync10(dest);
8443
+ if (stat.isSymbolicLink()) return !existsSync11(dest);
5830
8444
  return !stat.isFile();
5831
8445
  } catch {
5832
8446
  return true;
5833
8447
  }
5834
8448
  }
5835
- return !existsSync10(join19(dest, "SKILL.md"));
8449
+ return !existsSync11(join20(dest, "SKILL.md"));
5836
8450
  }
5837
8451
  function copySkillTree(source, dest) {
5838
8452
  try {
@@ -5849,7 +8463,7 @@ function copySkillTree(source, dest) {
5849
8463
  }
5850
8464
  }
5851
8465
  function copySkillTreeAtomic(source, dest, kind) {
5852
- mkdirSync5(dirname8(dest), { recursive: true });
8466
+ mkdirSync6(dirname8(dest), { recursive: true });
5853
8467
  if (kind === "file") {
5854
8468
  if (destinationPresent(dest)) removeDestination(dest);
5855
8469
  copySkillTree(source, dest);
@@ -5877,7 +8491,7 @@ function copySkillTreeAtomic(source, dest, kind) {
5877
8491
  }
5878
8492
  }
5879
8493
  function linkOrCopy(source, dest, mode, kind) {
5880
- mkdirSync5(dirname8(dest), { recursive: true });
8494
+ mkdirSync6(dirname8(dest), { recursive: true });
5881
8495
  if (mode === "copy") {
5882
8496
  copySkillTreeAtomic(source, dest, kind);
5883
8497
  return "copy";
@@ -5885,7 +8499,7 @@ function linkOrCopy(source, dest, mode, kind) {
5885
8499
  try {
5886
8500
  if (process.platform === "win32") {
5887
8501
  const stat = lstatSync4(source);
5888
- if (stat.isDirectory() || stat.isSymbolicLink() && existsSync10(join19(source, "SKILL.md"))) {
8502
+ if (stat.isDirectory() || stat.isSymbolicLink() && existsSync11(join20(source, "SKILL.md"))) {
5889
8503
  symlinkSync(source, dest, "junction");
5890
8504
  return "link";
5891
8505
  }
@@ -5916,12 +8530,12 @@ function installBundle(options) {
5916
8530
  // src/host/instructions-skills/content-revision.ts
5917
8531
  import { createHash as createHash7 } from "node:crypto";
5918
8532
  import { readdirSync as readdirSync6, readFileSync as readFileSync5 } from "node:fs";
5919
- import { join as join20, relative as relative3 } from "node:path";
8533
+ import { join as join21, relative as relative3 } from "node:path";
5920
8534
  function listRelativeFiles(dir, root) {
5921
8535
  const entries = [];
5922
8536
  for (const entry of readdirSync6(dir, { withFileTypes: true })) {
5923
8537
  if (entry.name.startsWith(".")) continue;
5924
- const abs = join20(dir, entry.name);
8538
+ const abs = join21(dir, entry.name);
5925
8539
  if (entry.isDirectory()) {
5926
8540
  entries.push(...listRelativeFiles(abs, root));
5927
8541
  } else if (entry.isFile()) {
@@ -5934,7 +8548,7 @@ function contentRevisionOfDir(dir) {
5934
8548
  const paths = listRelativeFiles(dir, dir).sort();
5935
8549
  const aggregate = createHash7("sha256");
5936
8550
  for (const relPath of paths) {
5937
- const contents = readFileSync5(join20(dir, relPath));
8551
+ const contents = readFileSync5(join21(dir, relPath));
5938
8552
  const fileDigest = createHash7("sha256").update(`${relPath}\0`).update(contents).digest();
5939
8553
  aggregate.update(fileDigest);
5940
8554
  }
@@ -6043,7 +8657,7 @@ function tempWorkDir(prefix) {
6043
8657
  base = realpathSync(base);
6044
8658
  } catch {
6045
8659
  }
6046
- return mkdtempSync(join21(base, prefix));
8660
+ return mkdtempSync(join22(base, prefix));
6047
8661
  }
6048
8662
  function execDetail(error) {
6049
8663
  if (!(error instanceof Error)) return String(error);
@@ -6145,7 +8759,7 @@ async function materializeSkillGitTreeFromSource(source, workDir, signal, progre
6145
8759
  return { rootDir, parsed };
6146
8760
  }
6147
8761
  async function materializeRepo(parsed, workDir, signal, progressSessionId) {
6148
- const cloneDir = join21(workDir, "repo");
8762
+ const cloneDir = join22(workDir, "repo");
6149
8763
  const archiveErrors = [];
6150
8764
  const sessionId = progressSessionId?.trim() ?? "";
6151
8765
  if (parsed.github !== null) {
@@ -6286,14 +8900,14 @@ async function installSkillsFromGit(options) {
6286
8900
  // src/host/instructions-skills/update-check.ts
6287
8901
  import { mkdtempSync as mkdtempSync2, realpathSync as realpathSync2, rmSync as rmSync5 } from "node:fs";
6288
8902
  import { tmpdir as tmpdir4 } from "node:os";
6289
- import { join as join22 } from "node:path";
8903
+ import { join as join23 } from "node:path";
6290
8904
  function tempWorkDir2(prefix) {
6291
8905
  let base = tmpdir4();
6292
8906
  try {
6293
8907
  base = realpathSync2(base);
6294
8908
  } catch {
6295
8909
  }
6296
- return mkdtempSync2(join22(base, prefix));
8910
+ return mkdtempSync2(join23(base, prefix));
6297
8911
  }
6298
8912
  function revisionPathForBundle(bundle) {
6299
8913
  return bundle.kind === "directory" ? bundle.sourcePath : bundle.sourcePath;
@@ -6352,9 +8966,9 @@ async function checkGithubSkillUpdate(record2, options) {
6352
8966
 
6353
8967
  // src/host/instructions-skills/zip-install.ts
6354
8968
  import { execFile as execFile4 } from "node:child_process";
6355
- 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";
6356
8970
  import { tmpdir as tmpdir5 } from "node:os";
6357
- 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";
6358
8972
  import { promisify as promisify4 } from "node:util";
6359
8973
  var execFileAsync4 = promisify4(execFile4);
6360
8974
  function tempWorkDir3(prefix) {
@@ -6363,11 +8977,11 @@ function tempWorkDir3(prefix) {
6363
8977
  base = realpathSync3(base);
6364
8978
  } catch {
6365
8979
  }
6366
- return mkdtempSync3(join23(base, prefix));
8980
+ return mkdtempSync3(join24(base, prefix));
6367
8981
  }
6368
8982
  async function extractZipArchive(zipPath, destDir, signal) {
6369
8983
  signal.throwIfAborted();
6370
- mkdirSync6(destDir, { recursive: true });
8984
+ mkdirSync7(destDir, { recursive: true });
6371
8985
  try {
6372
8986
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
6373
8987
  windowsHide: true,
@@ -6381,14 +8995,14 @@ async function extractZipArchive(zipPath, destDir, signal) {
6381
8995
  }
6382
8996
  async function installSkillsFromZipFile(options) {
6383
8997
  const zipPath = resolve14(options.zipPath);
6384
- if (!existsSync12(zipPath)) {
8998
+ if (!existsSync13(zipPath)) {
6385
8999
  throw new AuxiliaryError("FILE_NOT_FOUND", `Zip not found: ${zipPath}`);
6386
9000
  }
6387
9001
  if (!zipPath.toLowerCase().endsWith(".zip")) {
6388
9002
  throw new AuxiliaryError("FILE_DENIED", `Expected a .zip archive: ${basename12(zipPath)}`);
6389
9003
  }
6390
9004
  const workDir = tempWorkDir3("ae-skill-zip-");
6391
- const extractDir = join23(workDir, "extract");
9005
+ const extractDir = join24(workDir, "extract");
6392
9006
  try {
6393
9007
  await extractZipArchive(zipPath, extractDir, options.signal);
6394
9008
  const root = unwrapArchiveRoot(extractDir);
@@ -6551,12 +9165,12 @@ async function enrichSkillsFromLedger(skills, options) {
6551
9165
  }
6552
9166
  function inferSkillInstallTarget(name2, cwd, projectRoot, env = process.env) {
6553
9167
  const roots = skillRootsFor(cwd, projectRoot, env);
6554
- const projectAgents = join24(resolve15(projectRoot), ".agents", "skills");
6555
- const projectDsh = join24(resolve15(projectRoot), ".dsh", "skills");
6556
- const userAgents = join24(agentsHomeOf(env), "skills");
6557
- 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");
6558
9172
  for (const root of roots) {
6559
- 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`));
6560
9174
  if (!present) continue;
6561
9175
  if (samePath2(root, projectAgents)) return "project";
6562
9176
  if (samePath2(root, projectDsh)) return "project-dsh";
@@ -6794,7 +9408,7 @@ async function readSkillDocumentNow(options) {
6794
9408
  throw new AuxiliaryError("FILE_DENIED", "Only SKILL.md may be previewed");
6795
9409
  }
6796
9410
  options.signal.throwIfAborted();
6797
- if (!existsSync13(absolutePath2)) {
9411
+ if (!existsSync14(absolutePath2)) {
6798
9412
  throw new AuxiliaryError("FILE_NOT_FOUND", "Skill document not found");
6799
9413
  }
6800
9414
  try {
@@ -6829,7 +9443,7 @@ async function readSkillDocumentNow(options) {
6829
9443
  }
6830
9444
 
6831
9445
  // src/host/mcp-connectors/io.ts
6832
- import { existsSync as existsSync15 } from "node:fs";
9446
+ import { existsSync as existsSync16 } from "node:fs";
6833
9447
 
6834
9448
  // src/host/mcp-connectors/validate.ts
6835
9449
  var MCP_SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
@@ -6951,22 +9565,22 @@ function parseMcpJsonText(jsonText) {
6951
9565
  }
6952
9566
 
6953
9567
  // src/host/mcp-connectors/install-git.ts
6954
- import { existsSync as existsSync14, mkdirSync as mkdirSync7, readFileSync as readFileSync7, renameSync as renameSync6, rmSync as rmSync7 } from "node:fs";
6955
- 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";
6956
9570
 
6957
9571
  // src/host/mcp-connectors/paths.ts
6958
- import { join as join25 } from "node:path";
9572
+ import { join as join26 } from "node:path";
6959
9573
  function mcpConnectorsRoot(pluginDataPackageRoot) {
6960
- return join25(pluginDataPackageRoot, "mcp-connectors");
9574
+ return join26(pluginDataPackageRoot, "mcp-connectors");
6961
9575
  }
6962
9576
  function mcpConnectorsLedgerPath(root) {
6963
- return join25(root, "mcp-connectors.json");
9577
+ return join26(root, "mcp-connectors.json");
6964
9578
  }
6965
9579
  function mcpServersRoot(root) {
6966
- return join25(root, "mcp-servers");
9580
+ return join26(root, "mcp-servers");
6967
9581
  }
6968
9582
  function mcpServerInstallDir(root, id) {
6969
- return join25(mcpServersRoot(root), id);
9583
+ return join26(mcpServersRoot(root), id);
6970
9584
  }
6971
9585
 
6972
9586
  // src/host/mcp-connectors/install-git.ts
@@ -6983,8 +9597,8 @@ function inferStdioFromPackageJson(installDir, override) {
6983
9597
  cwd: installDir
6984
9598
  };
6985
9599
  }
6986
- const pkgPath = join26(installDir, "package.json");
6987
- if (!existsSync14(pkgPath)) {
9600
+ const pkgPath = join27(installDir, "package.json");
9601
+ if (!existsSync15(pkgPath)) {
6988
9602
  return {
6989
9603
  transport: "stdio",
6990
9604
  command: "npx",
@@ -7001,7 +9615,7 @@ function inferStdioFromPackageJson(installDir, override) {
7001
9615
  return {
7002
9616
  transport: "stdio",
7003
9617
  command: process.execPath,
7004
- args: [join26(installDir, bin)],
9618
+ args: [join27(installDir, bin)],
7005
9619
  env: {},
7006
9620
  cwd: installDir
7007
9621
  };
@@ -7014,7 +9628,7 @@ function inferStdioFromPackageJson(installDir, override) {
7014
9628
  return {
7015
9629
  transport: "stdio",
7016
9630
  command: process.execPath,
7017
- args: [join26(installDir, first)],
9631
+ args: [join27(installDir, first)],
7018
9632
  env: {},
7019
9633
  cwd: installDir
7020
9634
  };
@@ -7024,7 +9638,7 @@ function inferStdioFromPackageJson(installDir, override) {
7024
9638
  return {
7025
9639
  transport: "stdio",
7026
9640
  command: process.execPath,
7027
- args: [join26(installDir, pkg.main)],
9641
+ args: [join27(installDir, pkg.main)],
7028
9642
  env: {},
7029
9643
  cwd: installDir
7030
9644
  };
@@ -7043,17 +9657,17 @@ function inferStdioFromPackageJson(installDir, override) {
7043
9657
  async function installMcpServerFromGit(options) {
7044
9658
  const parsed = parseGitSkillSource(options.source);
7045
9659
  const installDir = mcpServerInstallDir(options.rootDir, options.id);
7046
- if (existsSync14(installDir)) {
9660
+ if (existsSync15(installDir)) {
7047
9661
  if (!options.force) {
7048
9662
  throw new AuxiliaryError("FILE_EDIT_FAILED", `MCP install dir already exists: ${installDir}`);
7049
9663
  }
7050
9664
  removePathRobust(installDir);
7051
9665
  }
7052
- mkdirSync7(join26(options.rootDir, "mcp-servers"), { recursive: true });
9666
+ mkdirSync8(join27(options.rootDir, "mcp-servers"), { recursive: true });
7053
9667
  const staging = `${installDir}.staging.${process.pid}`;
7054
9668
  try {
7055
- if (existsSync14(staging)) removePathRobust(staging);
7056
- mkdirSync7(staging, { recursive: true });
9669
+ if (existsSync15(staging)) removePathRobust(staging);
9670
+ mkdirSync8(staging, { recursive: true });
7057
9671
  if (parsed.github === null) {
7058
9672
  throw new AuxiliaryError(
7059
9673
  "FILE_EDIT_FAILED",
@@ -7069,13 +9683,13 @@ async function installMcpServerFromGit(options) {
7069
9683
  options.signal.throwIfAborted();
7070
9684
  let contentRoot = repoDir;
7071
9685
  if (parsed.subpath !== null) {
7072
- const nested = join26(repoDir, parsed.subpath);
7073
- if (!existsSync14(nested)) {
9686
+ const nested = join27(repoDir, parsed.subpath);
9687
+ if (!existsSync15(nested)) {
7074
9688
  throw new AuxiliaryError("FILE_EDIT_FAILED", `Subpath not found in repo: ${parsed.subpath}`);
7075
9689
  }
7076
9690
  contentRoot = nested;
7077
9691
  }
7078
- mkdirSync7(join26(options.rootDir, "mcp-servers"), { recursive: true });
9692
+ mkdirSync8(join27(options.rootDir, "mcp-servers"), { recursive: true });
7079
9693
  if (contentRoot !== repoDir) {
7080
9694
  const nestedStaging = `${installDir}.nested.${process.pid}`;
7081
9695
  renameSync6(contentRoot, nestedStaging);
@@ -7090,11 +9704,11 @@ async function installMcpServerFromGit(options) {
7090
9704
  }
7091
9705
  } catch (error) {
7092
9706
  try {
7093
- if (existsSync14(staging)) rmSync7(staging, { recursive: true, force: true });
9707
+ if (existsSync15(staging)) rmSync7(staging, { recursive: true, force: true });
7094
9708
  } catch {
7095
9709
  }
7096
9710
  try {
7097
- if (existsSync14(installDir)) removePathRobust(installDir);
9711
+ if (existsSync15(installDir)) removePathRobust(installDir);
7098
9712
  } catch {
7099
9713
  }
7100
9714
  if (error instanceof AuxiliaryError) throw error;
@@ -7192,7 +9806,7 @@ async function uninstallMcpConnectorNow(host, request) {
7192
9806
  }
7193
9807
  const next = doc.connectors.filter((entry) => entry.id !== request.id);
7194
9808
  const installDir = mcpServerInstallDir(host.store.rootDir, request.id);
7195
- if (existsSync15(installDir)) {
9809
+ if (existsSync16(installDir)) {
7196
9810
  try {
7197
9811
  removePathRobust(installDir);
7198
9812
  } catch (error) {
@@ -7324,7 +9938,7 @@ function listMcpConnectorToolsNow(host, request) {
7324
9938
  }
7325
9939
 
7326
9940
  // src/host/mcp-connectors/store.ts
7327
- 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";
7328
9942
  import { dirname as dirname10 } from "node:path";
7329
9943
 
7330
9944
  // src/host/mcp-connectors/types.ts
@@ -7407,7 +10021,7 @@ function parseDoc2(raw) {
7407
10021
  }
7408
10022
  }
7409
10023
  function createMcpConnectorsStore(rootDir) {
7410
- mkdirSync8(rootDir, { recursive: true });
10024
+ mkdirSync9(rootDir, { recursive: true });
7411
10025
  const file = mcpConnectorsLedgerPath(rootDir);
7412
10026
  return {
7413
10027
  rootDir,
@@ -7426,7 +10040,7 @@ function createMcpConnectorsStore(rootDir) {
7426
10040
  version: MCP_CONNECTORS_VERSION,
7427
10041
  connectors: [...connectors]
7428
10042
  };
7429
- mkdirSync8(dirname10(file), { recursive: true });
10043
+ mkdirSync9(dirname10(file), { recursive: true });
7430
10044
  const tmp = `${file}.${process.pid}.tmp`;
7431
10045
  writeFileSync4(tmp, `${JSON.stringify(doc, null, 2)}
7432
10046
  `, "utf8");
@@ -9337,7 +11951,7 @@ function mergeUsageCalls(stored, history) {
9337
11951
  // src/host/usage/ledger.ts
9338
11952
  import { randomUUID as randomUUID6 } from "node:crypto";
9339
11953
  import { chmod as chmod4, mkdir as mkdir5, readFile as readFile5, rename as rename4, unlink as unlink5, writeFile as writeFile4 } from "node:fs/promises";
9340
- import { basename as basename14, join as join27 } from "node:path";
11954
+ import { basename as basename14, join as join28 } from "node:path";
9341
11955
  import { z as z3 } from "zod";
9342
11956
  var callSchema = z3.object({
9343
11957
  at: z3.number().int().nonnegative(),
@@ -9367,7 +11981,7 @@ async function removeIfPresent5(path) {
9367
11981
  }
9368
11982
  }
9369
11983
  async function writeAtomic4(path, value) {
9370
- const temporary = join27(join27(path, ".."), `.${basename14(path)}.${randomUUID6()}.tmp`);
11984
+ const temporary = join28(join28(path, ".."), `.${basename14(path)}.${randomUUID6()}.tmp`);
9371
11985
  try {
9372
11986
  await writeFile4(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
9373
11987
  await rename4(temporary, path);
@@ -9381,7 +11995,7 @@ var UsageLedger = class {
9381
11995
  }) {
9382
11996
  this.root = root;
9383
11997
  this.warn = warn;
9384
- this.file = join27(root, "ledger.json");
11998
+ this.file = join28(root, "ledger.json");
9385
11999
  }
9386
12000
  root;
9387
12001
  warn;
@@ -9904,6 +12518,196 @@ var softPauseSetRequestCodec = codec(
9904
12518
  softPauseSetRequestSchema
9905
12519
  );
9906
12520
  var softPauseStateCodec = codec("dsh-agent-enhancer#SoftPauseState", softPauseStateSchema);
12521
+ var showOsNotificationRequestSchema = z4.strictObject({
12522
+ title: z4.string().min(1).max(120),
12523
+ body: z4.string().min(1).max(240),
12524
+ tag: z4.string().max(120).optional()
12525
+ });
12526
+ var showOsNotificationResultSchema = z4.strictObject({
12527
+ shown: z4.boolean(),
12528
+ channel: z4.enum(["electron", "windows", "none"])
12529
+ });
12530
+ var showOsNotificationRequestCodec = codec(
12531
+ "dsh-agent-enhancer#ShowOsNotificationRequest",
12532
+ showOsNotificationRequestSchema
12533
+ );
12534
+ var showOsNotificationResultCodec = codec(
12535
+ "dsh-agent-enhancer#ShowOsNotificationResult",
12536
+ showOsNotificationResultSchema
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
+ );
9907
12711
  var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
9908
12712
  var instructionFileEntrySchema = z4.strictObject({
9909
12713
  id: z4.string().min(1),
@@ -10484,6 +13288,109 @@ var remoteInfo = createTypertRemoteInfo({
10484
13288
  }],
10485
13289
  result: softPauseStateCodec
10486
13290
  },
13291
+ "agentEnhancer/showOsNotification": {
13292
+ service: "agentEnhancer",
13293
+ implementation: "showOsNotification",
13294
+ invocation: { kind: "direct" },
13295
+ parameters: [{
13296
+ name: "request",
13297
+ source: "json",
13298
+ codec: showOsNotificationRequestCodec,
13299
+ strictCodec: showOsNotificationRequestCodec
13300
+ }],
13301
+ result: showOsNotificationResultCodec
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
+ },
10487
13394
  "agentEnhancer/listInstructionsSkills": {
10488
13395
  service: "agentEnhancer",
10489
13396
  implementation: "listInstructionsSkills",
@@ -10885,9 +13792,111 @@ var checkpointRemoteInfo = createTypertRemoteInfo({
10885
13792
  }
10886
13793
  }, z4);
10887
13794
 
13795
+ // src/host/run-alerts/notify.ts
13796
+ import { execFile as execFile5 } from "node:child_process";
13797
+ import { createRequire as createRequire2 } from "node:module";
13798
+ import { promisify as promisify5 } from "node:util";
13799
+ var execFileAsync5 = promisify5(execFile5);
13800
+ var nodeRequire2 = createRequire2(import.meta.url);
13801
+ var DESKTOP_WINDOWS_APP_USER_MODEL_ID = "electron.app.DeepSeek Harness";
13802
+ function loadElectron() {
13803
+ try {
13804
+ return nodeRequire2("electron");
13805
+ } catch {
13806
+ return void 0;
13807
+ }
13808
+ }
13809
+ function resolveWindowsAppId(electron = loadElectron()) {
13810
+ const fromEnv = process.env.DSH_TOAST_APP_ID?.trim();
13811
+ if (fromEnv) return fromEnv;
13812
+ try {
13813
+ const id = electron?.app?.getAppUserModelId?.();
13814
+ if (typeof id === "string" && id.trim() !== "") return id.trim();
13815
+ } catch {
13816
+ }
13817
+ try {
13818
+ const name2 = electron?.app?.getName?.() ?? electron?.app?.name;
13819
+ if (typeof name2 === "string" && name2.trim() !== "") {
13820
+ return `electron.app.${name2.trim()}`;
13821
+ }
13822
+ } catch {
13823
+ }
13824
+ return DESKTOP_WINDOWS_APP_USER_MODEL_ID;
13825
+ }
13826
+ function showViaElectron(input, electron = loadElectron()) {
13827
+ try {
13828
+ const NotificationCtor = electron?.Notification;
13829
+ if (NotificationCtor === void 0) return false;
13830
+ if (typeof NotificationCtor.isSupported === "function" && !NotificationCtor.isSupported()) {
13831
+ return false;
13832
+ }
13833
+ const note = new NotificationCtor({
13834
+ title: input.title,
13835
+ body: input.body,
13836
+ silent: false
13837
+ });
13838
+ note.show();
13839
+ return true;
13840
+ } catch {
13841
+ return false;
13842
+ }
13843
+ }
13844
+ function escapeXml(value) {
13845
+ return value.replace(/&/gu, "&amp;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;").replace(/"/gu, "&quot;").replace(/'/gu, "&apos;");
13846
+ }
13847
+ function escapePowerShellSingle(value) {
13848
+ return value.replace(/'/gu, "''");
13849
+ }
13850
+ async function showViaWindowsToast(input, appId) {
13851
+ if (process.platform !== "win32") return false;
13852
+ const title = escapeXml(input.title.slice(0, 120));
13853
+ const body = escapeXml(input.body.slice(0, 240));
13854
+ const xml = escapePowerShellSingle(
13855
+ `<toast><visual><binding template="ToastGeneric"><text>${title}</text><text>${body}</text></binding></visual></toast>`
13856
+ );
13857
+ const script = [
13858
+ "$ErrorActionPreference = 'Stop'",
13859
+ "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null",
13860
+ "[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",
13861
+ `$xml = '${xml}'`,
13862
+ "$doc = New-Object Windows.Data.Xml.Dom.XmlDocument",
13863
+ "$doc.LoadXml($xml)",
13864
+ `$appId = '${escapePowerShellSingle(appId)}'`,
13865
+ "$toast = [Windows.UI.Notifications.ToastNotification]::new($doc)",
13866
+ "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId).Show($toast)"
13867
+ ].join("; ");
13868
+ try {
13869
+ await execFileAsync5("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
13870
+ windowsHide: true,
13871
+ timeout: 8e3,
13872
+ env: process.env
13873
+ });
13874
+ return true;
13875
+ } catch {
13876
+ return false;
13877
+ }
13878
+ }
13879
+ async function showOsNotificationNow(input) {
13880
+ const title = input.title.trim();
13881
+ const body = input.body.trim();
13882
+ if (title === "" || body === "") return { shown: false, channel: "none" };
13883
+ if (process.env.VITEST === "true") return { shown: false, channel: "none" };
13884
+ const payload = {
13885
+ title: title.slice(0, 120),
13886
+ body: body.slice(0, 240),
13887
+ ...input.tag === void 0 ? {} : { tag: input.tag }
13888
+ };
13889
+ const electron = loadElectron();
13890
+ if (showViaElectron(payload, electron)) return { shown: true, channel: "electron" };
13891
+ if (await showViaWindowsToast(payload, resolveWindowsAppId(electron))) {
13892
+ return { shown: true, channel: "windows" };
13893
+ }
13894
+ return { shown: false, channel: "none" };
13895
+ }
13896
+
10888
13897
  // src/host/update/check.ts
10889
- import { homedir as homedir4 } from "node:os";
10890
- import { join as join29 } from "node:path";
13898
+ import { homedir as homedir5 } from "node:os";
13899
+ import { join as join30 } from "node:path";
10891
13900
 
10892
13901
  // src/host/update/cli.ts
10893
13902
  import { spawn as nodeSpawn } from "node:child_process";
@@ -10958,9 +13967,9 @@ async function runPluginAdd(latest, spawnFn = defaultSpawn) {
10958
13967
 
10959
13968
  // src/host/update/install-kind.ts
10960
13969
  import { lstatSync as lstatSync5 } from "node:fs";
10961
- import { join as join28 } from "node:path";
13970
+ import { join as join29 } from "node:path";
10962
13971
  function detectInstallKind(profileDir) {
10963
- const pkgPath = join28(profileDir, "node_modules", PACKAGE_NAME);
13972
+ const pkgPath = join29(profileDir, "node_modules", PACKAGE_NAME);
10964
13973
  try {
10965
13974
  const stat = lstatSync5(pkgPath);
10966
13975
  if (stat.isSymbolicLink()) return "link";
@@ -11090,9 +14099,9 @@ function isNewerVersion(latest, current) {
11090
14099
  }
11091
14100
 
11092
14101
  // src/host/update/check.ts
11093
- function resolveDesktopProfileDir(env = process.env, home = homedir4()) {
11094
- const dshHome2 = env.DSH_HOME ?? join29(home, ".dsh");
11095
- 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");
11096
14105
  }
11097
14106
  async function checkPluginUpdate(deps) {
11098
14107
  const latest = await deps.fetchLatest();
@@ -11178,6 +14187,12 @@ var Config = z5.object({
11178
14187
  sessionDeleteEnabled: z5.boolean().default(true).volatile(),
11179
14188
  fileEditEnabled: z5.boolean().default(true).volatile(),
11180
14189
  softPauseEnabled: z5.boolean().default(true).volatile(),
14190
+ runAlertsEnabled: z5.boolean().default(true).volatile(),
14191
+ /** Coerced via resolveRunAlertsLevel in readSettings (`hidden` | `unfocused` | `always`). */
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(),
11181
14196
  instructionsSkillsEnabled: z5.boolean().default(true).volatile(),
11182
14197
  mcpConnectorsEnabled: z5.boolean().default(true).volatile(),
11183
14198
  // Empty provider/model = follow the current Desktop session model.
@@ -11224,8 +14239,13 @@ var AgentEnhancerService = class extends TypertRemoteService {
11224
14239
  };
11225
14240
  }
11226
14241
  }, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
11227
- join30(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
11228
- ), 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
+ )) {
11229
14249
  super(ctx, "agentEnhancer");
11230
14250
  this.models = models;
11231
14251
  this.usage = usage;
@@ -11236,6 +14256,10 @@ var AgentEnhancerService = class extends TypertRemoteService {
11236
14256
  this.softPauseEnabled = softPauseEnabled;
11237
14257
  this.installLedgerRoot = installLedgerRoot;
11238
14258
  this.mcpHost = mcpHost;
14259
+ this.browserAgent = browserAgent;
14260
+ this.browserAgentSettings = browserAgentSettings;
14261
+ this.setBrowserAgentBrowser = setBrowserAgentBrowser;
14262
+ this.browserAgentProfileDir = browserAgentProfileDir;
11239
14263
  }
11240
14264
  models;
11241
14265
  usage;
@@ -11246,6 +14270,52 @@ var AgentEnhancerService = class extends TypertRemoteService {
11246
14270
  softPauseEnabled;
11247
14271
  installLedgerRoot;
11248
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
+ }
11249
14319
  requireMcpHost() {
11250
14320
  if (this.mcpHost === null) {
11251
14321
  throw new RemoteError("agent-enhancer/failed", "MCP connectors host is unavailable", {
@@ -11720,6 +14790,92 @@ var AgentEnhancerService = class extends TypertRemoteService {
11720
14790
  else this.softPause.release(request.sessionId);
11721
14791
  return { sessionId: request.sessionId, engaged: this.softPause.isEngaged(request.sessionId) };
11722
14792
  }
14793
+ /** Desktop OS notification for run alerts (Electron / Windows Action Center). */
14794
+ async showOsNotification(request) {
14795
+ this.assertOwner();
14796
+ return await showOsNotificationNow(request);
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
+ }
11723
14879
  async applyUpdate() {
11724
14880
  this.assertOwner();
11725
14881
  return applyPluginUpdateForHost({
@@ -11732,16 +14888,16 @@ var AgentEnhancerService = class extends TypertRemoteService {
11732
14888
  }
11733
14889
  };
11734
14890
  function resolveCheckpointRoot(dshHome2) {
11735
- const base = join30(dshHome2, "profiles", "desktop", "plugin-data");
11736
- const nextPkg = join30(base, PACKAGE_NAME);
11737
- const next = join30(nextPkg, "checkpoint");
11738
- const prev = join30(base, LEGACY_PACKAGE_NAME, "checkpoint");
11739
- if (!existsSync16(next) && existsSync16(prev)) {
11740
- 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 });
11741
14897
  renameSync8(prev, next);
11742
- const prevPkg = join30(base, LEGACY_PACKAGE_NAME);
14898
+ const prevPkg = join31(base, LEGACY_PACKAGE_NAME);
11743
14899
  try {
11744
- if (existsSync16(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
14900
+ if (existsSync17(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
11745
14901
  } catch {
11746
14902
  }
11747
14903
  }
@@ -11809,6 +14965,10 @@ function readSettings(config) {
11809
14965
  sessionDeleteEnabled: config.sessionDeleteEnabled.get(),
11810
14966
  fileEditEnabled: config.fileEditEnabled.get(),
11811
14967
  softPauseEnabled: config.softPauseEnabled.get(),
14968
+ runAlertsEnabled: config.runAlertsEnabled.get(),
14969
+ runAlertsLevel: resolveRunAlertsLevel(config.runAlertsLevel.get()),
14970
+ browserAgentEnabled: config.browserAgentEnabled.get(),
14971
+ browserAgentBrowser: resolveBrowserAgentBrowser(config.browserAgentBrowser.get()),
11812
14972
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
11813
14973
  mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
11814
14974
  optimizeProvider: config.optimizeProvider.get(),
@@ -11839,9 +14999,9 @@ function apply(ctx, config) {
11839
14999
  const settings = () => readSettings(config);
11840
15000
  const models = new AuxiliaryModels(ctx, settings);
11841
15001
  installAutoSessionRoute(ctx, { settings });
11842
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join30(homedir5(), ".dsh"));
11843
- const pluginDataPackageRoot = join30(storageRoot, "..");
11844
- 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) => {
11845
15005
  ctx.logger.warn(message);
11846
15006
  });
11847
15007
  const balancesFacade = (() => {
@@ -11871,12 +15031,12 @@ function apply(ctx, config) {
11871
15031
  })();
11872
15032
  installUsageObserver(ctx, usage);
11873
15033
  const store = new CheckpointStore(storageRoot);
11874
- const cutStore = new SessionCutStore(join30(storageRoot, "cuts"));
15034
+ const cutStore = new SessionCutStore(join31(storageRoot, "cuts"));
11875
15035
  const cutCache = /* @__PURE__ */ new Map();
11876
15036
  const sessionCleanup = new SessionCleanupRegistry();
11877
15037
  sessionCleanup.register(createCheckpointCleaner({ store, cutStore, storageRoot }));
11878
- sessionCleanup.register(createContextExcludeCleaner(join30(storageRoot, "..")));
11879
- const extraFoldersStore = createExtraFoldersStore(join30(storageRoot, "..", "extra-folders"));
15038
+ sessionCleanup.register(createContextExcludeCleaner(join31(storageRoot, "..")));
15039
+ const extraFoldersStore = createExtraFoldersStore(join31(storageRoot, "..", "extra-folders"));
11880
15040
  const softPauseGate = new SoftPauseGate();
11881
15041
  const mcpStore = createMcpConnectorsStore(mcpConnectorsRoot(pluginDataPackageRoot));
11882
15042
  const mcpRuntime = new McpConnectorRuntime(ctx, mcpStore);
@@ -11886,6 +15046,34 @@ function apply(ctx, config) {
11886
15046
  const detail = error instanceof Error ? error.message : String(error);
11887
15047
  ctx.logger.warn(`agent-enhancer: initial MCP connector sync failed: ${detail}`);
11888
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
+ });
11889
15077
  new AgentEnhancerService(
11890
15078
  ctx,
11891
15079
  models,
@@ -11908,21 +15096,44 @@ function apply(ctx, config) {
11908
15096
  softPauseGate,
11909
15097
  () => settings().softPauseEnabled,
11910
15098
  pluginDataPackageRoot,
11911
- 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
11912
15109
  );
11913
15110
  ctx.effect(() => {
11914
15111
  const unsubscribe = ctx.on("internal/update", (resolvedConfig, next) => {
11915
- const enabled = resolvedConfig.mcpConnectorsEnabled.get();
15112
+ const cfg = resolvedConfig;
15113
+ const enabled = cfg.mcpConnectorsEnabled.get();
11916
15114
  mcpRuntime.setFeatureEnabled(enabled);
11917
15115
  void mcpRuntime.sync().catch((error) => {
11918
15116
  const detail = error instanceof Error ? error.message : String(error);
11919
15117
  ctx.logger.warn(`agent-enhancer: MCP connector sync after settings update failed: ${detail}`);
11920
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
+ }
11921
15131
  return next();
11922
15132
  });
11923
15133
  return async () => {
11924
15134
  unsubscribe();
11925
15135
  await mcpRuntime.disposeAll();
15136
+ await browserAgent.dispose();
11926
15137
  };
11927
15138
  });
11928
15139
  installSoftPause(ctx, {