@deepseek-insight/dsi 0.8.1 → 0.8.3

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 (101) hide show
  1. package/build/client/_app/immutable/assets/0.DyOAkKS-.css +2 -0
  2. package/build/client/_app/immutable/assets/2.BPprd30B.css +1 -0
  3. package/build/client/_app/immutable/chunks/{CJ1fzlPC.js → BoHeiMOU.js} +1 -1
  4. package/build/client/_app/immutable/chunks/C9QAOGL1.js +2 -0
  5. package/build/client/_app/immutable/chunks/QJuSx3RG.js +1 -0
  6. package/build/client/_app/immutable/chunks/sC_8Ss7w.js +1 -0
  7. package/build/client/_app/immutable/entry/{app.DP0oSUf-.js → app.S_mxIoOg.js} +2 -2
  8. package/build/client/_app/immutable/entry/start.BPQAB3iV.js +1 -0
  9. package/build/client/_app/immutable/nodes/{1.UuScj-IS.js → 1.D20V6eTe.js} +1 -1
  10. package/build/client/_app/immutable/nodes/{2.CJRPZhbe.js → 2.BHcBdFqH.js} +223 -223
  11. package/build/client/_app/version.json +1 -1
  12. package/build/handler.js +4 -4
  13. package/build/index.js +4 -4
  14. package/build/server/chunks/chunks/{db.js-B8BUpxGM.js → db.js-DQm6CZ_r.js} +2 -2
  15. package/build/server/chunks/chunks/{db2.js-CNe3I_g2.js → db2.js-DUhFxA3a.js} +2 -2
  16. package/build/server/chunks/chunks/{dsh-connection.js-xltcocWy.js → dsh-connection.js-BgeraFA2.js} +2 -2
  17. package/build/server/chunks/chunks/{dsh-events.js-CGuF_had.js → dsh-events.js-BUkLR6ZV.js} +13 -1
  18. package/build/server/chunks/chunks/{git-probe.js-CUsTmhmV.js → git-probe.js-CLF37SRh.js} +3 -3
  19. package/build/server/chunks/chunks/{insight-config.js-CaHHJpFK.js → insight-config.js-Dp_2gB5J.js} +5 -3
  20. package/build/server/chunks/chunks/{internal2.js-Pv5iygVN.js → internal2.js-Ba5p8uFM.js} +2 -2
  21. package/build/server/chunks/chunks/registry.js-C2MdrfNv.js +954 -0
  22. package/build/server/chunks/chunks/{state.js-BCaKzPy6.js → state.js-BSiAgink.js} +2 -2
  23. package/build/server/chunks/chunks/{watcher.js-DcT3cS4v.js → watcher.js-BVKnoQUw.js} +5 -5
  24. package/build/server/chunks/entries/endpoints/api/a2a/_id_/{_server.ts.js-19pFOjH8.js → _server.ts.js-BjzdVwdY.js} +3 -3
  25. package/build/server/chunks/entries/endpoints/api/a2a/{_server.ts.js-BcUn6axe.js → _server.ts.js-3kQCQuHT.js} +6 -6
  26. package/build/server/chunks/entries/endpoints/api/a2a/register/{_server.ts.js-oMpzLZoy.js → _server.ts.js-BUBTCLFn.js} +6 -6
  27. package/build/server/chunks/entries/endpoints/api/browser/_id_/activate/_server.ts.js-CogDOHKu.js +45 -0
  28. package/build/server/chunks/entries/endpoints/api/browser/_id_/close/{_server.ts.js-DC3qPMQS.js → _server.ts.js-xOt7LnS1.js} +3 -3
  29. package/build/server/chunks/entries/endpoints/api/browser/_id_/closetab/_server.ts.js-CSmVPvSM.js +44 -0
  30. package/build/server/chunks/entries/endpoints/api/browser/_id_/element/_server.ts.js-BA40oCDW.js +43 -0
  31. package/build/server/chunks/entries/endpoints/api/browser/_id_/input/{_server.ts.js-CHNcK7BH.js → _server.ts.js-EX7eVzjp.js} +6 -5
  32. package/build/server/chunks/entries/endpoints/api/browser/_id_/mcp/{_server.ts.js-CYkOJL2O.js → _server.ts.js-B_EcmyFt.js} +3 -3
  33. package/build/server/chunks/entries/endpoints/api/browser/_id_/navigate/{_server.ts.js-DHTDi8KR.js → _server.ts.js-C3dYbyS3.js} +12 -8
  34. package/build/server/chunks/entries/endpoints/api/browser/_id_/opentab/_server.ts.js-CMhJJO25.js +45 -0
  35. package/build/server/chunks/entries/endpoints/api/browser/_id_/page/{_server.ts.js-Y5khEC2l.js → _server.ts.js-DIW4uI2S.js} +5 -4
  36. package/build/server/chunks/entries/endpoints/api/browser/_id_/stream/{_server.ts.js-BmjgfZD2.js → _server.ts.js-CIPIlq5X.js} +3 -3
  37. package/build/server/chunks/entries/endpoints/api/browser/_id_/tabs/_server.ts.js-CoEdOiml.js +34 -0
  38. package/build/server/chunks/entries/endpoints/api/browser/_id_/viewport/{_server.ts.js-IxS-goi1.js → _server.ts.js-CdELUoGT.js} +7 -5
  39. package/build/server/chunks/entries/endpoints/api/browser/{_server.ts.js-6STmJ7FD.js → _server.ts.js-ea6HpNGh.js} +15 -5
  40. package/build/server/chunks/entries/endpoints/api/config/{_server.ts.js-BVyx8gPc.js → _server.ts.js-C8XDnDwe.js} +3 -3
  41. package/build/server/chunks/entries/endpoints/api/dsh/directory/{_server.ts.js-CNJbv6CC.js → _server.ts.js-BFmWshpv.js} +3 -3
  42. package/build/server/chunks/entries/endpoints/api/dsh/jobs/{_server.ts.js-CDWmXDJX.js → _server.ts.js-DATWy5mQ.js} +3 -3
  43. package/build/server/chunks/entries/endpoints/api/dsh/jobs/follow/{_server.ts.js-BDXQcQSL.js → _server.ts.js-CugOD1Zd.js} +3 -3
  44. package/build/server/chunks/entries/endpoints/api/dsh/pick-directory/{_server.ts.js-CgedtzOg.js → _server.ts.js-DCupM4da.js} +3 -3
  45. package/build/server/chunks/entries/endpoints/api/dsh/presets/{_server.ts.js-ut2pK15B.js → _server.ts.js-Bh1btvr9.js} +3 -3
  46. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/attachment/{_server.ts.js-Ct2W7g4c.js → _server.ts.js-Cb8SBWVw.js} +3 -3
  47. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/cancel/{_server.ts.js-Rke3V_qh.js → _server.ts.js-WI9yH2iG.js} +3 -3
  48. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/catalog/{_server.ts.js-BYHm5WBA.js → _server.ts.js-bN9adUqz.js} +3 -3
  49. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/changes/{_server.ts.js-B_bEUKkt.js → _server.ts.js-Bxlm966G.js} +3 -3
  50. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/command/{_server.ts.js-D78fGUQk.js → _server.ts.js-CM-raN_Q.js} +3 -3
  51. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/events/{_server.ts.js-CgB_c7zG.js → _server.ts.js-BzP30TXW.js} +4 -4
  52. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/fork/{_server.ts.js-dVaW22_K.js → _server.ts.js-DvNkrTaY.js} +3 -3
  53. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/goal/{_server.ts.js-Dl8SBXdH.js → _server.ts.js-DXbCrefw.js} +3 -3
  54. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/history/{_server.ts.js-BKDiwMIE.js → _server.ts.js-B7YRQhuJ.js} +4 -4
  55. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/models/{_server.ts.js-D3FY2Wxt.js → _server.ts.js-C_AEaLLJ.js} +3 -3
  56. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/path/{_server.ts.js-BWuIEdjl.js → _server.ts.js-Dj-pF5ik.js} +2 -2
  57. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/permission/{_server.ts.js-CeiQFOGP.js → _server.ts.js-BX9FWJ6g.js} +3 -3
  58. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/prompt/{_server.ts.js-lMofZOns.js → _server.ts.js-CQ2Bmtu4.js} +3 -3
  59. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/rename/{_server.ts.js-CNalVHrK.js → _server.ts.js-Ha7xjnKW.js} +3 -3
  60. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/respond/{_server.ts.js-I2s8qvcV.js → _server.ts.js-BOg6llHk.js} +3 -3
  61. package/build/server/chunks/entries/endpoints/api/dsh/session/_sessionId_/select-model/{_server.ts.js-DTKELD7v.js → _server.ts.js-DBqGALzZ.js} +3 -3
  62. package/build/server/chunks/entries/endpoints/api/dsh/sessions/{_server.ts.js-BXSD__Gg.js → _server.ts.js-CvA8WDDb.js} +3 -3
  63. package/build/server/chunks/entries/endpoints/api/dsh/workspace-file/{_server.ts.js-C9IZl2Qh.js → _server.ts.js-BfjNH40j.js} +3 -3
  64. package/build/server/chunks/entries/endpoints/api/dsh/workspace-tree/{_server.ts.js-BRXu3UtL.js → _server.ts.js-De_qumyr.js} +3 -3
  65. package/build/server/chunks/entries/endpoints/api/dsh/workspaces/{_server.ts.js-DmnpiaD2.js → _server.ts.js-tFpJJHCb.js} +3 -3
  66. package/build/server/chunks/entries/endpoints/api/dsh/workspaces/_workspaceId_/delete/{_server.ts.js-C5qCdsdm.js → _server.ts.js-DVx5GGA_.js} +3 -3
  67. package/build/server/chunks/entries/endpoints/api/dsh/workspaces/_workspaceId_/rename/{_server.ts.js-BVUn49yf.js → _server.ts.js-DuKT-aZp.js} +3 -3
  68. package/build/server/chunks/entries/endpoints/api/prompts/_id_/{_server.ts.js-DuCOsoF0.js → _server.ts.js-DsWFidFY.js} +3 -3
  69. package/build/server/chunks/entries/endpoints/api/prompts/{_server.ts.js-2mcRY7IP.js → _server.ts.js-C6j0adQs.js} +3 -3
  70. package/build/server/chunks/entries/endpoints/api/prompts/use/{_server.ts.js-DZjaHZxU.js → _server.ts.js-BChAg4hm.js} +3 -3
  71. package/build/server/chunks/entries/endpoints/api/settings/{_server.ts.js-DTVmsohJ.js → _server.ts.js-BPSHqbZN.js} +2 -2
  72. package/build/server/chunks/entries/endpoints/api/terminal/{_server.ts.js-DZXTArj7.js → _server.ts.js-D5CbUe5k.js} +2 -2
  73. package/build/server/chunks/entries/endpoints/api/workspace/file-write/{_server.ts.js-LSc5EKH7.js → _server.ts.js-B-5YihUA.js} +5 -5
  74. package/build/server/chunks/entries/endpoints/api/workspace/git-events/{_server.ts.js-DNjiScBe.js → _server.ts.js-DT5jRZFE.js} +5 -5
  75. package/build/server/chunks/entries/endpoints/api/workspace/git-file-head/{_server.ts.js-CHMbLoSn.js → _server.ts.js-DtW-utrd.js} +5 -5
  76. package/build/server/chunks/entries/endpoints/api/workspace/git-map/{_server.ts.js-BgM4JEAm.js → _server.ts.js-8AIAo9jX.js} +5 -5
  77. package/build/server/chunks/entries/endpoints/api/workspace/git-status/{_server.ts.js-BH0cLS8o.js → _server.ts.js-CMw96vjY.js} +5 -5
  78. package/build/server/chunks/entries/endpoints/api/workspace/write-gate/{_server.ts.js-BzlV3cVT.js → _server.ts.js-DKufa14_.js} +5 -5
  79. package/build/server/chunks/entries/pages/{_error.svelte.js-BRyCyR0c.js → _error.svelte.js-D8-G0evO.js} +3 -3
  80. package/build/server/chunks/entries/pages/{_page.server.ts.js-DttLUwdf.js → _page.server.ts.js-7x6ZfGoB.js} +3 -3
  81. package/build/server/chunks/entries/pages/{_page.svelte.js-CKY8hz9T.js → _page.svelte.js-7xWLRsiZ.js} +333 -158
  82. package/build/server/chunks/{handler-D1oqmwyy.js → handler-BedQ0jP-.js} +3 -3
  83. package/build/server/chunks/{index.js-BZ8zP9wS.js → index.js-BF6tPPQs.js} +2 -2
  84. package/build/server/chunks/{manifest.js-CA6PuZTD.js → manifest.js-3c0p7QAl.js} +90 -55
  85. package/build/server/chunks/nodes/{0.js-DtkNHIFx.js → 0.js-B3i7sGR_.js} +3 -3
  86. package/build/server/chunks/nodes/1.js-eUf50uxI.js +9 -0
  87. package/build/server/chunks/nodes/{2.js-P1boc94A.js → 2.js-CgnRGwm6.js} +8 -8
  88. package/package.json +2 -7
  89. package/skills/dsi-kb-scenario/SKILL.md +67 -0
  90. package/template/.dsi/prompts.sqlite-shm +0 -0
  91. package/template/.dsi/prompts.sqlite-wal +0 -0
  92. package/template/.dsi/settings.yaml +8 -1
  93. package/build/client/_app/immutable/assets/0.DBVVEjy9.css +0 -2
  94. package/build/client/_app/immutable/assets/2.BhBfHqja.css +0 -1
  95. package/build/client/_app/immutable/chunks/C0tWPpc3.js +0 -2
  96. package/build/client/_app/immutable/chunks/gZFoJ-NI.js +0 -1
  97. package/build/client/_app/immutable/chunks/xkjLeSzJ.js +0 -1
  98. package/build/client/_app/immutable/entry/start.mBp3LB6J.js +0 -1
  99. package/build/server/chunks/chunks/registry.js-BTiJ1Kaj.js +0 -577
  100. package/build/server/chunks/nodes/1.js-Q6zZupRG.js +0 -9
  101. /package/build/client/_app/immutable/nodes/{0.Dm_ry-Pr.js → 0.6dTmg1Xv.js} +0 -0
@@ -0,0 +1,954 @@
1
+ import { d as readBrowserConfig } from './insight-config.js-Dp_2gB5J.js';
2
+ import { mkdirSync, rmSync, readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { spawn, spawnSync } from 'node:child_process';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { chromium } from 'playwright-core';
7
+
8
+ //#region src/lib/server/browser/relay.ts
9
+ var RelayClosedError = class extends Error {
10
+ constructor() {
11
+ super("relay is closed");
12
+ this.name = "RelayClosedError";
13
+ }
14
+ };
15
+ var BrowserRelay = class {
16
+ quality;
17
+ maxFps;
18
+ cdp;
19
+ subscribers = /* @__PURE__ */ new Set();
20
+ seq = 0;
21
+ latest = null;
22
+ chain = Promise.resolve();
23
+ started = false;
24
+ /** ADR-0040 D1: an INACTIVE tab's screencast is suspended (no Chrome-side
25
+ * encode, no wire cost) while the relay — ring, seq, subscribers — lives
26
+ * on, so re-activation resumes instead of rebuilding. */
27
+ paused = false;
28
+ /** JPEG quality 0..100 — from BrowserConfig.screencastQuality
29
+ * (default 90; yaml `browser.screencast:` override, amendment 3).
30
+ * maxFps — ADR-0039 D1: target fps intent; start() derives CDP's
31
+ * everyNthFrame from a nominal 30 Hz paint clock (clamp ≥1). */
32
+ constructor(cdp, quality = 90, maxFps = 15) {
33
+ this.quality = quality;
34
+ this.maxFps = maxFps;
35
+ this.cdp = cdp;
36
+ }
37
+ async start() {
38
+ if (!this.cdp || this.started) throw new RelayClosedError();
39
+ this.cdp.on("Page.screencastFrame", (ev) => {
40
+ this.seq += 1;
41
+ this.latest = {
42
+ seq: this.seq,
43
+ jpeg: ev.data,
44
+ metadata: ev.metadata
45
+ };
46
+ for (const sub of this.subscribers) sub(this.latest);
47
+ this.cdp?.send("Page.screencastFrameAck", { sessionId: ev.sessionId }).catch(() => void 0);
48
+ });
49
+ await this.cdp.send("Page.startScreencast", {
50
+ format: "jpeg",
51
+ quality: this.quality,
52
+ everyNthFrame: Math.max(1, Math.round(30 / this.maxFps))
53
+ });
54
+ this.started = true;
55
+ this.paused = false;
56
+ }
57
+ /** Suspend the screencast, keep the relay (ADR-0040 D1). Idempotent. */
58
+ async pause() {
59
+ if (!this.cdp || !this.started || this.paused) return;
60
+ this.paused = true;
61
+ await this.cdp.send("Page.stopScreencast").catch(() => void 0);
62
+ }
63
+ /** Re-start the screencast after a pause (same dials). Idempotent. */
64
+ async resume() {
65
+ if (!this.cdp || !this.started || !this.paused) return;
66
+ this.paused = false;
67
+ await this.cdp.send("Page.startScreencast", {
68
+ format: "jpeg",
69
+ quality: this.quality,
70
+ everyNthFrame: Math.max(1, Math.round(30 / this.maxFps))
71
+ }).catch(() => void 0);
72
+ }
73
+ /** Activation MUST stream (ADR-0040 D4): START a never-started (lazily
74
+ * attached) relay, RESUME a paused one, no-op an already-streaming one.
75
+ * BUGFIX 2026-10-24: activate() called resume() only — a lazily attached
76
+ * tab (started=false) never began streaming and the mirror froze on its
77
+ * seeded boundary frame (the operator's hung second YouTube tab). */
78
+ async ensureStreaming() {
79
+ if (!this.cdp) throw new RelayClosedError();
80
+ if (!this.started) return this.start();
81
+ if (this.paused) return this.resume();
82
+ }
83
+ /** Deterministic first-frame seed (RCA 2026-10-23 The First Frame That
84
+ * Never Knocked): a starved screencast birth leaves the ring empty
85
+ * FOREVER — screencast only speaks on paint damage. The opener synthesizes
86
+ * the first frame via Page.captureScreenshot and seeds the ring here so
87
+ * attachers get a frame immediately. Does not advance past a real frame. */
88
+ seed(frame) {
89
+ if (!this.cdp) throw new RelayClosedError();
90
+ if (this.latest) return;
91
+ this.seq += 1;
92
+ this.latest = {
93
+ ...frame,
94
+ seq: this.seq
95
+ };
96
+ for (const sub of this.subscribers) sub(this.latest);
97
+ }
98
+ latestFrame() {
99
+ if (!this.cdp) throw new RelayClosedError();
100
+ return this.latest;
101
+ }
102
+ subscribe(fn) {
103
+ if (!this.cdp) throw new RelayClosedError();
104
+ this.subscribers.add(fn);
105
+ return () => this.subscribers.delete(fn);
106
+ }
107
+ /** Serialized dispatch — every input waits for the previous one. */
108
+ dispatch(input) {
109
+ if (!this.cdp) return Promise.reject(new RelayClosedError());
110
+ const run = async () => {
111
+ if (!this.cdp) throw new RelayClosedError();
112
+ if (input.kind === "mouse") await this.cdp.send("Input.dispatchMouseEvent", {
113
+ type: input.type,
114
+ x: input.x,
115
+ y: input.y,
116
+ button: input.button ?? "none",
117
+ clickCount: input.clickCount,
118
+ deltaX: input.deltaX,
119
+ deltaY: input.deltaY,
120
+ pointerType: "mouse"
121
+ });
122
+ else if (input.kind === "key") await this.cdp.send("Input.dispatchKeyEvent", {
123
+ type: input.type,
124
+ key: input.key,
125
+ code: input.code,
126
+ windowsVirtualKeyCode: input.windowsVirtualKeyCode,
127
+ text: input.text
128
+ });
129
+ else await this.cdp.send("Input.insertText", { text: input.text });
130
+ };
131
+ const next = this.chain.then(run, run);
132
+ this.chain = next.catch(() => void 0);
133
+ return next;
134
+ }
135
+ stop() {
136
+ const cdp = this.cdp;
137
+ this.cdp = null;
138
+ this.subscribers.clear();
139
+ this.latest = null;
140
+ if (cdp && this.started) cdp.send("Page.stopScreencast").catch(() => void 0);
141
+ }
142
+ };
143
+ Number(process.env.DSI_MCP_PORT ?? 9515);
144
+ /** The reaper's ONLY test — pure: a session is reaper-eligible when nobody
145
+ * watches its stream AND its last MCP tool traffic is older than idleMs.
146
+ * An active agent (traffic younger than idleMs) is NEVER eligible (D2). */
147
+ function reaperEligible(e, idleMs, now) {
148
+ if (e.streamSubscribers > 0) return false;
149
+ return now - e.lastMcpActivity >= idleMs;
150
+ }
151
+ var BrowserRegistryRefusal = class extends Error {
152
+ code;
153
+ constructor(code, message) {
154
+ super(message);
155
+ this.name = "BrowserRegistryRefusal";
156
+ this.code = code;
157
+ }
158
+ };
159
+ function state() {
160
+ const p = process;
161
+ if (!p.__DSI_BROWSER_STATE__) {
162
+ p.__DSI_BROWSER_STATE__ = {
163
+ entries: /* @__PURE__ */ new Map(),
164
+ closed: /* @__PURE__ */ new Set()
165
+ };
166
+ sweepOrphanProfiles(new Set([...p.__DSI_BROWSER_STATE__.entries.keys()].map((id) => id.slice(0, 8))));
167
+ }
168
+ return p.__DSI_BROWSER_STATE__;
169
+ }
170
+ /** Boot-time sweep of profile dirs left by sessions that died without a
171
+ * close (crash, kill -9, reaper miss). keep = prefixes of LIVE entries —
172
+ * a module hot reload re-runs state() init against a process-global map
173
+ * that may hold live sessions, and this sweep must never delete one. */
174
+ function sweepOrphanProfiles(keep) {
175
+ try {
176
+ const root = readBrowserConfig().profileRoot;
177
+ for (const name of readdirSync(root)) if (!keep.has(name)) rmSync(join(root, name), {
178
+ recursive: true,
179
+ force: true
180
+ });
181
+ } catch {}
182
+ }
183
+ /** Brain re-homing (BUGFIX 2026-10-25): release the stable brain port
184
+ * from any OTHER live session so the NEWEST glass binds it. The DSH
185
+ * preset's brain URL is static (9515) — without this, the agent keeps
186
+ * driving an older glass while the operator watches the new one. The
187
+ * evicted glass mirrors fine; its status strip honestly reports the
188
+ * brain down (ADR-0029 D7: the mirror never depends on the brain). */
189
+ function evictBrainPort(brainPort, exceptId) {
190
+ for (const e of state().entries.values()) {
191
+ if (e.id === exceptId || !e.mcpInProcess || e.mcpInProcess.port !== brainPort) continue;
192
+ const brain = e.mcpInProcess;
193
+ (async () => {
194
+ try {
195
+ await new Promise((res) => {
196
+ brain.httpServer?.closeAllConnections?.();
197
+ brain.httpServer?.close?.(() => res());
198
+ setTimeout(res, 1500);
199
+ });
200
+ await brain.connection?.close?.();
201
+ } catch {}
202
+ })();
203
+ e.mcpInProcess = null;
204
+ e.mcpHealth = "down";
205
+ e.mcpError = "brain re-homed to a newer glass";
206
+ }
207
+ }
208
+ /** The in-process brain (D7): createConnection attached to the SAME headed
209
+ * browser via cdpEndpoint, served over a SIBLING http listener (SSE +
210
+ * messages endpoints) so a streamable-http MCP client (the DSH agent) can
211
+ * reach it without a child process. Port = session port + 100 (9501...):
212
+ * unique per session, out of the debug-port range. */
213
+ async function startInProcessMcp(browserPort, brainPort, onTraffic) {
214
+ const [{ createConnection }, { StreamableHTTPServerTransport }, http] = await Promise.all([
215
+ import('@playwright/mcp'),
216
+ import('@modelcontextprotocol/sdk/server/streamableHttp.js'),
217
+ import('node:http')
218
+ ]);
219
+ const connection = await createConnection({ browser: { cdpEndpoint: "http://127.0.0.1:" + browserPort } });
220
+ const transport = new StreamableHTTPServerTransport({
221
+ sessionIdGenerator: void 0,
222
+ enableJsonResponse: true
223
+ });
224
+ await connection.connect(transport);
225
+ const server = http.createServer(async (req, res) => {
226
+ if (new URL(req.url ?? "/", "http://127.0.0.1").pathname !== "/sse") {
227
+ res.statusCode = 404;
228
+ res.end();
229
+ return;
230
+ }
231
+ onTraffic?.();
232
+ try {
233
+ await transport.handleRequest(req, res);
234
+ } catch {
235
+ if (!res.writableEnded) res.end();
236
+ }
237
+ });
238
+ let port;
239
+ try {
240
+ port = await listen(server, brainPort);
241
+ } catch {
242
+ let lastErr = null;
243
+ port = 0;
244
+ for (let p = brainPort + 1; p <= brainPort + 60; p++) try {
245
+ port = await listen(server, p);
246
+ break;
247
+ } catch (e) {
248
+ lastErr = e;
249
+ }
250
+ if (port === 0) throw lastErr ?? /* @__PURE__ */ new Error("no free brain port in " + brainPort + "+ range");
251
+ }
252
+ return {
253
+ connection,
254
+ httpServer: server,
255
+ port
256
+ };
257
+ }
258
+ var listen = (server, port) => new Promise((res, rej) => {
259
+ const onError = () => {
260
+ server.off("listening", onListen);
261
+ rej(/* @__PURE__ */ new Error("EADDRINUSE " + port));
262
+ };
263
+ const onListen = () => {
264
+ server.off("error", onError);
265
+ const a = server.address();
266
+ res(typeof a === "object" && a ? a.port : port);
267
+ };
268
+ server.once("error", onError);
269
+ server.once("listening", onListen);
270
+ server.listen(port, "127.0.0.1");
271
+ });
272
+ function pidOfPort(port) {
273
+ const p = spawnSync("lsof", [
274
+ "-ti",
275
+ "tcp:" + port,
276
+ "-sTCP:LISTEN"
277
+ ], { stdio: "pipe" });
278
+ return p.status === 0 ? Number(p.stdout.toString().trim().split("\n")[0]) : null;
279
+ }
280
+ function portFree(port) {
281
+ return spawnSync("lsof", [
282
+ "-ti",
283
+ "tcp:" + port,
284
+ "-sTCP:LISTEN"
285
+ ], { stdio: "pipe" }).status !== 0;
286
+ }
287
+ function freePort(preferred) {
288
+ if (preferred && portFree(preferred)) return preferred;
289
+ for (let p = 9400; p < 9500; p++) if (portFree(p)) return p;
290
+ throw new Error("no free debug port in 9400..9499");
291
+ }
292
+ var BrowserRegistry = class {
293
+ list() {
294
+ return [...state().entries.values()].map((e) => ({
295
+ id: e.id,
296
+ port: e.port,
297
+ pid: e.pid,
298
+ profileDir: e.profileDir,
299
+ createdAt: e.createdAt,
300
+ mcp: e.mcpChild ? "child" : e.mcpInProcess ? "in-process" : "none",
301
+ mcpHealth: e.mcpHealth,
302
+ mcpError: e.mcpError
303
+ }));
304
+ }
305
+ peek(id) {
306
+ const e = state().entries.get(id);
307
+ if (!e) throw new BrowserRegistryRefusal("NO_SESSION", "no such browser session");
308
+ return e;
309
+ }
310
+ /** The brain's live SSE URL — the ACTUAL bound port (stable 9515 in the
311
+ * common case, session-relative in the rare fallback). */
312
+ mcpBrainUrl(id) {
313
+ const e = this.peek(id);
314
+ return "http://127.0.0.1:" + (e.mcpInProcess?.port ?? e.brainPort) + "/sse";
315
+ }
316
+ /** True when the id was closed (tombstoned) — routes use it to answer
317
+ * 409 CLOSED instead of a misleading 404. */
318
+ isClosed(id) {
319
+ return state().closed.has(id);
320
+ }
321
+ /** Re-bind lookup (ADR-0030 D1): does this persisted id still own a live
322
+ * session? Pure read — never creates, never throws. */
323
+ findLive(id) {
324
+ if (!id) return false;
325
+ return state().entries.has(id) && !state().closed.has(id);
326
+ }
327
+ /** Reaper inputs — the routes call these so the registry never imports a
328
+ * route (the wiring-point rule stays one-directional). */
329
+ noteStreamOpen(id) {
330
+ const e = state().entries.get(id);
331
+ if (e) e.streamSubscribers += 1;
332
+ }
333
+ noteStreamClose(id) {
334
+ const e = state().entries.get(id);
335
+ if (e) e.streamSubscribers = Math.max(0, e.streamSubscribers - 1);
336
+ }
337
+ noteMcpTraffic(id) {
338
+ const e = state().entries.get(id);
339
+ if (e) e.lastMcpActivity = Date.now();
340
+ }
341
+ /** The idle reaper (ADR-0030 D2): a SAFETY NET, never the owner. A
342
+ * session with zero stream subscribers and no MCP tool traffic for
343
+ * `browser.idleMs` is closed through the SAME idempotent close(id) the
344
+ * panel-close click uses. Headless-default makes this a correctness
345
+ * requirement: an invisible browser must not outlive its last driver. */
346
+ ensureReaper(idleMs) {
347
+ const s = state();
348
+ if (s.reaperTimer) return;
349
+ s.reaperTimer = setInterval(() => {
350
+ const now = Date.now();
351
+ for (const e of state().entries.values()) {
352
+ if (!reaperEligible(e, idleMs, now)) continue;
353
+ this.close(e.id).catch(() => void 0);
354
+ }
355
+ }, Math.min(idleMs / 2, 3e4));
356
+ s.reaperTimer.unref?.();
357
+ }
358
+ /** The ACTIVE tab's relay — what the stream route binds (ADR-0040 D2). */
359
+ relay(id) {
360
+ const e = this.peek(id);
361
+ const h = e.activeTargetId ? e.tabs.get(e.activeTargetId) : null;
362
+ if (!h) throw new BrowserRegistryRefusal("CLOSED", "no active tab handle");
363
+ return h.relay;
364
+ }
365
+ /** Resolve a verb's target handle: explicit targetId, else the active tab
366
+ * (ADR-0040 D3 — one verb seam, optional pointer). An ENUMERATED but
367
+ * not-yet-attached target attaches lazily here — attach is not stream
368
+ * (D1): verbs may reach any tab the strip can list. */
369
+ async handleOf(e, targetId) {
370
+ const key = targetId ?? e.activeTargetId ?? void 0;
371
+ if (!key) throw new BrowserRegistryRefusal("NO_TARGET", "no active tab");
372
+ const have = e.tabs.get(key);
373
+ if (have) return have;
374
+ for (let attempt = 0; attempt < 5 && !e.tabs.has(key); attempt += 1) {
375
+ if (attempt > 0) await new Promise((r) => setTimeout(r, 400));
376
+ for (const page of e.context.pages()) {
377
+ const scdp = await e.context.newCDPSession(page);
378
+ let tid = null;
379
+ try {
380
+ tid = (await scdp.send("Target.getTargetInfo")).targetInfo?.targetId ?? null;
381
+ } catch {}
382
+ if (!tid || e.tabs.has(tid)) {
383
+ await scdp.detach().catch(() => void 0);
384
+ continue;
385
+ }
386
+ const cfg = readBrowserConfig();
387
+ const handle = {
388
+ targetId: tid,
389
+ cdp: scdp,
390
+ relay: new BrowserRelay(scdp, cfg.screencastQuality, cfg.screencastMaxFps),
391
+ page
392
+ };
393
+ this.applyPanelViewport(e, handle).catch(() => void 0);
394
+ await scdp.send("Page.enable").catch(() => void 0);
395
+ await this.applyPanelViewport(e, {
396
+ cdp: scdp,
397
+ relay: handle.relay,
398
+ page
399
+ }).catch(() => void 0);
400
+ e.tabs.set(tid, handle);
401
+ if (tid === key) break;
402
+ }
403
+ }
404
+ const h = e.tabs.get(key);
405
+ if (!h) throw new BrowserRegistryRefusal("NO_TARGET", "no such tab: " + key);
406
+ return h;
407
+ }
408
+ /** Enumerate the context's page targets (ADR-0040 D5 feed) — type:page
409
+ * only; iframes/omnibox/service workers are chrome noise (wire capture
410
+ * 2026-10-24). Read-only: never attaches, never streams (D1). */
411
+ async listTabs(id) {
412
+ const e = this.peek(id);
413
+ const src = (e.activeTargetId ? e.tabs.get(e.activeTargetId) : null)?.cdp ?? [...e.tabs.values()][0]?.cdp;
414
+ if (!src) return [];
415
+ return ((await src.send("Target.getTargets").catch(() => null))?.targetInfos ?? []).filter((t) => t.type === "page").map((t) => ({
416
+ targetId: t.targetId,
417
+ url: t.url,
418
+ title: t.title,
419
+ active: t.targetId === e.activeTargetId
420
+ }));
421
+ }
422
+ /** Attach (lazily), seed the first frame, re-apply the viewport, and move
423
+ * the active pointer (ADR-0040 D1/D2/D4). The OLD active relay pauses —
424
+ * only the active tab streams. Returns the boundary payload. */
425
+ async activate(id, targetId) {
426
+ const e = this.peek(id);
427
+ if (e.closed) throw new BrowserRegistryRefusal("CLOSED", "session is closing");
428
+ const h = await this.handleOf(e, targetId);
429
+ const old = e.activeTargetId ? e.tabs.get(e.activeTargetId) : null;
430
+ if (old && old.targetId !== targetId) await old.relay.pause().catch(() => void 0);
431
+ await h.cdp.send("Page.enable").catch(() => void 0);
432
+ await this.applyPanelViewport(e, h);
433
+ await h.cdp.send("Page.bringToFront").catch(() => void 0);
434
+ await h.relay.ensureStreaming().catch(() => void 0);
435
+ if (h.relay.latestFrame() === null) for (let i = 0; i < 10 && h.relay.latestFrame() === null; i += 1) await new Promise((r) => setTimeout(r, 100));
436
+ if (h.relay.latestFrame() === null) {
437
+ const cfg = readBrowserConfig();
438
+ const shot = await h.cdp.send("Page.captureScreenshot", {
439
+ format: "jpeg",
440
+ quality: cfg.screencastQuality
441
+ }).catch(() => null);
442
+ if (shot?.data) h.relay.seed({
443
+ seq: 0,
444
+ jpeg: shot.data,
445
+ metadata: { seeded: true }
446
+ });
447
+ }
448
+ e.activeTargetId = targetId;
449
+ let url = "";
450
+ let title = "";
451
+ try {
452
+ const pi = await this.pageInfo(id, targetId);
453
+ url = pi.url;
454
+ title = pi.title;
455
+ } catch {}
456
+ return {
457
+ targetId,
458
+ seq: h.relay.latestFrame()?.seq ?? 0,
459
+ jpeg: h.relay.latestFrame()?.jpeg ?? null,
460
+ url,
461
+ title
462
+ };
463
+ }
464
+ async open(options = {}) {
465
+ const cfg = readBrowserConfig();
466
+ const id = randomUUID();
467
+ const port = freePort(options.port);
468
+ const profileDir = join(cfg.profileRoot, id.slice(0, 8));
469
+ mkdirSync(profileDir, { recursive: true });
470
+ const ignoreDefaultArgs = ["--enable-automation", "--mute-audio"];
471
+ const launch = (useChrome) => chromium.launchPersistentContext(profileDir, {
472
+ ...useChrome ? { channel: "chrome" } : {},
473
+ headless: options.headless ?? cfg.headless,
474
+ ignoreDefaultArgs,
475
+ args: [
476
+ "--remote-debugging-port=" + port,
477
+ "--no-first-run",
478
+ "--disable-blink-features=AutomationControlled",
479
+ "--disable-features=IsolateOrigins,site-per-process",
480
+ "--disable-dev-shm-usage",
481
+ "--disable-backgrounding-occluded-windows",
482
+ "--disable-renderer-backgrounding",
483
+ "--disable-background-timer-throttling",
484
+ "--autoplay-policy=no-user-gesture-required",
485
+ "--window-position=-32000,-32000",
486
+ "--window-size=" + (Math.max(200, Math.min(1920, options.width ?? 730)) + 6) + "," + (Math.max(120, Math.min(1080, options.height ?? 830)) + 70)
487
+ ],
488
+ viewport: options.headless ?? cfg.headless ? {
489
+ width: Math.max(200, Math.min(1920, options.width ?? 730)),
490
+ height: Math.max(120, Math.min(1080, options.height ?? 830))
491
+ } : null,
492
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
493
+ timezoneId: "America/New_York",
494
+ locale: "en-US"
495
+ });
496
+ let context;
497
+ try {
498
+ context = await launch(true);
499
+ } catch (chromeErr) {
500
+ context = await launch(false);
501
+ }
502
+ context.browser();
503
+ const pid = pidOfPort(port);
504
+ const cdp = await context.newCDPSession(context.pages()[0] ?? await context.newPage());
505
+ const relay = new BrowserRelay(cdp, cfg.screencastQuality, cfg.screencastMaxFps);
506
+ const tabs = /* @__PURE__ */ new Map();
507
+ let activeTargetId = null;
508
+ try {
509
+ activeTargetId = (await cdp.send("Target.getTargetInfo")).targetInfo?.targetId ?? null;
510
+ } catch {}
511
+ if (activeTargetId) tabs.set(activeTargetId, {
512
+ targetId: activeTargetId,
513
+ cdp,
514
+ relay,
515
+ page: context.pages()[0]
516
+ });
517
+ await relay.start();
518
+ const start = options.url ?? "data:text/html,<title>Glass Browser</title><body style=\"font-family:system-ui;color:gray;display:grid;place-items:center;height:100vh;margin:0\">Glass Browser — waiting for the agent</body>";
519
+ await cdp.send("Page.enable").catch(() => void 0);
520
+ await cdp.send("Page.navigate", { url: start }).catch(() => void 0);
521
+ await new Promise((r) => setTimeout(r, 600));
522
+ if (relay.latestFrame() === null) for (let i = 0; i < 10 && relay.latestFrame() === null; i += 1) await new Promise((r) => setTimeout(r, 100));
523
+ if (relay.latestFrame() === null) {
524
+ const shot = await cdp.send("Page.captureScreenshot", {
525
+ format: "jpeg",
526
+ quality: cfg.screencastQuality
527
+ }).catch(() => null);
528
+ if (shot) relay.seed({
529
+ seq: 0,
530
+ jpeg: shot.data,
531
+ metadata: { seeded: true }
532
+ });
533
+ }
534
+ const brainPort = Number(process.env.DSI_MCP_PORT ?? cfg.brainPort);
535
+ if (cfg.enabled) this.ensureReaper(cfg.idleMs);
536
+ const entry = {
537
+ id,
538
+ context,
539
+ tabs,
540
+ activeTargetId,
541
+ viewport: {
542
+ width: Math.max(200, Math.min(1920, options.width ?? 730)),
543
+ height: Math.max(120, Math.min(1080, options.height ?? 830))
544
+ },
545
+ headless: options.headless ?? cfg.headless,
546
+ port,
547
+ pid,
548
+ profileDir,
549
+ brainPort,
550
+ streamSubscribers: 0,
551
+ lastMcpActivity: Date.now(),
552
+ mcpChild: null,
553
+ mcpInProcess: null,
554
+ mcpHealth: "up",
555
+ mcpError: null,
556
+ closed: false,
557
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
558
+ };
559
+ state().entries.set(id, entry);
560
+ if (options.spawnMcp ?? true) {
561
+ if (process.env.DSI_MCP_IN_PROCESS === "1") {
562
+ evictBrainPort(brainPort, id);
563
+ try {
564
+ entry.mcpInProcess = await startInProcessMcp(entry.port, brainPort, () => {
565
+ entry.lastMcpActivity = Date.now();
566
+ });
567
+ } catch (e) {
568
+ entry.mcpHealth = "down";
569
+ entry.mcpError = e.message;
570
+ }
571
+ } else this.spawnMcpChild(entry, cfg.mcpPin);
572
+ }
573
+ return {
574
+ id,
575
+ port,
576
+ pid,
577
+ profileDir,
578
+ createdAt: entry.createdAt,
579
+ mcp: entry.mcpChild ? "child" : entry.mcpInProcess ? "in-process" : "none",
580
+ mcpHealth: entry.mcpHealth,
581
+ mcpError: entry.mcpError
582
+ };
583
+ }
584
+ /** Wave 3 (3.1) owns the real arg matrix; Wave 1 wires the spawn so close
585
+ * ordering (mcp child → cdp → browser) is pinned from day one. */
586
+ spawnMcpChild(entry, mcpPin) {
587
+ const child = spawn("npx", [
588
+ "@playwright/mcp@" + mcpPin,
589
+ "--cdp-endpoint",
590
+ "http://127.0.0.1:" + entry.port
591
+ ], {
592
+ stdio: "ignore",
593
+ detached: false
594
+ });
595
+ entry.mcpChild = child;
596
+ child.on("error", (e) => {
597
+ entry.mcpHealth = "down";
598
+ entry.mcpError = String(e);
599
+ });
600
+ child.on("exit", (code) => {
601
+ if (entry.mcpChild === child) {
602
+ entry.mcpHealth = "down";
603
+ entry.mcpError = "mcp child exited code " + code;
604
+ }
605
+ });
606
+ }
607
+ /** D8 owner-release. Idempotent: closing a closed id resolves cleanly. */
608
+ async close(id) {
609
+ const entry = state().entries.get(id);
610
+ if (!entry) return {
611
+ ok: true,
612
+ alreadyClosed: true
613
+ };
614
+ if (entry.closed) {
615
+ state().entries.delete(id);
616
+ return {
617
+ ok: true,
618
+ alreadyClosed: true
619
+ };
620
+ }
621
+ entry.closed = true;
622
+ state().closed.add(id);
623
+ if (state().closed.size > 256) state().closed.delete(state().closed.values().next().value);
624
+ const errs = [];
625
+ if (entry.mcpInProcess) try {
626
+ const brain = entry.mcpInProcess;
627
+ await new Promise((res) => {
628
+ brain.httpServer?.closeAllConnections?.();
629
+ brain.httpServer?.close?.(() => res());
630
+ setTimeout(res, 2e3);
631
+ });
632
+ await brain.connection?.close?.();
633
+ entry.mcpInProcess = null;
634
+ } catch (e) {
635
+ errs.push(e);
636
+ }
637
+ if (entry.mcpChild?.pid) try {
638
+ entry.mcpChild.kill("SIGTERM");
639
+ } catch (e) {
640
+ errs.push(e);
641
+ }
642
+ try {
643
+ for (const h of entry.tabs.values()) h.relay.stop();
644
+ entry.tabs.clear();
645
+ } catch (e) {
646
+ errs.push(e);
647
+ }
648
+ try {
649
+ await entry.context.close();
650
+ } catch (e) {
651
+ errs.push(e);
652
+ }
653
+ try {
654
+ rmSync(entry.profileDir, {
655
+ recursive: true,
656
+ force: true
657
+ });
658
+ } catch (e) {
659
+ errs.push(e);
660
+ }
661
+ state().entries.delete(id);
662
+ return {
663
+ ok: errs.length === 0,
664
+ alreadyClosed: false
665
+ };
666
+ }
667
+ /** Wait for the page's next load event, capped — the navigate idiom
668
+ * (a send races the context teardown otherwise) shared by reload and
669
+ * history travel (ADR-0031 D3/D4). */
670
+ async waitLoad(h, capMs = 3e3) {
671
+ await new Promise((res) => {
672
+ const on = (p) => {
673
+ h.cdp.off("Page.loadEventFired", on);
674
+ res();
675
+ };
676
+ h.cdp.on("Page.loadEventFired", on);
677
+ setTimeout(res, capMs);
678
+ });
679
+ }
680
+ /** Navigate the session's active page — public because causing page
681
+ * damage is the only reliable way to make screencast emit a frame. */
682
+ async navigate(id, url, opts) {
683
+ const e = this.peek(id);
684
+ const h = await this.handleOf(e, opts?.targetId);
685
+ await h.cdp.send("Page.enable").catch(() => void 0);
686
+ if (opts?.waitLoad) {
687
+ const loaded = this.waitLoad(h);
688
+ await h.cdp.send("Page.navigate", { url });
689
+ await loaded;
690
+ return;
691
+ }
692
+ await h.cdp.send("Page.navigate", { url });
693
+ }
694
+ /** Match the page viewport to the panel's glass box (ADR-0031
695
+ * amendment 2): the screencast frame then equals the panel size, so
696
+ * the mirror shows content at native scale instead of zooming a
697
+ * fixed default viewport. CDP-side clamps keep hostile sizes out. */
698
+ async setViewport(id, width, height, targetId) {
699
+ console.log("[viewport] set", id.slice(0, 8), width + "x" + height, "target", targetId ?? "active");
700
+ const w = Math.max(200, Math.min(8192, Math.round(width)));
701
+ const h = Math.max(120, Math.min(8192, Math.round(height)));
702
+ const e = this.peek(id);
703
+ e.viewport = {
704
+ width: w,
705
+ height: h
706
+ };
707
+ const handle = await this.handleOf(e, targetId);
708
+ await handle.cdp.send("Page.enable").catch(() => void 0);
709
+ const prevSeq = handle.relay.latestFrame()?.seq ?? -1;
710
+ await this.applyPanelViewport(e, handle);
711
+ await this.seedAfterResize(handle, prevSeq).catch(() => void 0);
712
+ }
713
+ /** ADR-0041 D3: a resize must REPAINT, not wait for the next page
714
+ * change — the screencast speaks only on change, so a static page
715
+ * keeps the old-aspect frame letterboxed on the panel forever (the
716
+ * operator's black bands, 2026-10-25). Bounded grace for a FRESH
717
+ * frame (seq past prevSeq); silence answers with the deterministic
718
+ * captureScreenshot seed — activate()'s first-frame idiom re-fired
719
+ * for the resize path. Never hangs the verb past the grace. */
720
+ async seedAfterResize(handle, prevSeq) {
721
+ for (let i = 0; i < 10 && (handle.relay.latestFrame()?.seq ?? -1) === prevSeq; i += 1) await new Promise((r) => setTimeout(r, 100));
722
+ if ((handle.relay.latestFrame()?.seq ?? -1) !== prevSeq) return;
723
+ const cfg = readBrowserConfig();
724
+ const shot = await handle.cdp.send("Page.captureScreenshot", {
725
+ format: "jpeg",
726
+ quality: cfg.screencastQuality
727
+ }).catch(() => null);
728
+ if (shot?.data) handle.relay.seed({
729
+ seq: 0,
730
+ jpeg: shot.data,
731
+ metadata: {
732
+ seeded: true,
733
+ resize: true
734
+ }
735
+ });
736
+ }
737
+ /** The history position (ADR-0031): every proxy-verb answer carries it
738
+ * so the header's back/forward buttons stay honest at the ends. */
739
+ async navInfo(id, targetId) {
740
+ const e = this.peek(id);
741
+ const h = await this.handleOf(e, targetId);
742
+ await h.cdp.send("Page.enable").catch(() => void 0);
743
+ const hist = await h.cdp.send("Page.getNavigationHistory", {});
744
+ return {
745
+ currentIndex: hist.currentIndex,
746
+ entryCount: hist.entries.length
747
+ };
748
+ }
749
+ /** Reload the session's active page (ADR-0031 D4): Page.reload keeps
750
+ * the history entry, unlike re-navigating the current URL. */
751
+ async reload(id, targetId) {
752
+ const e = this.peek(id);
753
+ const h = await this.handleOf(e, targetId);
754
+ await h.cdp.send("Page.enable").catch(() => void 0);
755
+ const loaded = this.waitLoad(h);
756
+ await h.cdp.send("Page.reload", {});
757
+ await loaded;
758
+ return this.pageInfo(id, targetId);
759
+ }
760
+ /** Travel the browser's OWN back/forward list (ADR-0031 D3):
761
+ * Page.getNavigationHistory picks the entry, Page.navigateToHistoryEntry
762
+ * is the browser's travel verb — never Runtime.evaluate('history.back()'),
763
+ * which races the teardown and lies about the browser-level list.
764
+ * Bounds refusals keep the header buttons honest at the list ends. */
765
+ async pageHistory(id, dir, targetId) {
766
+ const e = this.peek(id);
767
+ const h = await this.handleOf(e, targetId);
768
+ await h.cdp.send("Page.enable").catch(() => void 0);
769
+ const hist = await h.cdp.send("Page.getNavigationHistory", {});
770
+ const target = dir === "back" ? hist.currentIndex - 1 : hist.currentIndex + 1;
771
+ if (target < 0 || target >= hist.entries.length) throw new BrowserRegistryRefusal("CLOSED", "HISTORY_END — cannot go " + dir + " from index " + hist.currentIndex + " of " + hist.entries.length);
772
+ const loaded = this.waitLoad(h);
773
+ await h.cdp.send("Page.navigateToHistoryEntry", { entryId: hist.entries[target].id });
774
+ await loaded;
775
+ return {
776
+ ...await this.pageInfo(id, targetId),
777
+ currentIndex: target,
778
+ entryCount: hist.entries.length
779
+ };
780
+ }
781
+ /** Race an evaluate against a cap — a hung evaluate must never wedge a
782
+ * route (the navigate-hang finding, spec W2 2.3 debugging). */
783
+ async evaluateCapped(cdp, expr, capMs = 3e3) {
784
+ let timer;
785
+ const cap = new Promise((res) => {
786
+ timer = setTimeout(() => res(null), capMs);
787
+ });
788
+ try {
789
+ const res = await Promise.race([cdp.send("Runtime.evaluate", {
790
+ expression: expr,
791
+ returnByValue: true
792
+ }), cap]);
793
+ return res ? String(res.result?.value ?? "") : null;
794
+ } finally {
795
+ if (timer) clearTimeout(timer);
796
+ }
797
+ }
798
+ /** The active page's url + title + inner viewport — the status strip's
799
+ * location read, the e2e's DOM-truth channel (the glass proves clicks
800
+ * by effects the page itself reports), and the viewport-follow witness
801
+ * (innerWidth/innerHeight prove the emulation landed, amend 2). */
802
+ async pageInfo(id, targetId) {
803
+ const e = this.peek(id);
804
+ const h = await this.handleOf(e, targetId);
805
+ const raw = await this.evaluateCapped(h.cdp, "JSON.stringify({ url: location.href, title: document.title, dpr: window.devicePixelRatio, innerWidth: window.innerWidth, innerHeight: window.innerHeight, playerError: (document.querySelector(\".ytp-error-content-wrap-reason, .ytp-error-content, [role=alert]\")?.textContent || \"\").trim() || null, mediaErrorCode: (document.querySelector(\"video\")?.error?.code) ?? null })", 3e3);
806
+ if (raw === null) return {
807
+ url: "(busy)",
808
+ title: "(busy)",
809
+ dpr: 1,
810
+ innerWidth: 0,
811
+ innerHeight: 0,
812
+ playerError: null,
813
+ mediaErrorCode: null
814
+ };
815
+ return JSON.parse(raw);
816
+ }
817
+ /** The page element under viewport coords — the glass context menu's
818
+ * data pass (BUGFIX 2026-10-25: Chrome's NATIVE right-click menu is
819
+ * browser UI and never renders in the screencast, so DSI supplies its
820
+ * own menu; this tells it what the right-click landed on). */
821
+ async elementAt(id, x, y, targetId) {
822
+ const e = this.peek(id);
823
+ const h = await this.handleOf(e, targetId);
824
+ const expr = "JSON.stringify((() => { const el = document.elementFromPoint(" + Number(x) + "," + Number(y) + "); if (!el) return { href: null, src: null, text: null }; const a = el.closest(\"a\"); const img = el.closest(\"img\"); return { href: a ? a.href : null, src: img ? (img.currentSrc || img.src) : null, text: (a && a.textContent || \"\").trim().slice(0, 80) || null }; })())";
825
+ const raw = await this.evaluateCapped(h.cdp, expr, 2e3);
826
+ if (raw === null) return {
827
+ href: null,
828
+ src: null,
829
+ text: null
830
+ };
831
+ try {
832
+ return JSON.parse(raw);
833
+ } catch {
834
+ return {
835
+ href: null,
836
+ src: null,
837
+ text: null
838
+ };
839
+ }
840
+ }
841
+ /** Open a NEW tab in the glass at `url` and make it the active face
842
+ * (the context menu's 'open in new tab' verbs). Returns the new tab. */
843
+ async openTab(id, url, opts) {
844
+ const e = this.peek(id);
845
+ if (e.closed) throw new BrowserRegistryRefusal("CLOSED", "session is closing");
846
+ const src = (e.activeTargetId ? e.tabs.get(e.activeTargetId) : null)?.cdp ?? [...e.tabs.values()][0]?.cdp;
847
+ if (!src) throw new BrowserRegistryRefusal("CLOSED", "no tab handle to create from");
848
+ const targetId = (await src.send("Target.createTarget", { url: "about:blank" }))?.targetId;
849
+ if (!targetId) throw new BrowserRegistryRefusal("NO_TARGET", "Target.createTarget returned no id");
850
+ await this.navigate(id, url, {
851
+ waitLoad: true,
852
+ targetId
853
+ });
854
+ if (opts?.activate ?? true) await this.activate(id, targetId);
855
+ const h = e.tabs.get(targetId);
856
+ const pi = await this.pageInfo(id, targetId).catch(() => ({
857
+ url,
858
+ title: ""
859
+ }));
860
+ return {
861
+ targetId,
862
+ seq: h?.relay.latestFrame()?.seq ?? 0,
863
+ jpeg: h?.relay.latestFrame()?.jpeg ?? null,
864
+ url: pi.url || url,
865
+ title: pi.title
866
+ };
867
+ }
868
+ /** Apply the remembered panel viewport by RESIZING THE WINDOW (round 10:
869
+ * emulation-on-headed renders the page centered in the big off-screen
870
+ * window — the small/cut-off mirror). Also clears any stale override. */
871
+ /** Resize the glass's WINDOW to the panel size and clear emulation.
872
+ * ROUND 10 (the REAL small/cut-off root cause, headed-proven):
873
+ * Emulation.setDeviceMetricsOverride on HEADED chrome renders the
874
+ * emulated viewport CENTERED INSIDE the physical off-screen window
875
+ * (black around it) and the screencast captures the whole window —
876
+ * the mirror shows a tiny page. Resizing the WINDOW itself makes the
877
+ * page fill it natively; the panel is the window's face (ADR-0029 D1).
878
+ * Re-asserted on every attach/switch/setViewport (round 11: something
879
+ * re-expands the window — the mirror shrinks again — so this is now
880
+ * idempotent and called from all three paths). */
881
+ async applyPanelViewport(e, handle) {
882
+ await handle.cdp.send("Page.enable").catch(() => void 0);
883
+ if (e.headless && handle.page) {
884
+ await Promise.race([handle.page.setViewportSize({
885
+ width: e.viewport.width,
886
+ height: e.viewport.height
887
+ }).catch(() => void 0), new Promise((res) => setTimeout(res, 2500))]);
888
+ return;
889
+ }
890
+ const race = async (p, fb) => await Promise.race([p.catch(() => fb), new Promise((res) => setTimeout(() => res(fb), 2500))]);
891
+ const anyCdp = handle.cdp;
892
+ const dims = await race(anyCdp.send("Runtime.evaluate", {
893
+ expression: "JSON.stringify({ oh: window.outerHeight - window.innerHeight, ow: window.outerWidth - window.innerWidth })",
894
+ returnByValue: true
895
+ }), null);
896
+ let chromeH = 0, chromeW = 0;
897
+ try {
898
+ const d = JSON.parse(dims && dims.result && dims.result.value || "{}");
899
+ chromeH = Number(d.oh) || 0;
900
+ chromeW = Number(d.ow) || 0;
901
+ } catch {}
902
+ const anyCdp2 = handle.cdp;
903
+ const win = await race(anyCdp2.send("Target.getWindowForTarget"), null);
904
+ if (win && win.windowId) {
905
+ await race(anyCdp2.send("Browser.setWindowBounds", {
906
+ windowId: win.windowId,
907
+ bounds: {
908
+ width: Math.max(200, e.viewport.width + chromeW),
909
+ height: Math.max(120, e.viewport.height + chromeH),
910
+ windowState: "normal"
911
+ }
912
+ }), null);
913
+ const check = await race(anyCdp2.send("Browser.getWindowForTarget", { targetId: e.activeTargetId }), null);
914
+ console.log("[window] resized ->", JSON.stringify(check && check.bounds ? check.bounds : check), "want", e.viewport.width + chromeW, "x", e.viewport.height + chromeH);
915
+ } else console.log("[window] no windowId — resize skipped (raced out)");
916
+ await race(anyCdp2.send("Emulation.clearDeviceMetricsOverride"), null);
917
+ }
918
+ /** Close ONE tab (the strip X): Target.closeTarget, stop its relay,
919
+ * drop the handle — and if it was the active face, the pointer moves
920
+ * to the first surviving tab (re-activated, first-frame contract
921
+ * re-fired). Closing the LAST tab is refused: the kill ladder owns
922
+ * session death (the trash is the operator-facing kill). */
923
+ async closeTab(id, targetId) {
924
+ const e = this.peek(id);
925
+ if (e.closed) throw new BrowserRegistryRefusal("CLOSED", "session is closing");
926
+ if (e.tabs.size <= 1) throw new BrowserRegistryRefusal("NO_TARGET", "cannot close the last tab — use the trash to close the glass");
927
+ const victim = e.tabs.get(targetId);
928
+ if (!victim) throw new BrowserRegistryRefusal("NO_TARGET", "no such tab: " + targetId);
929
+ victim.relay.stop();
930
+ e.tabs.delete(targetId);
931
+ await victim.cdp.send("Target.closeTarget", { targetId }).catch(() => void 0);
932
+ await victim.cdp.detach().catch(() => void 0);
933
+ if (e.activeTargetId === targetId) {
934
+ const next = [...e.tabs.keys()][0] ?? null;
935
+ e.activeTargetId = next;
936
+ if (next) await this.activate(id, next).catch(() => void 0);
937
+ else e.activeTargetId = null;
938
+ }
939
+ return {
940
+ ok: true,
941
+ activeTargetId: e.activeTargetId
942
+ };
943
+ }
944
+ async dispatch(id, input, targetId) {
945
+ if (!state().entries.has(id) && state().closed.has(id)) throw new BrowserRegistryRefusal("CLOSED", "session was closed");
946
+ const e = this.peek(id);
947
+ if (e.closed) throw new BrowserRegistryRefusal("CLOSED", "session is closing");
948
+ await (await this.handleOf(e, targetId)).relay.dispatch(input);
949
+ }
950
+ };
951
+ var browserRegistry = new BrowserRegistry();
952
+
953
+ export { BrowserRegistryRefusal as B, browserRegistry as b };
954
+ //# sourceMappingURL=registry.js-C2MdrfNv.js.map