dsh-browser-firefox 0.3.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/package.json ADDED
@@ -0,0 +1,98 @@
1
+ {
2
+ "name": "dsh-browser-firefox",
3
+ "description": "Firefox browser control for DeepSeek Harness: token-authenticated WebSocket bridge + text-first browser_* tools driving the user's own Firefox via the companion AMO extension",
4
+ "version": "0.3.0",
5
+ "author": "tuojc",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/tuojc/dsh-browser-firefox.git",
10
+ "directory": "plugin"
11
+ },
12
+ "homepage": "https://github.com/tuojc/dsh-browser-firefox",
13
+ "bugs": "https://github.com/tuojc/dsh-browser-firefox/issues",
14
+ "keywords": [
15
+ "dsh-plugin",
16
+ "deepseek-harness",
17
+ "firefox",
18
+ "browser-automation",
19
+ "webextension"
20
+ ],
21
+ "dsh": {
22
+ "bundle": {
23
+ "patch": "./cordis.patch.yml"
24
+ }
25
+ },
26
+ "type": "module",
27
+ "main": "lib/index.js",
28
+ "types": "lib/types/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./lib/types/index.d.ts",
32
+ "default": "./lib/index.js"
33
+ },
34
+ "./protocol": {
35
+ "types": "./lib/types/protocol.d.ts",
36
+ "default": "./lib/protocol.js"
37
+ },
38
+ "./invariant": {
39
+ "types": "./lib/types/invariant.d.ts",
40
+ "default": "./lib/invariant.js"
41
+ },
42
+ "./cordis.patch.yml": "./cordis.patch.yml",
43
+ "./src/*": "./src/*",
44
+ "./package.json": "./package.json"
45
+ },
46
+ "files": [
47
+ "lib/index.js",
48
+ "lib/invariant.js",
49
+ "lib/protocol.js",
50
+ "lib/types/**/*.d.ts",
51
+ "cordis.patch.yml",
52
+ "src"
53
+ ],
54
+ "peerDependencies": {
55
+ "@deepseek-ai/cordis": "^4.0.1",
56
+ "@deepseek-ai/dsh-host-apiproxy": "^0.1.0-rc.6",
57
+ "@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.6",
58
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
59
+ "@deepseek-ai/dsh-home-paths": "^0.1.0-rc.6",
60
+ "@deepseek-ai/dsh-tools": "^0.1.0-rc.6"
61
+ },
62
+ "dependencies": {
63
+ "@deepseek-ai/schemastery": "^3.18.1",
64
+ "ws": "^8.21.0"
65
+ },
66
+ "scripts": {
67
+ "test": "vitest run",
68
+ "typecheck": "tsc -b --pretty false",
69
+ "build": "tsc -b --pretty false && tsdown",
70
+ "prepublishOnly": "pnpm run build"
71
+ },
72
+ "devDependencies": {
73
+ "@deepseek-ai/cordis": "4.0.1",
74
+ "@deepseek-ai/cordis-plugin-include": "1.0.6",
75
+ "@deepseek-ai/cordis-plugin-loader": "1.0.2",
76
+ "@deepseek-ai/dsh-agent": "0.1.0-rc.6",
77
+ "@deepseek-ai/dsh-agent-loop": "0.1.0-rc.6",
78
+ "@deepseek-ai/dsh-host-apiproxy": "0.1.0-rc.6",
79
+ "@deepseek-ai/dsh-host-webserver": "0.1.0-rc.6",
80
+ "@deepseek-ai/dsh-invariants": "0.1.0-rc.6",
81
+ "@deepseek-ai/dsh-llm": "0.1.0-rc.6",
82
+ "@deepseek-ai/dsh-home-paths": "0.1.0-rc.6",
83
+ "@deepseek-ai/dsh-session": "0.1.0-rc.6",
84
+ "@deepseek-ai/dsh-storage": "0.1.0-rc.6",
85
+ "@deepseek-ai/dsh-storage-domain": "0.1.0-rc.6",
86
+ "@deepseek-ai/dsh-storage-json": "0.1.0-rc.6",
87
+ "@deepseek-ai/dsh-system-prompt": "0.1.0-rc.6",
88
+ "@deepseek-ai/dsh-tools": "0.1.0-rc.6",
89
+ "@deepseek-ai/dsh-user-questions": "0.1.0-rc.6",
90
+ "@deepseek-ai/dsh-workspace": "0.1.0-rc.6",
91
+ "@types/node": "^22.20.0",
92
+ "@types/ws": "^8.18.1",
93
+ "playwright-core": "^1.61.1",
94
+ "tsdown": "0.22.2",
95
+ "typescript": "^6.0.3",
96
+ "vitest": "^4.1.8"
97
+ }
98
+ }
package/src/index.ts ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * `@deepseek-ai/dsh-bridge-browser`: token-authenticated WebSocket bridge for
3
+ * the browser extension plus the text-only `browser_*` tool set.
4
+ *
5
+ * The bridge mounts its own upgrade route (`/ext/bridge`) on the host
6
+ * webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
7
+ * authentication (first frame `hello` within HELLO_TIMEOUT_MS). Gateway RPCs
8
+ * from the extension are dispatched through the same fetch-shaped handler the
9
+ * /api carrier uses, and session events are pumped per connection. Tools
10
+ * execute by dispatching `tool.call` frames to the connected extension, which
11
+ * performs the action in the user's active tab.
12
+ *
13
+ * Opt-in by design: nothing is registered unless this plugin appears in the
14
+ * composition. No dsh core code is touched.
15
+ *
16
+ * @module @deepseek-ai/dsh-bridge-browser
17
+ */
18
+
19
+ import { randomUUID } from 'node:crypto'
20
+ import type { Context } from '@deepseek-ai/cordis'
21
+ import z from '@deepseek-ai/schemastery'
22
+ import type {} from '@deepseek-ai/dsh-tools'
23
+ import type {} from '@deepseek-ai/dsh-host-apiproxy'
24
+ import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
25
+ import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api'
26
+ import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api'
27
+ import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
28
+ import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
29
+ import { BridgeServer } from './server.ts'
30
+ import { registerBrowserTools } from './tools.ts'
31
+ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH } from './protocol.ts'
32
+ import { withSessionDeferral } from './session-deferral.ts'
33
+ import { withSessionWorkspace } from './session-workspace.ts'
34
+ import { resolveToken } from './token.ts'
35
+
36
+ /** Cordis plugin name used by loader diagnostics. */
37
+ export const name = 'bridge-browser'
38
+
39
+ /** Services required by this plugin. */
40
+ export const inject = ['webServer', 'apiProxy', 'tools']
41
+
42
+ /** Default per-tool-call budget (ms). */
43
+ const DEFAULT_TOOL_TIMEOUT_MS = 60_000
44
+
45
+ /** Default rendered-snapshot character budget (protects model context). */
46
+ const DEFAULT_SNAPSHOT_MAX_CHARS = 12_000
47
+
48
+ /** Default cap on interactive inventory items per snapshot. */
49
+ const DEFAULT_MAX_INTERACTIVE_ITEMS = 120
50
+
51
+ /** Default directory backing the browser extension's session group. */
52
+ const DEFAULT_SESSION_WORKSPACE_PATH = dshHomePath('browser-sessions')
53
+
54
+ /** Default: sessions materialize only on the first message (open-and-close leaves no trace). */
55
+ const DEFAULT_DEFER_SESSION_CREATE = true
56
+
57
+ /** Plugin config: deployment-varying tunables only; the wire contract stays fixed. */
58
+ export interface Config {
59
+ /** Fixed bearer token. When absent, a token is generated on first boot and persisted under the dsh home (0600). */
60
+ token?: string
61
+ /** Per-tool-call timeout in ms. Defaults to 60000. */
62
+ toolTimeoutMs?: number
63
+ /** Upper bound on one snapshot's rendered characters. Defaults to 12000. */
64
+ snapshotMaxChars?: number
65
+ /** Upper bound on interactive inventory items per snapshot. Defaults to 60. */
66
+ maxInteractiveItems?: number
67
+ /** Dedicated workspace path for extension-created sessions. Empty disables grouping. */
68
+ sessionWorkspacePath?: string
69
+ /** Defer real session creation until the first prompt. Defaults to true. */
70
+ deferSessionCreate?: boolean
71
+ }
72
+
73
+ export const Config: z<Config> = z.object({
74
+ token: z.string(),
75
+ toolTimeoutMs: z.number().step(1).min(1).default(DEFAULT_TOOL_TIMEOUT_MS),
76
+ snapshotMaxChars: z.number().step(1).min(1).default(DEFAULT_SNAPSHOT_MAX_CHARS),
77
+ maxInteractiveItems: z.number().step(1).min(1).default(DEFAULT_MAX_INTERACTIVE_ITEMS),
78
+ sessionWorkspacePath: z.string().default(DEFAULT_SESSION_WORKSPACE_PATH),
79
+ deferSessionCreate: z.boolean().default(DEFAULT_DEFER_SESSION_CREATE),
80
+ })
81
+
82
+ /** The shape after schemastery applies its defaults to every field. */
83
+ type ResolvedConfig = Required<Omit<Config, 'token'>> & Pick<Config, 'token'>
84
+
85
+ /** Configured budgets must be positive integers. Exported for validation tests. */
86
+ export function assertPositiveInteger(name: string, value: number): void {
87
+ if (!Number.isInteger(value) || value < 1) {
88
+ throw new Error(`bridge-browser: ${name} must be a positive integer`)
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Apply defaults and direct-call validation at the plugin boundary.
94
+ * @param config - Loader-resolved or directly supplied plugin configuration.
95
+ * @returns a complete configuration ready for runtime use.
96
+ */
97
+ export function resolveConfig(config: Config): ResolvedConfig {
98
+ const resolved: ResolvedConfig = {
99
+ ...(config.token === undefined ? {} : { token: config.token }),
100
+ toolTimeoutMs: config.toolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS,
101
+ snapshotMaxChars: config.snapshotMaxChars ?? DEFAULT_SNAPSHOT_MAX_CHARS,
102
+ maxInteractiveItems: config.maxInteractiveItems ?? DEFAULT_MAX_INTERACTIVE_ITEMS,
103
+ sessionWorkspacePath: config.sessionWorkspacePath ?? DEFAULT_SESSION_WORKSPACE_PATH,
104
+ deferSessionCreate: config.deferSessionCreate ?? DEFAULT_DEFER_SESSION_CREATE,
105
+ }
106
+ assertPositiveInteger('toolTimeoutMs', resolved.toolTimeoutMs)
107
+ assertPositiveInteger('snapshotMaxChars', resolved.snapshotMaxChars)
108
+ assertPositiveInteger('maxInteractiveItems', resolved.maxInteractiveItems)
109
+ return resolved
110
+ }
111
+
112
+ /**
113
+ * Mount the bridge: resolve the token, register the upgrade route, the tool
114
+ * set, and an optional system-prompt section, all effect-scoped for HMR.
115
+ *
116
+ * @param ctx - Cordis context.
117
+ * @param config - plugin config (schema defaults applied).
118
+ */
119
+ export async function apply(ctx: Context, config: Config): Promise<void> {
120
+ const resolved = resolveConfig(config)
121
+
122
+ const tokenRes = await resolveToken(resolved.token)
123
+ // Workspace grouping wraps the gateway create; session deferral wraps the
124
+ // result so materialization at first prompt still flows through grouping.
125
+ const api: ApiProxy = withSessionDeferral(
126
+ withSessionWorkspace(
127
+ ctx.apiProxy,
128
+ resolved.sessionWorkspacePath,
129
+ message => { ctx.logger.warn(message) },
130
+ ),
131
+ resolved.deferSessionCreate,
132
+ )
133
+ const server = new BridgeServer({
134
+ token: tokenRes.token,
135
+ apiHandler: toFetchHandler(api),
136
+ openEvents: (signal) => api.events.mux({ rpcId: RpcId(randomUUID()), payload: {} }, signal),
137
+ toolTimeoutMs: resolved.toolTimeoutMs,
138
+ caps: {
139
+ textOnly: true,
140
+ snapshotMaxChars: resolved.snapshotMaxChars,
141
+ maxInteractiveItems: resolved.maxInteractiveItems,
142
+ },
143
+ })
144
+
145
+ const route: WebUpgradeRoute = {
146
+ path: BRIDGE_PATH,
147
+ handler: (req, socket, head) => { server.handleUpgrade(req, socket, head) },
148
+ }
149
+ ctx.effect(() => ctx.webServer.registerUpgrade(route), 'bridge-browser: /ext/bridge upgrade route')
150
+ // 异步 disposer:HMR/卸载时先等桥完全关闭(socket/泵/acceptor 静默)再继续。
151
+ ctx.effect(() => () => server.close(), 'bridge-browser: bridge server')
152
+
153
+ // Zero-config discovery endpoint: the extension fetches this to learn the
154
+ // bridge WebSocket URL without any manual configuration. The URL carries no
155
+ // secret (loopback connections skip the token); non-loopback deployments
156
+ // keep requiring the token on the WS itself.
157
+ const configRoute: WebRoute = {
158
+ kind: 'exact',
159
+ path: BRIDGE_CONFIG_PATH,
160
+ handler: (_req, res) => {
161
+ res.writeHead(200, { 'content-type': 'application/json' })
162
+ res.end(JSON.stringify({ wsUrl: `ws://127.0.0.1:${ctx.webServer.port}${BRIDGE_PATH}` }))
163
+ },
164
+ }
165
+ ctx.effect(() => ctx.webServer.register(configRoute), 'bridge-browser: /ext/bridge-config route')
166
+
167
+ ctx.effect(() => {
168
+ const disposers = registerBrowserTools(ctx, server, {
169
+ toolTimeoutMs: resolved.toolTimeoutMs,
170
+ snapshotMaxChars: resolved.snapshotMaxChars,
171
+ maxInteractiveItems: resolved.maxInteractiveItems,
172
+ })
173
+ return () => { for (const dispose of disposers.values()) dispose() }
174
+ }, 'bridge-browser: browser tools')
175
+
176
+ // Optional system-prompt contribution: a one-line hint only — the model is
177
+ // told to fetch snapshots on demand instead of hoarding page text.
178
+ const systemPrompt = ctx.get('systemPrompt')
179
+ if (systemPrompt !== undefined) {
180
+ ctx.effect(() => systemPrompt.section({
181
+ name: 'tool:bridge-browser',
182
+ order: 107,
183
+ text: 'A browser bridge may be connected. To read or operate the user\'s active browser page, call browser_snapshot '
184
+ + '(text-only; numbered items are the click/type targets). Never assume page content you have not snapshot.',
185
+ }), 'bridge-browser: system prompt section')
186
+ }
187
+
188
+ ctx.logger.info(
189
+ tokenRes.generated
190
+ ? `browser bridge: new token generated and persisted at ${tokenRes.file} (chmod 0600); connect the extension and paste it in its settings`
191
+ : `browser bridge: using token from ${tokenRes.file}`,
192
+ )
193
+ ctx.logger.info(`browser bridge: listening on ${BRIDGE_PATH}`)
194
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Package-owned invariant companion for `@deepseek-ai/dsh-bridge-browser`.
3
+ * @module @deepseek-ai/dsh-bridge-browser/invariant
4
+ */
5
+
6
+ /* jscpd:ignore-start */
7
+ import type { Context } from '@deepseek-ai/cordis'
8
+ import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
9
+
10
+ const PACKAGE_NAME = '@deepseek-ai/dsh-bridge-browser'
11
+
12
+ /** Cordis companion plugin name. */
13
+ export const name = 'bridge-browser-invariant'
14
+ /** Service required before the companion can reserve package ownership. */
15
+ export const inject = ['invariants']
16
+
17
+ /**
18
+ * No runtime invariant: the bridge's connection registry and pending tool map
19
+ * are instance-private (no published event stream to assert against), and the
20
+ * wire contract is pinned by protocol.ts and covered by its unit tests. The
21
+ * tools are plain ctx.tools registrations observed by dsh-tools' own
22
+ * invariant.
23
+ */
24
+ const install: InvariantInstaller = () => {}
25
+
26
+ /**
27
+ * Register this package's invariant companion.
28
+ * @param ctx - Cordis context carrying the invariant service.
29
+ * @returns the installed registration's disposer after setup succeeds.
30
+ */
31
+ export const apply = (ctx: Context): Promise<() => void> =>
32
+ Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
33
+ /* jscpd:ignore-end */
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Wire contract between the dsh bridge plugin and the browser extension.
3
+ *
4
+ * Zero-dependency module (pure types, constants, and a parser): both the
5
+ * plugin (node) and the Chrome extension (browser bundle) import this file, so
6
+ * the frame shapes can never drift between the two halves.
7
+ *
8
+ * Frames are one JSON object per WebSocket message, discriminated by `t`.
9
+ * Correlation ids (`id`) are minted by the requestor and echoed by the
10
+ * responder; they are opaque strings, never parsed.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ /** WebSocket pathname the bridge plugin registers on the host webserver. */
16
+ export const BRIDGE_PATH = '/ext/bridge'
17
+
18
+ /** Zero-config discovery endpoint: returns `{ wsUrl }` for the extension. */
19
+ export const BRIDGE_CONFIG_PATH = '/ext/bridge-config'
20
+
21
+ /** Seconds a fresh socket may take to present `hello` before it is closed. */
22
+ export const HELLO_TIMEOUT_MS = 5_000
23
+
24
+ /** Server-side ping cadence; the client answers `pong` to prove liveness. */
25
+ export const PING_INTERVAL_MS = 30_000
26
+
27
+ /** Default bytes of the generated bearer token (256-bit). */
28
+ export const DEFAULT_TOKEN_BYTES = 32
29
+
30
+ /** Error codes a tool call may settle with. Open set: consumers must tolerate unknown codes. */
31
+ export type ToolErrorCode =
32
+ | 'no-active-tab'
33
+ | 'content-unavailable'
34
+ | 'action-failed'
35
+ | 'timeout'
36
+ | 'bridge-closed'
37
+ | 'bad-args'
38
+ | 'internal'
39
+
40
+ /** One tool-call failure: stable machine code plus human text for the model. */
41
+ export interface ToolError {
42
+ code: ToolErrorCode
43
+ message: string
44
+ }
45
+
46
+ /** Capabilities negotiated in `hello`/`hello.ok`. The extension performs its own actions; these bounds shape page snapshots. */
47
+ export interface BridgeCaps {
48
+ /** The extension renders page state as text only (no screenshots). */
49
+ textOnly: true
50
+ /** Upper bound on one rendered snapshot's characters (plugin config). */
51
+ snapshotMaxChars: number
52
+ /** Upper bound on interactive inventory items per snapshot (plugin config). */
53
+ maxInteractiveItems: number
54
+ }
55
+
56
+ /** Frames sent by the extension to the bridge plugin. */
57
+ export type ClientFrame =
58
+ /** First frame, within HELLO_TIMEOUT_MS of socket open. */
59
+ | { t: 'hello'; token: string; caps: BridgeCaps }
60
+ /** Unary gateway RPC passthrough (method names from the apiproxy RpcMethodMap). */
61
+ | { t: 'rpc'; id: string; method: string; payload: unknown }
62
+ /** Result of a previously dispatched tool call. */
63
+ | { t: 'tool.result'; id: string; ok: true; result: unknown }
64
+ | { t: 'tool.result'; id: string; ok: false; error: ToolError }
65
+ /** Liveness reply. */
66
+ | { t: 'pong' }
67
+
68
+ /** Frames sent by the bridge plugin to the extension. */
69
+ export type ServerFrame =
70
+ /** Accepted after a valid `hello`. */
71
+ | { t: 'hello.ok'; caps: BridgeCaps }
72
+ /** Reply to an `rpc` frame; `result` is the apiproxy ServerResponse envelope. */
73
+ | { t: 'rpc.result'; id: string; ok: true; result: unknown }
74
+ | { t: 'rpc.result'; id: string; ok: false; error: { code: string; message: string } }
75
+ /** One gateway event envelope (the same server-request shape the GUI's /api/events.mux carries). */
76
+ | { t: 'event'; frame: { rpcId: string; method: string; payload: unknown } }
77
+ /** A model-requested browser action to execute in the active tab. */
78
+ | { t: 'tool.call'; id: string; name: string; args: Record<string, unknown>; sessionId?: string; title?: string }
79
+ /** Liveness probe. */
80
+ | { t: 'ping' }
81
+ /** Fatal connection error; the client should re-authenticate. */
82
+ | { t: 'error'; code: string; message: string }
83
+
84
+ /** Any frame on the wire. */
85
+ export type BridgeFrame = ClientFrame | ServerFrame
86
+
87
+ /**
88
+ * Type guard: is this frame one the SERVER may send? Client-only shapes
89
+ * (hello/tool.result/pong) narrow out, so server-side consumers never
90
+ * dispatch on their own request vocabulary.
91
+ * @param frame - parsed frame.
92
+ * @returns true for server-sendable frames.
93
+ */
94
+ export function isServerFrame(frame: BridgeFrame): frame is ServerFrame {
95
+ return frame.t === 'hello.ok'
96
+ || frame.t === 'rpc.result'
97
+ || frame.t === 'event'
98
+ || frame.t === 'tool.call'
99
+ || frame.t === 'ping'
100
+ || frame.t === 'error'
101
+ }
102
+
103
+ /**
104
+ * Type guard: is this frame one the CLIENT may send? Server-only shapes
105
+ * narrow out, so client-side consumers never dispatch on server vocabulary.
106
+ * @param frame - parsed frame.
107
+ * @returns true for client-sendable frames.
108
+ */
109
+ export function isClientFrame(frame: BridgeFrame): frame is ClientFrame {
110
+ return frame.t === 'hello' || frame.t === 'rpc' || frame.t === 'tool.result' || frame.t === 'pong'
111
+ }
112
+
113
+ /**
114
+ * Parse one WebSocket message into a frame.
115
+ * @param text - raw message text.
116
+ * @returns the frame, or `undefined` when the message is not a valid frame.
117
+ */
118
+ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
119
+ let value: unknown
120
+ try {
121
+ value = JSON.parse(text)
122
+ } catch {
123
+ return undefined
124
+ }
125
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
126
+ const frame = value as Record<string, unknown>
127
+ if (typeof frame.t !== 'string') return undefined
128
+ switch (frame.t) {
129
+ case 'hello':
130
+ return typeof frame.token === 'string'
131
+ && isCaps(frame.caps)
132
+ ? { t: 'hello', token: frame.token, caps: frame.caps }
133
+ : undefined
134
+ case 'rpc':
135
+ return typeof frame.id === 'string' && typeof frame.method === 'string'
136
+ ? { t: 'rpc', id: frame.id, method: frame.method, payload: frame.payload }
137
+ : undefined
138
+ case 'tool.result':
139
+ if (typeof frame.id !== 'string') return undefined
140
+ if (frame.ok === true && 'result' in frame) {
141
+ return { t: 'tool.result', id: frame.id, ok: true, result: frame.result }
142
+ }
143
+ return isToolError(frame.error)
144
+ ? { t: 'tool.result', id: frame.id, ok: false, error: frame.error }
145
+ : undefined
146
+ case 'pong':
147
+ return { t: 'pong' }
148
+ case 'hello.ok':
149
+ return isCaps(frame.caps)
150
+ ? { t: 'hello.ok', caps: frame.caps }
151
+ : undefined
152
+ case 'rpc.result':
153
+ if (typeof frame.id !== 'string') return undefined
154
+ if (frame.ok === true && 'result' in frame) {
155
+ return { t: 'rpc.result', id: frame.id, ok: true, result: frame.result }
156
+ }
157
+ return typeof frame.error === 'object' && frame.error !== null
158
+ ? { t: 'rpc.result', id: frame.id, ok: false, error: frame.error as { code: string; message: string } }
159
+ : undefined
160
+ case 'event':
161
+ return typeof frame.frame === 'object' && frame.frame !== null
162
+ ? { t: 'event', frame: frame.frame as ServerFrame extends { t: 'event' } ? ServerFrame['frame'] : never }
163
+ : undefined
164
+ case 'tool.call':
165
+ return typeof frame.id === 'string' && typeof frame.name === 'string'
166
+ && typeof frame.args === 'object' && frame.args !== null && !Array.isArray(frame.args)
167
+ ? {
168
+ t: 'tool.call',
169
+ id: frame.id,
170
+ name: frame.name,
171
+ args: frame.args as Record<string, unknown>,
172
+ ...(typeof frame.sessionId === 'string' ? { sessionId: frame.sessionId } : {}),
173
+ ...(typeof frame.title === 'string' ? { title: frame.title } : {}),
174
+ }
175
+ : undefined
176
+ case 'ping':
177
+ return { t: 'ping' }
178
+ case 'error':
179
+ return typeof frame.code === 'string' && typeof frame.message === 'string'
180
+ ? { t: 'error', code: frame.code, message: frame.message }
181
+ : undefined
182
+ default:
183
+ return undefined
184
+ }
185
+ }
186
+
187
+ function isCaps(value: unknown): value is BridgeCaps {
188
+ if (typeof value !== 'object' || value === null) return false
189
+ const caps = value as Record<string, unknown>
190
+ return caps.textOnly === true
191
+ && typeof caps.snapshotMaxChars === 'number' && caps.snapshotMaxChars > 0
192
+ && typeof caps.maxInteractiveItems === 'number' && caps.maxInteractiveItems > 0
193
+ }
194
+
195
+ function isToolError(value: unknown): value is ToolError {
196
+ return typeof value === 'object' && value !== null
197
+ && typeof (value as Record<string, unknown>).code === 'string'
198
+ && typeof (value as Record<string, unknown>).message === 'string'
199
+ }