dsh-embedded-browser-next 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/lazy.js ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Lazy tool registration: the browser tools appear only after the entry skill
3
+ * has been invoked.
4
+ *
5
+ * Tool schemas are billed on **every** request, while a skill's catalog entry is
6
+ * two lines and its body is read on demand. So the `browser_embedded_*`
7
+ * schemas stay unpublished until something proves the model is actually doing
8
+ * browser work: a successful `skill` tool call naming {@link SKILL_NAME}, a
9
+ * `/browser-use` user gesture, or a past invocation found in a session log.
10
+ *
11
+ * The reveal is host-wide, not per session: `ctx.tools.register` publishes into
12
+ * one registry that every session reads, so the first session to invoke the
13
+ * skill opens the gate for all of them. That matches the shape of the registry
14
+ * rather than inventing a per-session tool list nothing else understands.
15
+ *
16
+ * Reload safety (the failure mode that made the reference implementation
17
+ * disable this): unload/remount must not lose a gate that was already opened.
18
+ * A plugin that only listened for future events would stay silent for the rest
19
+ * of the process after a reload, because the invocation that opened it is in the
20
+ * past — so {@link armLazyTools} also replays every live session's log at arm
21
+ * time, and a session created later replays its own on `session/created`.
22
+ *
23
+ * @module dsh-embedded-browser/lazy
24
+ */
25
+
26
+ /**
27
+ * Directory name of the entry skill that gates these tools.
28
+ *
29
+ * `browser-use` is the routing skill: it decides between this plugin's channel
30
+ * and the BrowserSkill channel, and only the model that read it knows the
31
+ * browser tools exist. The name is duplicated here on purpose — the skill lives
32
+ * in the user's skill repository, not in this package, so there is nothing to
33
+ * import.
34
+ */
35
+ export const SKILL_NAME = 'browser-use'
36
+
37
+ /** Every tool name the gate publishes once it opens; for diagnostics only. */
38
+ export const TOOL_PREFIX = 'browser_embedded_'
39
+
40
+ /**
41
+ * Read the skill name out of a `skill` tool call's arguments.
42
+ *
43
+ * Tool arguments reach an event listener either already normalized into an
44
+ * object or still as the raw JSON string, so both shapes are accepted.
45
+ *
46
+ * @param args - the call's arguments, in either shape.
47
+ * @returns the skill name, or undefined when the payload does not name one.
48
+ */
49
+ function skillNameOf(args) {
50
+ if (typeof args === 'string') {
51
+ try {
52
+ return skillNameOf(JSON.parse(args))
53
+ } catch {
54
+ return undefined
55
+ }
56
+ }
57
+ if (typeof args === 'object' && args !== null && 'name' in args) {
58
+ const name = args.name
59
+ return typeof name === 'string' ? name : undefined
60
+ }
61
+ return undefined
62
+ }
63
+
64
+ /**
65
+ * Whether one session event is the `/browser-use` user gesture.
66
+ *
67
+ * A slash command arrives as an ordinary message whose source carries the skill
68
+ * identity, which is what makes it a skill invocation rather than prose.
69
+ *
70
+ * @param data - the event payload.
71
+ * @returns whether it invokes {@link SKILL_NAME}.
72
+ */
73
+ function isSkillInvocationMessage(data) {
74
+ if (typeof data !== 'object' || data === null) return false
75
+ const source = data.source
76
+ if (typeof source !== 'object' || source === null) return false
77
+ return source.kind === 'skill-invocation' && source.name === SKILL_NAME
78
+ }
79
+
80
+ /**
81
+ * Whether a durable session log already proves a successful invocation.
82
+ *
83
+ * A `tool/call` alone is not proof — the model may have named a skill that does
84
+ * not exist, or the call may have failed — so the matching `tool/result` must
85
+ * come back without an error. A slash-command message needs no pairing.
86
+ *
87
+ * @param events - the session's events, in log order.
88
+ * @returns whether the skill was successfully invoked at least once.
89
+ */
90
+ function hasSuccessfulSkillInvocation(events) {
91
+ if (!Array.isArray(events)) return false
92
+ const callIds = new Set()
93
+ for (const event of events) {
94
+ if (event?.type !== 'tool/call') continue
95
+ const data = event.data
96
+ if (data?.name === 'skill' && skillNameOf(data.arguments) === SKILL_NAME) callIds.add(data.callId)
97
+ }
98
+ for (const event of events) {
99
+ if (event?.type === 'tool/result') {
100
+ const message = event.data?.message
101
+ if (typeof message !== 'object' || message === null) continue
102
+ if (message.isError === false && callIds.has(message.callId)) return true
103
+ }
104
+ if (isSkillInvocationMessage(event?.data)) return true
105
+ }
106
+ return false
107
+ }
108
+
109
+ /**
110
+ * Publish the tool suite on first proof, and keep it published.
111
+ *
112
+ * @param ctx - host context whose fiber owns the listeners.
113
+ * @param registerSuite - registers every tool and returns one disposer.
114
+ * @param deps - logger for the failure path.
115
+ * @returns a disposer that removes the listeners and, if it opened, the suite.
116
+ */
117
+ export function armLazyTools(ctx, registerSuite, { logger } = {}) {
118
+ const warn = (message) => logger?.warn?.(message)
119
+ let suiteDisposer
120
+ const open = () => {
121
+ if (suiteDisposer !== undefined) return
122
+ try {
123
+ suiteDisposer = registerSuite()
124
+ } catch (error) {
125
+ suiteDisposer = undefined
126
+ warn(`lazy tool registration failed: ${error.message}`)
127
+ }
128
+ }
129
+
130
+ const disposers = []
131
+
132
+ // `tools/result` and `session/event` are scope-filtered by design (an
133
+ // agent-scoped listener sees only its own sessions), and an untagged listener
134
+ // is already admitted everywhere — `{ global: true }` states that on purpose
135
+ // rather than leaning on the default. The gate is host-wide, so it must not
136
+ // depend on which agent happened to emit.
137
+ const global = { global: true }
138
+
139
+ // Path 1: the model called the skill and the call succeeded.
140
+ disposers.push(
141
+ ctx.on(
142
+ 'tools/result',
143
+ (exec, result) => {
144
+ if (result?.isError === true) return
145
+ if (exec?.name !== 'skill') return
146
+ if (skillNameOf(exec.arguments) === SKILL_NAME) open()
147
+ },
148
+ global,
149
+ ),
150
+ )
151
+
152
+ // Path 2: the human typed `/browser-use`.
153
+ disposers.push(
154
+ ctx.on(
155
+ 'session/event',
156
+ (_session, event) => {
157
+ if (isSkillInvocationMessage(event?.data)) open()
158
+ },
159
+ global,
160
+ ),
161
+ )
162
+
163
+ // Replay: a reload must not lose a gate a *past* session already opened.
164
+ const scan = (session) => {
165
+ if (suiteDisposer !== undefined) return
166
+ try {
167
+ if (hasSuccessfulSkillInvocation(session?.events)) open()
168
+ } catch (error) {
169
+ warn(`lazy reveal scan failed: ${error.message}`)
170
+ }
171
+ }
172
+ disposers.push(ctx.on('session/created', (session) => scan(session), global))
173
+
174
+ // The replay reads the live session store, which may mount *after* this plugin
175
+ // (`ctx.get` at apply time would then find nothing and the reload path would be
176
+ // lost to composition order — the client half of this plugin hit exactly that
177
+ // bug on 2026-09-21). `ctx.inject` runs the callback as soon as the service
178
+ // exists, which is immediately when it already does. The injected fiber is a
179
+ // child of this context, so it is disposed with the gate.
180
+ ctx.inject(['sessions'], (sessionCtx) => {
181
+ try {
182
+ if (typeof sessionCtx.sessions.list !== 'function') return
183
+ for (const session of sessionCtx.sessions.list()) scan(session)
184
+ } catch (error) {
185
+ warn(`lazy reveal replay failed: ${error.message}`)
186
+ }
187
+ })
188
+
189
+ return () => {
190
+ for (const dispose of disposers.splice(0)) dispose()
191
+ suiteDisposer?.()
192
+ }
193
+ }
package/lib/mjpeg.js ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * One HTTP response that a panel renders with a plain `<img>`.
3
+ *
4
+ * The point is not the encoding. It is that **no JavaScript touches the pixels**.
5
+ * A `multipart/x-mixed-replace` response lets the browser's own image pipeline
6
+ * decode each part and composite it, so the panel's main thread stays free for
7
+ * input handling. The canvas path this replaces decoded and redrew every frame on
8
+ * that same thread, which is where the latency and the stutter came from.
9
+ *
10
+ * The sink deliberately implements the same tiny surface `ScreencastHub` already
11
+ * uses for WebSocket panels (`sendJson` / `sendBinary` / `bufferedAmount` /
12
+ * `on('close')`), so the hub does not need a second code path: an HTTP viewer and
13
+ * a WebSocket viewer are both just "a place frames go".
14
+ *
15
+ * It is receive-only. Input still travels over the session's WebSocket, because a
16
+ * replacement response has no upstream.
17
+ *
18
+ * @module dsh-embedded-browser/mjpeg
19
+ */
20
+
21
+ import { EventEmitter } from 'node:events'
22
+
23
+ /** Boundary token; unique per response so a stale reader cannot splice frames. */
24
+ let boundarySeq = 0
25
+
26
+ /**
27
+ * Stream JPEG frames to one `<img>` element.
28
+ */
29
+ export class MjpegSink extends EventEmitter {
30
+ /**
31
+ * @param options - the response to hold open, plus a debug logger.
32
+ */
33
+ constructor({ response, logger }) {
34
+ super()
35
+ this.response = response
36
+ this.logger = logger
37
+ this.boundary = `dsh-eb-${Date.now().toString(36)}-${(boundarySeq += 1)}`
38
+ /** Filled in by the hub, like a WebSocket connection's. */
39
+ this.sessionId = undefined
40
+ this.watching = false
41
+ this.focusedAt = 0
42
+ this.closed = false
43
+ this.frames = 0
44
+ this.bytes = 0
45
+ // A viewer closing its tab or navigating away is the normal way this ends, and
46
+ // Node reports it **asynchronously**: `response.write()` at that moment
47
+ // succeeds, and the broken pipe surfaces later as a `close`/`error` event on
48
+ // the response. `try/catch` around the write therefore cannot see it. Worse,
49
+ // an unhandled `error` on a ServerResponse is an uncaught exception — one
50
+ // panel being closed while frames were in flight could take the whole host
51
+ // down. The sink owns its own response, so it owns these two listeners.
52
+ this.onResponseClose = () => this.close()
53
+ this.onResponseError = (error) => {
54
+ this.logger?.debug?.(`mjpeg response error: ${error?.message ?? error}`)
55
+ this.close()
56
+ }
57
+ // Optional call: a real ServerResponse is always an emitter, but the sink is
58
+ // also exercised against minimal stand-ins in unit tests.
59
+ response.on?.('close', this.onResponseClose)
60
+ response.on?.('error', this.onResponseError)
61
+ this.open()
62
+ }
63
+
64
+ /** Bytes queued but not yet flushed — the hub drops frames above this. */
65
+ get bufferedAmount() {
66
+ return this.response.writableLength ?? 0
67
+ }
68
+
69
+ /** Start the multipart response so `<img>` shows a spinner, not an error. */
70
+ open() {
71
+ try {
72
+ this.response.writeHead(200, {
73
+ 'Content-Type': `multipart/x-mixed-replace; boundary=${this.boundary}`,
74
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
75
+ Pragma: 'no-cache',
76
+ Connection: 'keep-alive',
77
+ // A proxy that buffers would turn the stream into one giant image.
78
+ 'X-Accel-Buffering': 'no',
79
+ })
80
+ this.response.flushHeaders?.()
81
+ } catch (error) {
82
+ this.logger?.debug?.(`mjpeg open failed: ${error.message}`)
83
+ this.closed = true
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Control messages have no representation on a replacement stream.
89
+ *
90
+ * The panel still receives them over its WebSocket; this sink only carries
91
+ * pictures.
92
+ */
93
+ sendJson() {
94
+ return false
95
+ }
96
+
97
+ /**
98
+ * Write one JPEG as a multipart part.
99
+ *
100
+ * @param buffer - the encoded frame.
101
+ * @returns whether it was accepted.
102
+ */
103
+ sendBinary(buffer) {
104
+ if (this.closed) return false
105
+ // Corked so the five pieces leave as a single write. They are one image: a
106
+ // flush between `Content-Length` and the body would hand the panel's decoder
107
+ // a half-written part, and it would also cost four extra syscalls per frame —
108
+ // at 60 fps and 350 KB a frame, that is real time on the path that decides
109
+ // how quickly the picture follows the hand.
110
+ try {
111
+ this.response.cork?.()
112
+ } catch {
113
+ /* a stand-in response in tests may not implement cork */
114
+ }
115
+ try {
116
+ this.response.write(`--${this.boundary}\r\n`)
117
+ this.response.write('Content-Type: image/jpeg\r\n')
118
+ this.response.write(`Content-Length: ${buffer.length}\r\n\r\n`)
119
+ this.response.write(buffer)
120
+ this.response.write('\r\n')
121
+ this.frames += 1
122
+ this.bytes += buffer.length
123
+ return true
124
+ } catch (error) {
125
+ this.logger?.debug?.(`mjpeg write failed: ${error.message}`)
126
+ this.close()
127
+ return false
128
+ } finally {
129
+ try {
130
+ this.response.uncork?.()
131
+ } catch {
132
+ /* ditto */
133
+ }
134
+ }
135
+ }
136
+
137
+ /** End the response and tell the hub to recompute who owns the stream. */
138
+ close() {
139
+ if (this.closed) return
140
+ this.closed = true
141
+ try {
142
+ this.response.off?.('close', this.onResponseClose)
143
+ this.response.off?.('error', this.onResponseError)
144
+ } catch {
145
+ /* an already-detached emitter is fine */
146
+ }
147
+ try {
148
+ this.response.end()
149
+ } catch {
150
+ /* the peer may already be gone */
151
+ }
152
+ this.emit('close')
153
+ }
154
+ }
package/lib/paths.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Where the browser tools may read from and write to.
3
+ *
4
+ * A page is untrusted input, and `browser_embedded_upload` attaches a **local
5
+ * file** to it while `browser_embedded_download` decides where bytes land. Left
6
+ * unguarded, a prompt injection in a page could talk the agent into uploading
7
+ * `~/.ssh/id_rsa` (or a credentials store) and then fetching it back out, or
8
+ * overwrite a file anywhere the user can write.
9
+ *
10
+ * The rules here are deliberately narrow and mechanical:
11
+ *
12
+ * - an upload may not name a known credentials folder or a system root;
13
+ * - a download may only land under the plugin's own Downloads folder.
14
+ *
15
+ * They are enforced in the node half, before CDP ever sees the path, so the
16
+ * refusal is the same whether the call came from a tool or a panel route.
17
+ *
18
+ * @module dsh-embedded-browser/paths
19
+ */
20
+
21
+ import { homedir } from 'node:os'
22
+ import { join, resolve, sep } from 'node:path'
23
+
24
+ /**
25
+ * Directory names that hold credentials or agent state.
26
+ *
27
+ * Matched as a whole path segment at any depth: `…/.ssh/id_rsa` is refused, and
28
+ * so is a project folder that happens to be called `.dsh`.
29
+ */
30
+ const PROTECTED_SEGMENTS = ['.ssh', '.dsh', '.gemini', '.gnupg', '.aws', '.kube', '.docker']
31
+
32
+ /** Roots that belong to the operating system rather than to the human's files. */
33
+ function systemRoots() {
34
+ const candidates = [
35
+ process.env.SystemRoot,
36
+ process.env.windir,
37
+ process.env.ProgramFiles,
38
+ process.env['ProgramFiles(x86)'],
39
+ process.env.ProgramData,
40
+ ]
41
+ return candidates
42
+ .filter((value) => typeof value === 'string' && value.trim() !== '')
43
+ .map((value) => resolve(value).toLowerCase())
44
+ }
45
+
46
+ /** The one directory downloads may use. */
47
+ export function downloadRoot() {
48
+ return join(homedir(), 'Downloads', 'dsh-embedded-browser')
49
+ }
50
+
51
+ function absolute(value) {
52
+ return resolve(String(value)).toLowerCase()
53
+ }
54
+
55
+ /**
56
+ * Why this path may not be uploaded, or `undefined` when it is fine.
57
+ *
58
+ * @param path - the path a caller asked to attach to a file input.
59
+ */
60
+ export function uploadRefusal(path) {
61
+ if (typeof path !== 'string' || path.trim() === '') return 'the path is empty'
62
+ const resolved = absolute(path)
63
+ const segments = resolved.split(/[\\/]+/)
64
+ for (const name of PROTECTED_SEGMENTS) {
65
+ if (segments.includes(name)) return `${name} holds credentials or agent state, not page input`
66
+ }
67
+ for (const root of systemRoots()) {
68
+ if (resolved === root || resolved.startsWith(`${root}${sep}`) || resolved.startsWith(`${root}/`)) {
69
+ return 'it lives in an operating-system directory'
70
+ }
71
+ }
72
+ return undefined
73
+ }
74
+
75
+ /**
76
+ * Resolve an upload path, refusing the protected ones.
77
+ *
78
+ * @param path - the path a caller asked to attach to a file input.
79
+ * @returns the absolute path to give CDP.
80
+ */
81
+ export function assertUploadAllowed(path) {
82
+ const reason = uploadRefusal(path)
83
+ if (reason !== undefined) throw new Error(`refusing to upload ${path}: ${reason}`)
84
+ return resolve(String(path))
85
+ }
86
+
87
+ /**
88
+ * Resolve a download directory, refusing everything outside the default one.
89
+ *
90
+ * Omitting the value keeps the documented default; naming a directory that is
91
+ * not below it is an error rather than a silent clamp, because a tool call that
92
+ * writes somewhere else must not look like it succeeded.
93
+ *
94
+ * @param path - the `downloadPath` a caller passed, if any.
95
+ * @returns the directory to hand to `Browser.setDownloadBehavior`.
96
+ */
97
+ export function assertDownloadDir(path) {
98
+ const root = resolve(downloadRoot())
99
+ if (path === undefined || path === null || String(path).trim() === '') return root
100
+ const abs = resolve(String(path))
101
+ const rootKey = root.toLowerCase()
102
+ const absKey = abs.toLowerCase()
103
+ if (absKey !== rootKey && absKey.startsWith(`${rootKey}${sep}`) === false) {
104
+ throw new Error(`refusing to download to ${abs}: downloads stay under ${root} (omit downloadPath to use it)`)
105
+ }
106
+ return abs
107
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Residence policy: which conversation gets to keep a real browser, and when one
3
+ * is let go.
4
+ *
5
+ * The rule this module exists to enforce is narrow and absolute:
6
+ *
7
+ * > A browser is **either** the panel's real one **or** the headless tab for the
8
+ * > whole life of one job. It never changes sides in the middle.
9
+ *
10
+ * Changing sides mid-job is not a degradation, it is amnesia: the agent navigates,
11
+ * snapshots, then clicks against a page that does not exist in the tab it is now
12
+ * talking to. That failure has no error message — it just quietly acts on the
13
+ * wrong page, which is exactly the sort of bug that reads as "the model is dumb".
14
+ *
15
+ * So "save memory" may only ever mean **close the real browser**, never "switch to
16
+ * the other one". Closing is safe and reversible: the workspace partition outlives
17
+ * the guest (`DesktopBrowserGuests.release` keeps storage), so reopening restores
18
+ * every login; only the page has to load again.
19
+ *
20
+ * Five things keep a real browser alive:
21
+ *
22
+ * 1. **pinned** — the human ticked the box. Nothing automatic overrules this.
23
+ * 2. **in flight** — a tool call is using it right now.
24
+ * 3. **waiting on a person** — `ask_human` has not been answered.
25
+ * 4. **being watched** — the panel is on screen in front of someone.
26
+ * 5. **recently used** — within the idle window.
27
+ *
28
+ * Everything else is fair game for the sweeper.
29
+ *
30
+ * @module dsh-embedded-browser/residency
31
+ */
32
+
33
+ /** Default idle window before an unpinned browser is reclaimed, in minutes. */
34
+ export const DEFAULT_IDLE_MINUTES = 15
35
+
36
+ /** Default ceiling on concurrently kept real browsers. */
37
+ export const DEFAULT_MAX_LIVE = 3
38
+
39
+ /**
40
+ * What "the real browser" means for this deployment.
41
+ *
42
+ * - `always` — every conversation that touches the browser keeps a real one.
43
+ * - `on-demand` — a real one appears when used, and is reclaimed once idle.
44
+ * - `off` — never route to a real browser; the headless tab answers everything.
45
+ * Useful for unattended batch work where nothing is ever looked at.
46
+ */
47
+ export const MODES = ['always', 'on-demand', 'off']
48
+
49
+ /** Normalize a mode string, falling back to the safe default. */
50
+ export function normalizeMode(value) {
51
+ return MODES.includes(value) ? value : 'on-demand'
52
+ }
53
+
54
+ /** Clamp a number into `[min, max]`, treating non-numbers as the fallback. */
55
+ function clamp(value, min, max, fallback) {
56
+ const numeric = Number(value)
57
+ if (!Number.isFinite(numeric)) return fallback
58
+ return Math.min(max, Math.max(min, numeric))
59
+ }
60
+
61
+ /**
62
+ * Tracks per-session liveness and decides who gets reclaimed.
63
+ *
64
+ * This class holds no timers and touches no browser: it is a bookkeeper so the
65
+ * answer to "may this go?" can be unit-tested without an Electron around it.
66
+ */
67
+ export class Residency {
68
+ /**
69
+ * @param options - mode, idle window, ceiling, logger, and the reclaim callback.
70
+ */
71
+ constructor({ mode, idleMinutes, maxLive, logger, onReclaim } = {}) {
72
+ this.mode = normalizeMode(mode)
73
+ this.idleMs = clamp(idleMinutes, 0, 24 * 60, DEFAULT_IDLE_MINUTES) * 60_000
74
+ this.maxLive = Math.round(clamp(maxLive, 0, 64, DEFAULT_MAX_LIVE))
75
+ this.logger = logger
76
+ this.onReclaim = onReclaim ?? (() => {})
77
+
78
+ /** sessionId -> true when the human pinned it. */
79
+ this.pinned = new Set()
80
+ /** sessionId -> last time anything used it (ms). */
81
+ this.lastUsed = new Map()
82
+ /** sessionId -> number of tool calls currently inside it. */
83
+ this.inFlight = new Map()
84
+ }
85
+
86
+ /** Apply a settings change without dropping any live state. */
87
+ configure({ mode, idleMinutes, maxLive } = {}) {
88
+ if (mode !== undefined) this.mode = normalizeMode(mode)
89
+ if (idleMinutes !== undefined) this.idleMs = clamp(idleMinutes, 0, 24 * 60, DEFAULT_IDLE_MINUTES) * 60_000
90
+ if (maxLive !== undefined) this.maxLive = Math.round(clamp(maxLive, 0, 64, DEFAULT_MAX_LIVE))
91
+ }
92
+
93
+ /** Mark one session as used right now. */
94
+ touch(sessionId) {
95
+ if (typeof sessionId !== 'string' || sessionId === '') return
96
+ this.lastUsed.set(sessionId, Date.now())
97
+ }
98
+
99
+ /** A tool call entered this session: it must not be reclaimed until it leaves. */
100
+ enter(sessionId) {
101
+ if (typeof sessionId !== 'string' || sessionId === '') return
102
+ this.inFlight.set(sessionId, (this.inFlight.get(sessionId) ?? 0) + 1)
103
+ this.touch(sessionId)
104
+ }
105
+
106
+ /** A tool call left this session (always paired with {@link enter}). */
107
+ leave(sessionId) {
108
+ if (typeof sessionId !== 'string' || sessionId === '') return
109
+ const count = (this.inFlight.get(sessionId) ?? 1) - 1
110
+ if (count <= 0) this.inFlight.delete(sessionId)
111
+ else this.inFlight.set(sessionId, count)
112
+ this.touch(sessionId)
113
+ }
114
+
115
+ /** Whether a session is mid-call. */
116
+ busy(sessionId) {
117
+ return (this.inFlight.get(sessionId) ?? 0) > 0
118
+ }
119
+
120
+ /** Pin or unpin one session (the panel's tick box). */
121
+ setPinned(sessionId, pinned) {
122
+ if (typeof sessionId !== 'string' || sessionId === '') return false
123
+ if (pinned === true) this.pinned.add(sessionId)
124
+ else this.pinned.delete(sessionId)
125
+ this.touch(sessionId)
126
+ return this.pinned.has(sessionId)
127
+ }
128
+
129
+ /** Whether the human pinned this session. */
130
+ isPinned(sessionId) {
131
+ return this.pinned.has(sessionId)
132
+ }
133
+
134
+ /** Forget a session entirely (it was disposed or its browser closed). */
135
+ forget(sessionId) {
136
+ this.pinned.delete(sessionId)
137
+ this.lastUsed.delete(sessionId)
138
+ this.inFlight.delete(sessionId)
139
+ }
140
+
141
+ /**
142
+ * Whether this session should be driving a real panel browser.
143
+ *
144
+ * `off` is the one mode that refuses one outright; the other two both say yes
145
+ * once a guest exists, because "a guest exists" already means the panel is
146
+ * mounted. The difference between them is only *how long* it survives, which is
147
+ * {@link reap}'s business, not this predicate's.
148
+ */
149
+ wantsReal(guestReady) {
150
+ if (this.mode === 'off') return false
151
+ return guestReady === true
152
+ }
153
+
154
+ /**
155
+ * Choose the sessions to reclaim right now.
156
+ *
157
+ * @param state - live sessions (those with a mounted guest), plus the questions
158
+ * only the caller can answer: is a person waiting, is it on screen.
159
+ * @param now - clock injection for tests.
160
+ * @returns the session ids whose real browser should be closed.
161
+ */
162
+ reap({ live = [], hasPendingHuman = () => false, isWatching = () => false, now = Date.now() } = {}) {
163
+ const doomed = []
164
+ const survivors = []
165
+
166
+ for (const sessionId of live) {
167
+ if (this.mode === 'off') {
168
+ doomed.push(sessionId)
169
+ continue
170
+ }
171
+ if (this.mode === 'always') {
172
+ // Every conversation keeps its browser; the ceiling still applies, or
173
+ // `always` on a busy host is just an out-of-memory button.
174
+ survivors.push(sessionId)
175
+ continue
176
+ }
177
+ if (this.pinned.has(sessionId) === true) {
178
+ survivors.push(sessionId)
179
+ continue
180
+ }
181
+ // A call in flight, an unanswered hand-over, or a human looking at the page
182
+ // all mean the browser is *in use* — closing it there is the amnesia bug.
183
+ if (this.busy(sessionId) === true) {
184
+ survivors.push(sessionId)
185
+ continue
186
+ }
187
+ if (hasPendingHuman(sessionId) === true) {
188
+ survivors.push(sessionId)
189
+ continue
190
+ }
191
+ if (isWatching(sessionId) === true) {
192
+ survivors.push(sessionId)
193
+ continue
194
+ }
195
+ const used = this.lastUsed.get(sessionId)
196
+ // Never used and never touched: this is a freshly mounted panel whose guest
197
+ // has not been called yet, so treat "no record" as "just now" rather than as
198
+ // infinitely old.
199
+ const idleFor = used === undefined ? 0 : now - used
200
+ if (idleFor < this.idleMs) {
201
+ survivors.push(sessionId)
202
+ continue
203
+ }
204
+ doomed.push(sessionId)
205
+ }
206
+
207
+ // The ceiling is a separate, harsher rule: it applies to pinned sessions too,
208
+ // because "pinned" is a promise about *this* conversation, not a licence to
209
+ // hold every one of them forever. Oldest unpinned go first; if only pinned ones
210
+ // remain over the line, the oldest of those goes.
211
+ if (this.mode !== 'off' && this.maxLive > 0 && survivors.length > this.maxLive) {
212
+ const order = [...survivors].sort((a, b) => {
213
+ const pinA = this.pinned.has(a) ? 1 : 0
214
+ const pinB = this.pinned.has(b) ? 1 : 0
215
+ if (pinA !== pinB) return pinA - pinB
216
+ return (this.lastUsed.get(a) ?? 0) - (this.lastUsed.get(b) ?? 0)
217
+ })
218
+ const over = order.length - this.maxLive
219
+ for (let index = 0; index < over; index += 1) doomed.push(order[index])
220
+ }
221
+
222
+ return doomed
223
+ }
224
+
225
+ /** Human-readable snapshot for `/state` and the settings dialog. */
226
+ describe() {
227
+ return {
228
+ mode: this.mode,
229
+ idleMinutes: Math.round(this.idleMs / 60_000),
230
+ maxLive: this.maxLive,
231
+ pinned: [...this.pinned],
232
+ }
233
+ }
234
+ }