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,233 @@
1
+ // references.js — the HOST half of the `@` reference work (issue #1, item 26).
2
+ //
3
+ // WHAT THIS MODULE OWNS, AND WHAT IT DELIBERATELY DOES NOT
4
+ //
5
+ // * RUNNING-APPLICATION REFERENCES. The composer's @ menu can offer a running application's
6
+ // window. The browser cannot enumerate windows, so this module mounts one authenticated
7
+ // same-origin prefix and answers from the SAME ComputerUse instance the computer_* tools use:
8
+ // the worker's own filtered window inventory (it already hides its own indicator overlay,
9
+ // invisible windows and its own process). No second desktop driver exists here, and nothing in
10
+ // this file focuses, activates or clicks a window.
11
+ //
12
+ // THE READ IS PASSIVE (`cu.callPassive('windows')`, see lib/references-apps.js). `cu.call`
13
+ // signs every request as a cycle op, which made merely typing `@` light the native breathing
14
+ // border and arm the human monitors — a control cycle off a read, before the human had picked
15
+ // anything. Browsing, searching, picking and the send-time re-check are all reads and light
16
+ // nothing; the real computer_* call the human then makes is what opens the cycle.
17
+ //
18
+ // * THE FILE-CANDIDATE BALANCE. A workspace with more directories than the provider's result cap
19
+ // answered a bare `@` with nothing but folders; lib/references-files.js fixes that on the
20
+ // shipped `ctx.fileReferences` provider. No parallel search implementation is introduced.
21
+ //
22
+ // IT DOES NOT OWN THE BROWSER ROUTES. `/api/computer-use/browser/*` (list, access, setup, focus)
23
+ // belongs to lib/browser/host.js, which owns the bridge, the per-conversation window access and
24
+ // the tab citations. Registering the same prefix here would shadow that surface with a second,
25
+ // weaker implementation — so this module never mounts it and the client talks to exactly one
26
+ // owner per capability.
27
+ //
28
+ // ROUTES (same-origin, host-authenticated by `connection.requestRejection`):
29
+ //
30
+ // GET /api/computer-use/references/apps?q=<text> -> {apps[], total?, unavailable?}
31
+ // POST /api/computer-use/references/apps/resolve -> {ok, app, context} or {ok:false, code}
32
+ //
33
+ // Nothing here is model-visible: the routes feed the composer menu and the sidebar, and a pick
34
+ // only ever inserts a draft chip.
35
+ import { appContextText, createAppInventory } from './references-apps.js'
36
+ import { balanceFileReferences } from './references-files.js'
37
+
38
+ /** The one prefix this module owns. */
39
+ export const REFERENCES_API = '/api/computer-use/references'
40
+
41
+ const MAX_QUERY = 200
42
+ const MAX_BODY = 64 * 1024
43
+ const CANDIDATE_LIMIT = 40
44
+
45
+ const send = (res, code, body) => {
46
+ try {
47
+ res.statusCode = code
48
+ res.setHeader('content-type', 'application/json; charset=utf-8')
49
+ res.setHeader('cache-control', 'no-store')
50
+ res.end(JSON.stringify(body))
51
+ } catch { /* the socket may already be gone */ }
52
+ }
53
+
54
+ const text = (value, limit = MAX_QUERY) => (typeof value === 'string' ? value.slice(0, limit) : '')
55
+
56
+ const readable = error => text(error && (error.message || String(error)), 300)
57
+
58
+ function readBody (req, limit = MAX_BODY) {
59
+ return new Promise((resolve, reject) => {
60
+ const chunks = []
61
+ let size = 0
62
+ req.on('data', chunk => {
63
+ size += chunk.length
64
+ if (size > limit) { reject(new Error('request body too large')); req.destroy(); return }
65
+ chunks.push(chunk)
66
+ })
67
+ req.on('end', () => {
68
+ const raw = Buffer.concat(chunks).toString('utf8').trim()
69
+ if (!raw) { resolve({}); return }
70
+ try { resolve(JSON.parse(raw)) } catch (error) { reject(new Error('request body must be JSON')) }
71
+ })
72
+ req.on('error', reject)
73
+ })
74
+ }
75
+
76
+ /**
77
+ * Mount the reference routes and the file-candidate balance.
78
+ *
79
+ * @param {object} ctx the host plugin context (the same one `apply()` received)
80
+ * @param {{cu?: object, log?: object, config?: object, probe?: object, windows?: Function, alive?: Function}} deps
81
+ * `cu` is the live ComputerUse instance, `log` the plugin logger, `config` the validated plugin
82
+ * configuration (only `enabled` is read). `probe`/`windows`/`alive` exist ONLY so a regression test
83
+ * can drive the route with literals; production omits them and gets the real worker and PowerShell.
84
+ * @returns {{installed: boolean, routes: string[], inventory: object|null, dispose: () => void}}
85
+ */
86
+ export function installAppReferences (ctx, { cu, log, config, probe, windows, alive } = {}) {
87
+ const info = message => { try { log?.info?.(message) } catch { /* logging never breaks a route */ } }
88
+ const warn = message => { try { log?.warn?.(message) } catch { /* idem */ } }
89
+
90
+ let restoreFiles = () => {}
91
+ let restoreRoutes = () => {}
92
+ const result = { installed: false, routes: [REFERENCES_API], inventory: null, dispose: () => {} }
93
+
94
+ if (config && config.enabled === false) {
95
+ info('[computer-use] references: disabled by configuration')
96
+ return result
97
+ }
98
+
99
+ // ---- the shipped file-reference provider ---------------------------------------------------
100
+ try {
101
+ if (typeof ctx?.inject === 'function') {
102
+ ctx.inject(['fileReferences', 'workingDirectory'], sctx => {
103
+ restoreFiles = balanceFileReferences(sctx.fileReferences, sctx.workingDirectory)
104
+ if (typeof sctx.effect === 'function') sctx.effect(() => restoreFiles)
105
+ })
106
+ }
107
+ } catch (error) {
108
+ warn(`[computer-use] references: file-candidate balance not installed: ${readable(error)}`)
109
+ }
110
+
111
+ // ---- running applications -------------------------------------------------------------------
112
+ // One inventory per plugin instance: its runtime id is what every `dsh-app://` reference carries,
113
+ // so a reference minted before a reconnect still resolves to the same process generation.
114
+ // `probe` and `windows` are injection points: production passes neither, so the real PowerShell
115
+ // start-time probe and `cu.call('windows')` are used, while a regression test supplies literals and
116
+ // starts NO subprocess.
117
+ if (typeof cu?.call === 'function') {
118
+ try {
119
+ result.inventory = createAppInventory({
120
+ cu, log: warn,
121
+ ...(probe ? { probe } : {}),
122
+ ...(windows ? { windows } : {}),
123
+ ...(alive ? { alive } : {}),
124
+ })
125
+ info(`[computer-use] references: running-application inventory ${result.inventory.runtime}`)
126
+ } catch (error) {
127
+ warn(`[computer-use] references: application inventory unavailable: ${readable(error)}`)
128
+ }
129
+ } else {
130
+ // No native desktop component: the route still answers, with an explicit reason, so the sidebar
131
+ // shows "applications are unavailable" instead of a broken list.
132
+ warn('[computer-use] references: no ComputerUse instance supplied; application references will report unavailable')
133
+ }
134
+
135
+ async function handle (req, res) {
136
+ // The host's own fence, the same one the settings page and the browser routes use: a plain web
137
+ // page on the loopback address has no authenticated peer and is refused here.
138
+ let connection = null
139
+ try { connection = typeof ctx?.get === 'function' ? ctx.get('connection') : null } catch { connection = null }
140
+ if (!connection || typeof connection.requestRejection !== 'function') {
141
+ send(res, 403, { error: 'the host connection service is unavailable; reference routes need it' })
142
+ return
143
+ }
144
+ let rejection = null
145
+ try { rejection = connection.requestRejection(req) } catch { rejection = null }
146
+ if (rejection) { send(res, 403, { error: 'rejected by host', detail: String(rejection) }); return }
147
+
148
+ let url
149
+ try { url = new URL(req.url, 'http://127.0.0.1') } catch { send(res, 400, { error: 'bad request url' }); return }
150
+ const path = url.pathname.replace(/^\/api\/computer-use\/references\/?/, '').replace(/\/+$/, '')
151
+ const session = text(url.searchParams.get('session'), 200) || null
152
+ try {
153
+ if (path === 'apps' && req.method === 'GET') {
154
+ if (!result.inventory) { send(res, 200, { apps: [], unavailable: 'running-application inventory is unavailable' }); return }
155
+ try {
156
+ const listed = await result.inventory.list(text(url.searchParams.get('q')))
157
+ send(res, 200, { ...listed, apps: listed.apps.slice(0, CANDIDATE_LIMIT) })
158
+ } catch (error) {
159
+ send(res, 200, { apps: [], unavailable: readable(error) })
160
+ }
161
+ return
162
+ }
163
+ if (path === 'apps/resolve' && req.method === 'POST') {
164
+ const body = await readBody(req)
165
+ const ref = text(body.ref, 512)
166
+ if (!ref) { send(res, 400, { error: 'ref is required' }); return }
167
+ // The conversation is REQUIRED: a reference belongs to one session, and a resolve that
168
+ // cannot name it cannot establish, or re-check, that this human picked that window.
169
+ const pickSession = text(body.session, 200) || session
170
+ if (!pickSession) { send(res, 400, { error: 'session is required' }); return }
171
+ if (!result.inventory) {
172
+ send(res, 200, { ok: false, code: 'APP_INVENTORY_UNAVAILABLE', message: 'running-application inventory is unavailable' })
173
+ return
174
+ }
175
+ try {
176
+ const resolved = await result.inventory.resolve(ref)
177
+ // `pick: true` is sent only by the client's PICK path — after a human chose the row. A
178
+ // plain resolve (a chip preview, or the SEND-time re-check) still verifies identity, but it
179
+ // cannot by itself create a session reference, so a pasted or previewed mention never
180
+ // authorizes a window.
181
+ if (body.pick === true) result.inventory.recordPick(pickSession, ref)
182
+ const picked = result.inventory.pickedBy(pickSession, ref)
183
+ // A SEND of a chip this conversation never picked is refused: an unverified mention must
184
+ // not smuggle a window handle into the model's context.
185
+ if (body.pick !== true && !picked) {
186
+ send(res, 200, {
187
+ ok: false,
188
+ code: 'APP_REFERENCE_NOT_PICKED',
189
+ message: '这个应用引用不是在本会话里选择的;请重新用 @ 选择正在运行的应用',
190
+ })
191
+ return
192
+ }
193
+ send(res, 200, { ok: true, app: resolved, context: appContextText(resolved), picked })
194
+ } catch (error) {
195
+ // A refusal is DATA with a code the client turns into a blocked send; it is never a 200
196
+ // that carries a usable handle, and never an `ok:true` with partial fields.
197
+ send(res, 200, { ok: false, code: error?.code || 'APP_RESOLVE_FAILED', message: readable(error) })
198
+ }
199
+ return
200
+ }
201
+ send(res, 404, { error: 'unknown reference route', path })
202
+ } catch (error) {
203
+ send(res, 400, { error: readable(error) })
204
+ }
205
+ }
206
+
207
+ try {
208
+ if (typeof ctx?.inject === 'function') {
209
+ ctx.inject(['webServer'], sctx => {
210
+ try {
211
+ const dispose = sctx.webServer.register({ kind: 'prefix', path: REFERENCES_API, handler: (req, res) => { void handle(req, res) } })
212
+ restoreRoutes = () => { try { dispose?.() } catch { /* already gone */ } }
213
+ if (typeof sctx.effect === 'function') sctx.effect(() => restoreRoutes)
214
+ } catch (error) {
215
+ warn(`[computer-use] references routes not mounted: ${readable(error)}`)
216
+ }
217
+ })
218
+ } else {
219
+ warn('[computer-use] references routes not mounted: no ctx.inject on the host context')
220
+ }
221
+ } catch (error) {
222
+ warn(`[computer-use] references routes not mounted: ${readable(error)}`)
223
+ }
224
+
225
+ result.installed = true
226
+ result.dispose = () => {
227
+ try { restoreRoutes() } catch { /* already disposed */ }
228
+ restoreRoutes = () => {}
229
+ restoreFiles()
230
+ restoreFiles = () => {}
231
+ }
232
+ return result
233
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-codex-style-computer-use",
3
- "version": "2.3.5",
4
- "description": "Windows desktop automation for DeepSeek Harness. Discover actions per control, scroll to an exact percentage, switch views, and place the caret before or after matching text. Includes OCR and a prebuilt Windows worker.",
3
+ "version": "3.1.0",
4
+ "description": "Windows desktop and browser-tab automation for DeepSeek Harness: per-control actions, exact scrolling, OCR, and the app windows or web pages the user cites with @. Includes a prebuilt Windows worker.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "bin": {
@@ -43,6 +43,10 @@
43
43
  "@deepseek-ai/schemastery": "^3.0.0",
44
44
  "@deepseek-ai/dsh-scope": ">=0.0.1-rc.1 <0.1.0 || >=0.1.0-rc.1 <0.2.0-0 || >=0.2.0-rc.1"
45
45
  },
46
+ "dependencies": {
47
+ "playwright-core": "1.64.0",
48
+ "ws": "8.22.0"
49
+ },
46
50
  "peerDependenciesMeta": {
47
51
  "@deepseek-ai/cordis": {
48
52
  "optional": true
@@ -91,6 +95,7 @@
91
95
  },
92
96
  "scripts": {
93
97
  "test": "node scripts/check-behavior.mjs",
98
+ "test:browser-bridge": "node build/test-browser-bridge.mjs",
94
99
  "build:native": "node scripts/build-native.mjs",
95
100
  "verify:package": "node scripts/verify-package.mjs"
96
101
  },
@@ -5,6 +5,28 @@ import os from 'node:os'
5
5
  import path from 'node:path'
6
6
  import { spawn } from 'node:child_process'
7
7
  import { createHash } from 'node:crypto'
8
+ import { createRequire } from 'node:module'
9
+
10
+ /**
11
+ * The package.json of an installed dependency, resolved exactly as Node would from `packageRoot`.
12
+ *
13
+ * `require.resolve.paths` yields the real candidate directories (nested first, then every hoisted
14
+ * parent node_modules up the tree); `require.resolve(name + '/package.json')` then confirms which
15
+ * one the runtime would actually load — not merely which directory happens to exist. Returns
16
+ * undefined when the dependency is not installed at all, so the caller can fail loudly instead of
17
+ * silently borrowing a copy from somewhere else.
18
+ */
19
+ function resolveInstalled (requireFrom, name) {
20
+ try {
21
+ const manifest = requireFrom.resolve(`${name}/package.json`)
22
+ if (fs.existsSync(manifest)) return manifest
23
+ } catch { /* a package without an exported ./package.json falls back to the path walk below */ }
24
+ for (const dir of requireFrom.resolve.paths(name) ?? []) {
25
+ const manifest = path.join(dir, name, 'package.json')
26
+ if (fs.existsSync(manifest)) return manifest
27
+ }
28
+ return undefined
29
+ }
8
30
 
9
31
  const sourceRoot = path.resolve(import.meta.dirname, '..')
10
32
  const packageIndex = process.argv.indexOf('--package')
@@ -25,6 +47,25 @@ if (packageRoot) {
25
47
  fs.copyFileSync(path.join(sourceRoot, 'build', item.name), path.join(root, 'build', item.name))
26
48
  }
27
49
  fs.cpSync(path.join(sourceRoot, 'build/fixtures'), path.join(root, 'build/fixtures'), { recursive: true })
50
+ // The mirror this gate runs from is a copy, so its bare imports would resolve from the WRONG
51
+ // place. Resolve each DECLARED runtime dependency the way Node itself would from the real
52
+ // package location, then link that exact directory into the mirror. Only the package's own
53
+ // install tree is used — never the source checkout, never a global or a user cache — so the
54
+ // gate verifies the dependencies that were actually installed with the package, whether they
55
+ // are nested inside it or hoisted to a parent node_modules.
56
+ const declared = Object.keys(JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).dependencies ?? {})
57
+ if (declared.length) {
58
+ const requireFromPackage = createRequire(path.join(packageRoot, 'package.json'))
59
+ for (const name of declared) {
60
+ const manifest = resolveInstalled(requireFromPackage, name)
61
+ if (!manifest) throw Error(`the package declares "${name}" but it is not installed in the package's own tree.\n` +
62
+ `Install the package's dependencies before verifying it:\n npm install (in ${packageRoot})`)
63
+ const to = path.join(root, 'node_modules', name)
64
+ fs.mkdirSync(path.dirname(to), { recursive: true })
65
+ // A junction needs an absolute target and needs no elevation on Windows, unlike a file symlink.
66
+ fs.symlinkSync(path.dirname(manifest), to, 'junction')
67
+ }
68
+ }
28
69
  }
29
70
  const excluded = {
30
71
  'test-evidence-native.mjs': 'requires actual foreground SendInput and keyboard delivery; a never-activated private desktop cannot prove this physical-input property',
@@ -33,12 +74,31 @@ const excluded = {
33
74
  const reviewed = new Set([
34
75
  'action-feedback', 'agent-pointer', 'argument-recovery', 'approval-attribution', 'approval-channel', 'ask-invariants', 'ask-merge', 'ask-orphan', 'ask-release',
35
76
  'attention-native', 'attention', 'audit-completion', 'batch-coverage', 'buildusermessage', 'bundled-skill', 'client-export',
77
+ // Browser and reference partitions. Each is a pure Node test that starts no window, dispatches
78
+ // no input and touches no desktop, so it runs inside this gate:
79
+ // browser-bridge the real bridge over its own loopback port, driven by a synthetic WebSocket
80
+ // client (no browser, no extension, no CDP relay)
81
+ // browser-host the URL gate, citation grants, page-access guard and tool policy against a
82
+ // fake bridge and a fake Page
83
+ // browser-client the settings client bundle evaluated in a vm with a fake shell
84
+ // reference-* file/app candidate projection and the reference host, against fixtures
85
+ // Only browser-bridge needs installed packages (ws, playwright-core). Under --package they are
86
+ // resolved from the package's OWN install tree by Node's resolver (nested or hoisted), never
87
+ // taken from this checkout; see the copy block above.
88
+ 'browser-bridge', 'browser-host', 'browser-client',
89
+ 'reference-apps', 'reference-folders', 'reference-host',
36
90
  'coactive', 'compact-feedback', 'control-targets', 'core-system-recovery', 'cursor', 'cycle-completion',
37
91
  'cycle-no-timeout', 'cycle-open', 'desktop-acceptance-io', 'desktop-ownership', 'drag-options', 'evidence-protocol',
38
92
  'exit-coherence', 'feedback-cache-integration', 'feedback-policy', 'glow-pump', 'glow-visual', 'handoff-continuation',
39
93
  'handoff-lock', 'handoff-runtime', 'handoff-watchdog', 'host-gate', 'human-handoff', 'indicator-hold', 'input-stamp', 'key-command',
40
94
  'kickoff-focus', 'leave-timer', 'mcp-contracts', 'mcp-execution', 'modifier-vk', 'monitor-lifetime', 'native-hardening', 'native-respawn',
41
95
  'native-runtime', 'native-fault-lifecycle', 'observation-archive', 'observations', 'op-classification', 'pointer-lease', 'policy', 'preparation',
96
+ // The passive-read pair. `passive-owner` is a pure source/regex guard that starts nothing.
97
+ // `passive-owner-native` re-executes itself on the repository private non-input desktop
98
+ // (requirePrivateDesktop, exactly like uia-native and the other native cases below) and runs two
99
+ // real workers against the test-private DSH_COMPUTER_USE_OWNER_FILE; it dispatches no input beyond
100
+ // the `dryRun` shape that the ownership gate answers before dispatch. Measured: ~3 s, 8 assertions.
101
+ 'passive-owner', 'passive-owner-native',
42
102
  'release-channel', 'renders', 'root-integration', 'session-identity', 'skill-gate', 'steer-message-shape',
43
103
  'task-rules', 'terminal-cleanup', 'timeout-branch', 'turnend-agent', 'turnend-rootagent',
44
104
  'ui-geometry', 'uia-budget', 'uia-read-timeout', 'uia-native', 'uia-targets-native', 'verification-region', 'window-management-key',