dsh-codex-style-computer-use 2.3.5 → 3.1.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.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the Apache License, Version 2.0.
4
+ * See lib/browser/APACHE-2.0.txt.
5
+ *
6
+ * Adapted from Playwright's packages/playwright-core/src/tools/mcp/browserModel.ts
7
+ * (via dsh-doyourweb 0.2.6 src/vendor/browser-model.js): types removed, errors
8
+ * propagated, and browser-created tabs disabled — this host controls ONLY the tab
9
+ * the user explicitly referenced, so `Target.createTarget` / `Target.closeTarget`
10
+ * (and therefore `browser.newPage()`, `page.close()`, and popups the page opens)
11
+ * are refused instead of silently reaching the user's browser.
12
+ *
13
+ * It is vendored rather than called because Playwright's own BrowserModel lives in
14
+ * the Playwright MCP server, not in playwright-core, and it opens tabs itself.
15
+ * What is needed here is the narrow adapter: Playwright speaks CDP over a
16
+ * WebSocket; the bridge owns no debugger port, so each CDP command is forwarded
17
+ * to the paired extension's `chrome.debugger` session for exactly one tab. This
18
+ * class is that translation, including the synthetic `Target.attachedToTarget`
19
+ * announcement Playwright requires before it creates a BrowserContext.
20
+ */
21
+
22
+ /** One debugger session per tab, keyed by the browser's numeric tab id. */
23
+ export class BrowserModel {
24
+ /** @param {(method: string, params: unknown) => Promise<unknown>} sendToExtension */
25
+ constructor (sendToExtension) {
26
+ this.sendToExtension = sendToExtension
27
+ this.sessions = new Map()
28
+ this.knownTabs = new Map()
29
+ this.nextSessionId = 1
30
+ this.autoAttach = false
31
+ this.emit = () => {}
32
+ }
33
+
34
+ /** Attach the outbound CDP sink once the relay WebSocket is accepted. */
35
+ connectOverCDP (emit) { this.emit = emit }
36
+
37
+ /** Register the referenced tab so `Target.setAutoAttach` can attach it. */
38
+ onTabCreated (tab) {
39
+ this.knownTabs.set(tab.id, tab)
40
+ if (this.autoAttach) return this.attachTab(tab.id)
41
+ }
42
+
43
+ onTabRemoved (tabId) {
44
+ this.knownTabs.delete(tabId)
45
+ this.detachTab(tabId)
46
+ }
47
+
48
+ /** Forward a debugger event to Playwright under the session it belongs to. */
49
+ onDebuggerEvent (source, method, params) {
50
+ const tab = this.sessions.get(source.tabId)
51
+ if (!tab) return
52
+ if (method === 'Target.attachedToTarget' && params?.sessionId) tab.children.add(params.sessionId)
53
+ if (method === 'Target.detachedFromTarget' && params?.sessionId) tab.children.delete(params.sessionId)
54
+ this.emit({ sessionId: source.sessionId || tab.sessionId, method, params })
55
+ }
56
+
57
+ onDebuggerDetach (source) { this.detachTab(source.tabId) }
58
+
59
+ async enableAutoAttach () {
60
+ this.autoAttach = true
61
+ for (const tabId of this.knownTabs.keys()) await this.attachTab(tabId)
62
+ }
63
+
64
+ async attachTab (tabId) {
65
+ if (this.sessions.has(tabId)) return this.sessions.get(tabId)
66
+ await this.sendToExtension('chrome.debugger.attach', [{ tabId }, '1.3'])
67
+ const { targetInfo } = await this.sendToExtension('chrome.debugger.sendCommand', [{ tabId }, 'Target.getTargetInfo'])
68
+ const tab = { tabId, sessionId: `pw-tab-${this.nextSessionId++}`, targetInfo, children: new Set() }
69
+ this.sessions.set(tabId, tab)
70
+ // Playwright creates a BrowserContext per attached target, so this synthetic
71
+ // announcement is what makes `browser.contexts()[0].pages()[0]` exist.
72
+ this.emit({ method: 'Target.attachedToTarget', params: {
73
+ sessionId: tab.sessionId, targetInfo: { ...targetInfo, attached: true }, waitingForDebugger: false,
74
+ } })
75
+ return tab
76
+ }
77
+
78
+ detachTab (tabId) {
79
+ const tab = this.sessions.get(tabId)
80
+ if (!tab) return
81
+ this.sessions.delete(tabId)
82
+ this.emit({ method: 'Target.detachedFromTarget', params: {
83
+ sessionId: tab.sessionId, targetId: tab.targetInfo?.targetId,
84
+ } })
85
+ }
86
+
87
+ /**
88
+ * Answer one CDP command.
89
+ *
90
+ * Commands that describe the bridge itself are answered locally; everything else
91
+ * is forwarded to the extension for the tab this session belongs to.
92
+ */
93
+ async command (method, params, sessionId) {
94
+ if (method === 'Browser.getVersion') {
95
+ return { protocolVersion: '1.3', product: 'Chrome/Extension-Bridge', userAgent: 'DSH/Browser-Bridge' }
96
+ }
97
+ if (method === 'Browser.setDownloadBehavior') return {}
98
+ if (method === 'Target.setAutoAttach' && !sessionId) { await this.enableAutoAttach(); return {} }
99
+ if (method === 'Target.createTarget' || method === 'Target.closeTarget') {
100
+ throw new Error('Only the explicitly referenced existing tab can be controlled; open or close tabs in the browser')
101
+ }
102
+ const top = [...this.sessions.values()].find(tab => tab.sessionId === sessionId)
103
+ if (method === 'Target.getTargetInfo' && top) return { targetInfo: top.targetInfo }
104
+ const tab = top || [...this.sessions.values()].find(tab => tab.children.has(sessionId)) ||
105
+ (!sessionId && this.sessions.values().next().value)
106
+ if (!tab) throw new Error('Browser tab is detached; reference the tab again to reconnect')
107
+ return this.sendToExtension('chrome.debugger.sendCommand', [
108
+ { tabId: tab.tabId, ...(sessionId && !top ? { sessionId } : {}) }, method, params,
109
+ ])
110
+ }
111
+ }
@@ -0,0 +1,126 @@
1
+ // lib/browser/pairing.js — extension identity and one-time pairing.
2
+ //
3
+ // 1. WHO MAY CONNECT AT ALL: a browser WebSocket always carries an `Origin` and
4
+ // a page cannot forge it, so `chrome-extension://<id>` is a real discriminator
5
+ // and an http(s) origin is refused outright. It is not trust on its own — a
6
+ // local process can write any header — which is why the token exists.
7
+ // 2. WHICH EXTENSION IS THE USER'S: the folder this package ships pins a public
8
+ // `key`, so its id is fixed for every install path on Chrome and Edge and the
9
+ // bridge knows the one origin it will trust before anyone connects. A folder
10
+ // without a key has no identity to trust and is refused at startup, rather
11
+ // than learning an identity from whoever asks first.
12
+ // 3. WHICH REQUEST THE HUMAN MEANT: a 6-digit code unique among pending requests
13
+ // is shown in the popup and listed on the setup page; the human approves the
14
+ // row that matches. The code is not a secret — identifying EXACTLY ONE request
15
+ // is what makes the comparison meaningful, since an impostor cannot display
16
+ // the genuine extension's code.
17
+
18
+ import { createHash, randomBytes, randomInt, randomUUID } from 'node:crypto'
19
+
20
+ /** Chrome extension ids: the first 16 bytes of SHA-256(key), hex folded to a-p. */
21
+ export function extensionId (key) {
22
+ return createHash('sha256').update(Buffer.from(key, 'base64')).digest('hex')
23
+ .slice(0, 32).replace(/[0-9a-f]/g, c => String.fromCharCode(97 + parseInt(c, 16)))
24
+ }
25
+
26
+ /** The id a manifest pins, or `undefined` when it pins none. */
27
+ export function pinnedExtensionId (manifest) {
28
+ return typeof manifest?.key === 'string' && manifest.key.length > 0 ? extensionId(manifest.key) : undefined
29
+ }
30
+
31
+ /** An Origin a browser can produce for an extension id. */
32
+ export function isExtensionOrigin (origin) {
33
+ return typeof origin === 'string' && /^chrome-extension:\/\/[a-p]{32}$/.test(origin)
34
+ }
35
+
36
+ export function newBridgeToken () {
37
+ return randomBytes(32).toString('hex')
38
+ }
39
+
40
+ export function validBridgeToken (value) {
41
+ return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value)
42
+ }
43
+
44
+ /**
45
+ * Pending pairing requests. Every method is synchronous on purpose: the bridge
46
+ * handles upgrades where an `await` would let a second request race the caps.
47
+ */
48
+ export class Pairings {
49
+ constructor ({
50
+ ttlMs = 120_000,
51
+ maxPending = 4,
52
+ maxRequestsPerWindow = 30,
53
+ now = () => Date.now(),
54
+ uuid = () => randomUUID(),
55
+ code = () => String(randomInt(0, 1_000_000)).padStart(6, '0'),
56
+ } = {}) {
57
+ this.ttlMs = ttlMs
58
+ this.maxPending = maxPending
59
+ this.maxRequestsPerWindow = maxRequestsPerWindow
60
+ this.now = now
61
+ this.uuid = uuid
62
+ this.code = code
63
+ this.pending = new Map()
64
+ this.issued = []
65
+ }
66
+
67
+ /** A code no other pending request shows, so a match identifies one row. */
68
+ uniqueCode () {
69
+ const shown = new Set([...this.pending.values()].map(entry => entry.code))
70
+ for (let attempt = 0; attempt < 100; attempt++) {
71
+ const candidate = this.code()
72
+ if (!shown.has(candidate)) return candidate
73
+ }
74
+ return undefined
75
+ }
76
+
77
+ request (socket, origin) {
78
+ this.prune()
79
+ if (this.pending.size >= this.maxPending) return undefined
80
+ const cutoff = this.now() - this.ttlMs
81
+ while (this.issued.length && this.issued[0] <= cutoff) this.issued.shift()
82
+ if (this.issued.length >= this.maxRequestsPerWindow) return undefined
83
+ const code = this.uniqueCode()
84
+ if (code === undefined) return undefined
85
+ this.issued.push(this.now())
86
+ const created = this.now()
87
+ const entry = { id: this.uuid().slice(0, 8), code, socket, origin, created, expires: created + this.ttlMs }
88
+ this.pending.set(entry.id, entry)
89
+ return entry
90
+ }
91
+
92
+ /** Live requests for the setup page. The origin is never exposed to the page. */
93
+ list () {
94
+ this.prune()
95
+ return [...this.pending.values()].map(({ id, code, created, expires }) => ({ id, code, created, expires }))
96
+ }
97
+
98
+ take (id) {
99
+ this.prune()
100
+ const entry = this.pending.get(id)
101
+ if (entry === undefined) return undefined
102
+ this.pending.delete(id)
103
+ return entry
104
+ }
105
+
106
+ drop (socket) {
107
+ for (const [id, entry] of this.pending) if (entry.socket === socket) this.pending.delete(id)
108
+ }
109
+
110
+ prune () {
111
+ const now = this.now()
112
+ for (const [id, entry] of this.pending) {
113
+ if (entry.expires > now) continue
114
+ this.pending.delete(id)
115
+ try { entry.socket.close(1000, 'Pairing expired') } catch { /* already gone */ }
116
+ }
117
+ }
118
+
119
+ clear () {
120
+ for (const entry of this.pending.values()) {
121
+ try { entry.socket.close(1000, 'Bridge stopped') } catch { /* already closed */ }
122
+ }
123
+ this.pending.clear()
124
+ this.issued.length = 0
125
+ }
126
+ }
@@ -0,0 +1,131 @@
1
+ // lib/browser/policy.js — the approval decision for the browser tools.
2
+ //
3
+ // THE CONTRACT IS THE SHARED ONE, AND THAT IS ENFORCED BY DELEGATION, NOT BY A COPY.
4
+ //
5
+ // A first version of this file re-implemented the mode switch, and an independent acceptance run
6
+ // caught the predictable consequence: for an unanswerable ask (`approvalPolicy:"never"`, full
7
+ // access) `standard` settled as `allow` while the desktop gate settles it as `deny`. Two switches
8
+ // that must agree will eventually disagree, so this file no longer owns a switch at all. A browser
9
+ // actuation is classified by asking lib/policy.js with the DESKTOP ANALOGUE of that action:
10
+ //
11
+ // * an ordinary actuation (`act`, `open`, `find`) asks `policyDecision('computer_click')` — a
12
+ // normal desktop click — so read-only/standard/autonomous/unrestricted and the whole
13
+ // applyApprovalChannel settlement (full-access standing grant, standard refusing, delegated
14
+ // children never inheriting) are inherited verbatim;
15
+ // * a HIGH-RISK step (upload/drop, which DISCLOSES a local file to a website) asks
16
+ // `policyDecision('computer_type', {allowPassword:true})` — the desktop profile of "always
17
+ // asks", even in autonomous — and inherits that settlement too.
18
+ //
19
+ // The mode text the caller sees is still browser-specific, so the refusal names the page operation
20
+ // rather than a click the model never asked for.
21
+ //
22
+ // OBSERVATION IS NOT ACTUATION. A batch made only of `wait` and `extract` reads the page without
23
+ // changing it, so read-only mode must allow it — the same rule the desktop side applies to
24
+ // observation tools. A batch that mixes in one write stays an actuation.
25
+
26
+ import { applyApprovalChannel, policyDecision } from '../policy.js'
27
+
28
+ export const BROWSER_READ_TOOLS = new Set([
29
+ 'computer_browser_read',
30
+ 'computer_browser_capture',
31
+ ])
32
+
33
+ export const BROWSER_ACT_TOOLS = new Set([
34
+ 'computer_browser_act',
35
+ 'computer_browser_open',
36
+ 'computer_browser_find',
37
+ ])
38
+
39
+ /** Steps that only READ: they issue no input and change no document. */
40
+ export const OBSERVATION_STEPS = new Set(['wait', 'extract'])
41
+
42
+ export const BROWSER_DISCLOSURE_NOTE = 'this step discloses a local file to a website (upload/drop) — ' +
43
+ 'normally requires human approval'
44
+
45
+ /** Which step in a batch makes it high risk, named so a refusal points at it. */
46
+ export function batchRisk (steps) {
47
+ const list = Array.isArray(steps) ? steps : []
48
+ for (let index = 0; index < list.length; index++) {
49
+ const step = list[index]
50
+ if (!step) continue
51
+ if (step.op === 'upload' || (step.op === 'drop' && Array.isArray(step.files) && step.files.length)) {
52
+ return { index, op: step.op, note: BROWSER_DISCLOSURE_NOTE }
53
+ }
54
+ }
55
+ return null
56
+ }
57
+
58
+ /** Is this batch pure observation (no input, no navigation, no disclosure)? */
59
+ export function isObservationBatch (steps) {
60
+ const list = Array.isArray(steps) ? steps : []
61
+ return list.length > 0 && list.every(step => step && OBSERVATION_STEPS.has(String(step.op || '')))
62
+ }
63
+
64
+ /** A one-line description of a batch for the approval card and the gate log. */
65
+ export function batchSummary (steps) {
66
+ const list = Array.isArray(steps) ? steps : []
67
+ const ops = list.map(step => String(step?.op || '?')).join(' → ')
68
+ const navigate = list.find(step => step?.op === 'navigate' && step.value)
69
+ return `${ops}${navigate ? ` [navigate=${String(navigate.value).slice(0, 120)}]` : ''}`.slice(0, 240)
70
+ }
71
+
72
+ /** The desktop action whose approval profile this browser operation shares. */
73
+ function analogue (_risk) {
74
+ // Kept as documentation of the delegation below; the switch itself lives in lib/policy.js.
75
+ return null
76
+ }
77
+
78
+ /**
79
+ * @param {string} name tool name
80
+ * @param {object} args tool arguments
81
+ * @param {'read-only'|'standard'|'autonomous'|'unrestricted'} mode
82
+ * @param {object} [approvalEnv] from lib/approval-env.js
83
+ * @returns {{kind:'allow'|'deny'|'ask', reason?:string}}
84
+ */
85
+ export function browserPolicyDecision (name, args, mode, approvalEnv) {
86
+ const a = args || {}
87
+ if (BROWSER_READ_TOOLS.has(name)) return { kind: 'allow' }
88
+ if (!BROWSER_ACT_TOOLS.has(name)) return { kind: 'deny', reason: `unknown browser tool: ${name}` }
89
+
90
+ const suffix = name === 'computer_browser_act' ? ` [${batchSummary(a.steps)}]`
91
+ : name === 'computer_browser_open' ? ` [url=${String(a.url || '').slice(0, 120)}]`
92
+ : name === 'computer_browser_find' ? ` [query=${String(a.query || '').slice(0, 80)}]`
93
+ : ''
94
+
95
+ // A pure wait/extract batch changes nothing, so it follows the OBSERVATION rule and is allowed
96
+ // even in read-only mode. This is the desktop side's own distinction (a batch drives only when
97
+ // something inside it drives), applied to the browser's step vocabulary.
98
+ if (name === 'computer_browser_act' && isObservationBatch(a.steps)) {
99
+ return { kind: 'allow', reason: 'observation-only batch (wait/extract): reads the page, changes nothing' }
100
+ }
101
+
102
+ const risk = name === 'computer_browser_act' ? batchRisk(a.steps) : null
103
+ // DELEGATED to the shared classifier: same switch, same applyApprovalChannel settlement.
104
+ const shared = risk
105
+ ? policyDecision('computer_type', { text: 'x', allowPassword: true }, mode, approvalEnv)
106
+ : policyDecision('computer_click', {}, mode, approvalEnv)
107
+
108
+ if (shared.kind === 'allow') return shared.reason ? { kind: 'allow', reason: shared.reason } : { kind: 'allow' }
109
+
110
+ // Re-label with the browser operation so the human/model reads WHAT was refused, while KEEPING
111
+ // the shared verdict's settlement text verbatim (it names the approval channel and who was not
112
+ // asked). The settlement is whatever follows the classifying clause in the shared reason, so this
113
+ // never re-words a decision it did not make.
114
+ const browserReason = risk
115
+ ? `${risk.note}${suffix} [action[${risk.index}] ${risk.op}]`
116
+ : `browser action ${name}${suffix}`
117
+ const sharedReason = String(shared.reason || '')
118
+ const settlement = sharedReason.includes('; ')
119
+ ? sharedReason.slice(sharedReason.indexOf('; ') + 2).trim()
120
+ : ''
121
+ if (shared.kind === 'deny') {
122
+ if (mode === 'read-only' && !risk) {
123
+ return { kind: 'deny', reason: `automationMode=read-only: ${browserReason} changes the browser or widens access; read the page or run a wait/extract batch instead` }
124
+ }
125
+ return { kind: 'deny', reason: settlement ? `${browserReason}; ${settlement}` : browserReason }
126
+ }
127
+ return { kind: 'ask', reason: settlement ? `${browserReason}; ${settlement}` : browserReason }
128
+ }
129
+
130
+ /** Re-export so callers that already import this module need one fewer path. */
131
+ export { applyApprovalChannel }
@@ -0,0 +1,171 @@
1
+ // lib/browser/protocol.js — tab references and the URL contract.
2
+ //
3
+ // `dsh-browser://<profile>/<tabId>` is upstream DoYourWeb 0.2.6's reference
4
+ // scheme; hosts written against it keep working unchanged.
5
+ //
6
+ // THE URL POLICY IS THE AUTHORIZATION, not a cosmetic filter: a tab is an
7
+ // authenticated session to something, so `sessionWebUrl` is the ONE place that
8
+ // decides which pages this plugin may ever read or drive.
9
+ //
10
+ // Two classes of page are refused beyond the obvious ones:
11
+ // * THE HARNESS ITSELF. DSH serves its own UI over HTTP, and the bridge serves
12
+ // the pairing page. A tab on any of those origins is the control surface: a
13
+ // model that could drive it could approve its own approvals. `ports`
14
+ // therefore carries every protected host port, and any loopback page on one
15
+ // of them is refused — while an unrelated localhost dev server on another
16
+ // port stays usable, because that is ordinary web work.
17
+ // * LOCAL FILES THAT ARE NOT PAGES. `file:` is opt-in, and even then only an
18
+ // .html/.htm document ON THIS MACHINE qualifies: a UNC share
19
+ // (`file://server/share`), a directory, an executable, a script or a
20
+ // credential file is not a web page and must never become a browser target.
21
+ // A file page additionally requires the user's own browser grant ("Allow
22
+ // access to file URLs"), which the extension checks and reports.
23
+
24
+ import { timingSafeEqual } from 'node:crypto'
25
+
26
+ export const SCHEME = 'dsh-browser://'
27
+
28
+ /** Default bridge port. 43188 never collides with upstream's 43187. */
29
+ export const DEFAULT_PORT = 43188
30
+
31
+ /** Subprotocol name the extension offers. Distinct from upstream's on purpose. */
32
+ export const PROTOCOL_NAME = 'dsh-browser-cu'
33
+
34
+ /** Compatibility revision; a mismatch is a hint on the profile, never a refusal. */
35
+ export const bridgeProtocolRevision = 1
36
+
37
+ /** A local document that is actually a page. */
38
+ const LOCAL_DOCUMENT = /\.(?:html?|xhtml)$/i
39
+
40
+ export function validProfileId (value) {
41
+ return typeof value === 'string' && /^[a-z0-9-]{1,80}$/i.test(value)
42
+ }
43
+
44
+ export function tabRef (profile, tabId) {
45
+ if (!validProfileId(profile) || !Number.isSafeInteger(tabId) || tabId < 0) {
46
+ throw new Error('Invalid browser tab identity')
47
+ }
48
+ return `${SCHEME}${profile}/${tabId}`
49
+ }
50
+
51
+ export function parseRef (value) {
52
+ const match = typeof value === 'string' ? /^dsh-browser:\/\/([a-z0-9-]{1,80})\/(\d+)$/i.exec(value) : null
53
+ if (!match || !Number.isSafeInteger(Number(match[2]))) throw new Error('Invalid browser tab reference')
54
+ return { profile: match[1], tabId: Number(match[2]) }
55
+ }
56
+
57
+ /** Every distinct `dsh-browser://` reference in a message. */
58
+ export function mentions (text) {
59
+ return [...new Set(String(text ?? '').match(/dsh-browser:\/\/[a-z0-9-]{1,80}\/\d+/gi) ?? [])]
60
+ }
61
+
62
+ /** Constant-time secret comparison that never throws on a non-string. */
63
+ export function sameSecret (actual, expected) {
64
+ const a = Buffer.from(String(actual ?? ''), 'utf8')
65
+ const b = Buffer.from(String(expected ?? ''), 'utf8')
66
+ return a.length === b.length && a.length > 0 && timingSafeEqual(a, b)
67
+ }
68
+
69
+ export const normalizeBrowser = value => value === 'Edge' ? 'Edge' : 'Chrome'
70
+
71
+ /** Loopback spellings a browser reports, bracketed or bare. */
72
+ export function isLoopbackHost (host) {
73
+ const name = String(host ?? '').replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase()
74
+ return name === 'localhost' || name.endsWith('.localhost') || /^127\.\d+\.\d+\.\d+$/.test(name) ||
75
+ name === '0.0.0.0' || name === '::1' || name === '::'
76
+ }
77
+
78
+ function isWebStore (url) {
79
+ const host = url.hostname.replace(/\.$/, '').toLowerCase()
80
+ if (host === 'chromewebstore.google.com') return true
81
+ if (host === 'chrome.google.com' && /^\/webstore(?:\/|$)/i.test(url.pathname)) return true
82
+ if (host === 'microsoftedge.microsoft.com' && /^\/addons(?:\/|$)/i.test(url.pathname)) return true
83
+ return false
84
+ }
85
+
86
+ /** The port a URL addresses, defaulting by scheme. */
87
+ export function effectivePort (url) {
88
+ return Number(url.port || (url.protocol === 'https:' ? 443 : 80))
89
+ }
90
+
91
+ /**
92
+ * Is this a local HTML document, and nothing else?
93
+ *
94
+ * `file:///C:/x.html` yes. `file://server/share/x.html` (UNC) no — a network
95
+ * share is not a local page. `file:///C:/x.exe`, `file:///C:/dir/` and
96
+ * `file:///C:/` no — those are files and directories, not documents.
97
+ */
98
+ export function isLocalHtml (url) {
99
+ if (url.protocol !== 'file:') return false
100
+ // A non-empty host is a UNC path (file://server/share/manifest.json).
101
+ if (url.hostname !== '') return false
102
+ let pathname
103
+ try { pathname = decodeURIComponent(url.pathname) } catch { return false }
104
+ if (!pathname || pathname.endsWith('/') || pathname.endsWith('\\')) return false
105
+ if (pathname.includes('\0')) return false
106
+ // A bare drive root (`file:///D:`) is a directory, not a document.
107
+ if (/^\/?[a-z]:$/i.test(pathname)) return false
108
+ return LOCAL_DOCUMENT.test(pathname)
109
+ }
110
+
111
+ /**
112
+ * Normalise the second argument, which accepts either a single bridge port (the
113
+ * common call) or the full option object.
114
+ *
115
+ * @param {number|{port?: number, ports?: Iterable<number>, file?: boolean, allowFile?: boolean}} options
116
+ */
117
+ function urlOptions (options) {
118
+ if (typeof options === 'number') return { ports: [options], file: false }
119
+ const { port, ports, file, allowFile } = options ?? {}
120
+ const list = [...(ports ?? []), ...(port === undefined ? [] : [port])]
121
+ .map(Number).filter(value => Number.isSafeInteger(value) && value > 0)
122
+ return {
123
+ ports: [...new Set(list)],
124
+ // `allowFile` is the tab-listing setting; `file` is the per-URL opt-in. A page
125
+ // is a local document only when BOTH are true.
126
+ file: file === true && allowFile !== false,
127
+ }
128
+ }
129
+
130
+ /**
131
+ * The URL this plugin may open, list or control — or `null`.
132
+ *
133
+ * @param {string} value absolute URL
134
+ * @param {number|object} [options] a bridge port, or `{ports, file, allowFile}`
135
+ */
136
+ export function sessionWebUrl (value, options = {}) {
137
+ const { ports, file } = urlOptions(options)
138
+ let url
139
+ try { url = new URL(String(value ?? '')) } catch { return null }
140
+ // Credentials never travel through a browser reference.
141
+ if (url.username || url.password) return null
142
+ if (url.protocol === 'file:') return file && isLocalHtml(url) ? url : null
143
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
144
+ if (isWebStore(url)) return null
145
+ if (url.hostname.replace(/\.$/, '').toLowerCase() === 'passwords.google.com') return null
146
+ // The harness's own origin (and the bridge's pairing page) is the control
147
+ // surface and is never a browser target. Only the listed ports are guarded, so
148
+ // an unrelated localhost dev server stays usable.
149
+ if (isLoopbackHost(url.hostname) && ports.includes(effectivePort(url))) return null
150
+ return url
151
+ }
152
+
153
+ /** May this tab be listed / resolved, given the bridge's settings? */
154
+ export function allowedTabUrl (value, { port, ports = [], allowFile = true } = {}) {
155
+ return sessionWebUrl(value, { ports, port, file: allowFile }) !== null
156
+ }
157
+
158
+ /** Why a page was refused, in words a model can act on. */
159
+ export function urlRefusal (value, options = {}) {
160
+ let url
161
+ try { url = new URL(String(value ?? '')) } catch { return 'Not a valid absolute URL' }
162
+ if (url.protocol === 'file:') {
163
+ return isLocalHtml(url)
164
+ ? 'Local file pages are disabled in this plugin; enable "allow local HTML" or use an HTTP(S) page'
165
+ : 'Only a local .html/.htm document on this machine can be used — not a directory, executable, script or network share'
166
+ }
167
+ if (isLoopbackHost(url.hostname) && urlOptions(options).ports.includes(effectivePort(url))) {
168
+ return 'That page is the DSH control surface (or the browser pairing page) and is never a browser target'
169
+ }
170
+ return 'Only regular HTTP/HTTPS pages without credentials, or an .html page the user opened locally, can be used'
171
+ }
@@ -0,0 +1,82 @@
1
+ // lib/browser/schema.js — registry-ready JSON Schema for the browser tools.
2
+ //
3
+ // WHY THIS EXISTS (measured regression, 2026-11-28). The desktop tools are handed to
4
+ // `defineTool()` from `@deepseek-ai/dsh-tools`, which compiles their `parameters` PROPERTY MAP into
5
+ // the schema the registry actually serves. The browser tools were registered as raw definitions, so
6
+ // what reached `ctx.tools.register()` was still the property map — `{tab, snapshot, steps, …}` — a
7
+ // top-level object with no `type`, no `properties` and no `required`. On DSH 0.2.2-rc.5 the registry
8
+ // expects a registry-ready JSON Schema, so the projection was not a tool signature at all: a model
9
+ // saw undocumented parameters and an empty required list.
10
+ //
11
+ // TWO SOURCES OF TRUTH WOULD DRIFT, so this module keeps ONE: the property map stays the readable
12
+ // input (it is what `defineTool` wants too), and `toJsonSchema()` is the exact projection used when
13
+ // no compiler is available. When the real `defineTool` IS provided, its output is used instead —
14
+ // and `ensureObjectSchema()` checks it, so a compiler that returned a non-schema cannot silently
15
+ // reach the registry.
16
+
17
+ /** Property types this surface emits, and the JSON-Schema node each one becomes. */
18
+ function node (spec) {
19
+ const out = {}
20
+ const type = spec?.type
21
+ if (type === 'string') out.type = 'string'
22
+ else if (type === 'number' || type === 'integer') out.type = 'number'
23
+ else if (type === 'boolean') out.type = 'boolean'
24
+ else if (type === 'array') {
25
+ out.type = 'array'
26
+ out.items = spec.items ? node(spec.items) : { type: 'string' }
27
+ } else if (type === 'object') {
28
+ out.type = 'object'
29
+ const properties = {}
30
+ const required = []
31
+ for (const [key, child] of Object.entries(spec.properties ?? {})) {
32
+ properties[key] = node(child)
33
+ if (child?.required === true) required.push(key)
34
+ }
35
+ out.properties = properties
36
+ if (required.length) out.required = required
37
+ out.additionalProperties = spec.additionalProperties === true
38
+ } else {
39
+ // An undeclared type is a string: the model may still pass it and the tool validates.
40
+ out.type = 'string'
41
+ }
42
+ if (Array.isArray(spec?.enum) && spec.enum.length) out.enum = [...spec.enum]
43
+ if (typeof spec?.description === 'string' && spec.description) out.description = spec.description
44
+ return out
45
+ }
46
+
47
+ /**
48
+ * Project a property map into a registry-ready object schema.
49
+ *
50
+ * `required` on a property entry becomes the schema's `required` array; every other member is the
51
+ * JSON-Schema node for that property. `additionalProperties:false` is deliberate: an unknown
52
+ * argument is a mistake by the caller, not something to forward to a page.
53
+ */
54
+ export function toJsonSchema (parameters = {}) {
55
+ const properties = {}
56
+ const required = []
57
+ for (const [name, spec] of Object.entries(parameters ?? {})) {
58
+ properties[name] = node(spec)
59
+ if (spec?.required === true) required.push(name)
60
+ }
61
+ return { type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false }
62
+ }
63
+
64
+ /** Is this already a schema a registry can serve? */
65
+ export function isObjectSchema (value) {
66
+ return !!value && typeof value === 'object' && !Array.isArray(value) &&
67
+ value.type === 'object' && !!value.properties && typeof value.properties === 'object' &&
68
+ !Array.isArray(value.properties)
69
+ }
70
+
71
+ /**
72
+ * Guarantee `definition.parameters` is a servable schema.
73
+ *
74
+ * A compiler that returned something else is a bug in the wiring, not a reason to ship a tool with
75
+ * no signature: the property map is still at hand, so the projection is used and the failure is
76
+ * reported through `onProblem`.
77
+ */
78
+ export function ensureObjectSchema (definition, parameters, onProblem) {
79
+ if (isObjectSchema(definition?.parameters)) return definition
80
+ onProblem?.(`defineTool returned no usable object schema for ${definition?.name ?? 'a tool'}; projecting the property map instead`)
81
+ return { ...definition, parameters: toJsonSchema(parameters) }
82
+ }