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,586 @@
1
+ // references-apps.js — running-application references for the `@` menu.
2
+ //
3
+ // WHAT THIS OWNS
4
+ // A user picks a running application's WINDOW in the composer; the pick becomes one atomic
5
+ // reference in that conversation's draft, and nothing is sent, focused or driven. Later, that
6
+ // reference must resolve to the SAME window — or be refused — so an existing desktop tool
7
+ // (`computer_shot {hwnd}`, `computer_window`, `computer_uia`, `computer_ocr`) can act on it.
8
+ //
9
+ // WHY IDENTITY IS NOT JUST PID OR HWND
10
+ // Windows reuses both. A pid or handle that still "exists" after the app exited may belong to a
11
+ // completely different process, and two windows of the same app share a title and a pid. So a
12
+ // reference is bound to a TRIPLE, captured from the native worker's own window inventory
13
+ // (`cu.call('windows')`) plus the process's creation time:
14
+ //
15
+ // runtime (this host process) + pid + process start time + hwnd
16
+ //
17
+ // The runtime id is minted per plugin install, so a reference from an earlier DSH run can never
18
+ // resolve against a fresh one. Resolution re-enumerates and refuses on ANY of:
19
+ // * the window is gone -> APP_WINDOW_CLOSED
20
+ // * the pid/hwnd pair now names another -> APP_WINDOW_REPLACED
21
+ // window (class or process name changed)
22
+ // or the process start time changed
23
+ // * the process is gone -> APP_PROCESS_EXITED
24
+ // * the reference is unknown/from another -> APP_REFERENCE_STALE
25
+ // runtime
26
+ // * the start time could not be read at -> APP_IDENTITY_UNVERIFIED
27
+ // pick time or at resolve time
28
+ //
29
+ // The TITLE is deliberately NOT part of the identity: editing and saving a document changes it,
30
+ // while the window is the same one the human picked.
31
+ //
32
+ // START TIMES come from a bounded Windows probe, not from another desktop driver. It is one
33
+ // PowerShell round trip for the whole inventory (cached per pid), it is skipped entirely when the
34
+ // runtime cannot run it, and an unreadable start time is a REFUSAL rather than a weaker identity:
35
+ // `pid + hwnd` alone cannot tell a live window from a recycled pair, and an unverified handle must
36
+ // never reach a desktop tool.
37
+ //
38
+ // WINDOW ROWS are the native worker's own `windows` shape — `{hwnd, pid, process, title, class,
39
+ // rect, active, minimized}` (lib/core/worker.cs `WinDict`). There is no image path on those rows, so
40
+ // the probe's `path` is the only source of an executable path here.
41
+ import { createHash, randomUUID } from 'node:crypto'
42
+ import { execFile } from 'node:child_process'
43
+
44
+ /** Reference grammar shared with the client chip and with host-side mention parsers. */
45
+ export const APP_REF = /^dsh-app:\/\/([0-9a-f-]{36})\/([0-9a-f]{24})$/i
46
+
47
+ const WINDOW_TIMEOUT_MS = 4_000
48
+ const START_PROBE_TIMEOUT_MS = 4_000
49
+ const SNAPSHOT_TTL_MS = 1_500
50
+ const START_TTL_MS = 15_000
51
+ const KNOWN_LIMIT = 500
52
+
53
+ /** Shell surfaces that are "a window" to Windows but never an application to a person. */
54
+ const SHELL_PROCESSES = /^(?:shellexperiencehost|startmenuexperiencehost|searchhost|searchapp|textinputhost|widgets|widgetservice|widgetboard|lockapp|applicationframehost)$/i
55
+ const SHELL_CLASSES = /^(?:Progman|WorkerW|Shell_TrayWnd|Shell_SecondaryTrayWnd|tooltips_class32|MSCTFIME UI|IME|Windows\.UI\.CoreWindow)$/i
56
+
57
+ export function appError (code, message) {
58
+ const error = new Error(message)
59
+ error.code = code
60
+ return error
61
+ }
62
+
63
+ const clip = (value, limit) => {
64
+ const text = String(value == null ? '' : value)
65
+ return text.length <= limit ? text : text.slice(0, Math.max(0, limit - 1)) + '…'
66
+ }
67
+
68
+ /** The mention a chip's `ref` carries: the same shape DSH's own @ sources insert. */
69
+ export function formatAppMention (label, ref) {
70
+ const text = clip(String(label || '应用').replace(/[\[\]\\\r\n]/g, ' '), 128)
71
+ return `@[${text}](${ref})`
72
+ }
73
+
74
+ /** The `dsh-app://…` inside a mention (or the string itself when it is already a bare ref). */
75
+ export function appRefOf (value) {
76
+ const match = String(value == null ? '' : value).match(/dsh-app:\/\/[0-9a-f-]{36}\/[0-9a-f]{24}/i)
77
+ return match ? match[0] : null
78
+ }
79
+
80
+ function hashIdentity (parts) {
81
+ return createHash('sha256').update(parts.join('\u0000')).digest('hex').slice(0, 24)
82
+ }
83
+
84
+ /** Normalize one native window row; `undefined` when it is not a window a person can pick. */
85
+ export function normalizeWindowRow (row, { selfPid = process.pid, selfExe = process.execPath } = {}) {
86
+ if (!row || typeof row !== 'object') return undefined
87
+ const hwnd = Number(row.hwnd)
88
+ const pid = Number(row.pid)
89
+ if (!Number.isSafeInteger(hwnd) || hwnd <= 0) return undefined
90
+ if (!Number.isSafeInteger(pid) || pid <= 0) return undefined
91
+ const title = typeof row.title === 'string' ? row.title.trim() : ''
92
+ if (!title) return undefined
93
+ if (pid === selfPid) return undefined
94
+ const processName = typeof row.process === 'string' ? row.process : ''
95
+ // The native `windows` rows carry NO image path; a probe supplies one later. `exe` here is only a
96
+ // courtesy for a caller that already joined the two, so a missing value must not exclude a row.
97
+ const exe = typeof row.exe === 'string' && row.exe ? row.exe : ''
98
+ // THIS PLUGIN'S OWN WINDOWS ARE NEVER CANDIDATES. The pid test above covers this process; the
99
+ // executable test covers the other processes of the same application (Desktop's main/renderer/GPU
100
+ // are separate pids of one exe), which is the case the host guard exists for. When the row carries
101
+ // no image path — the production shape — the executable's BASENAME is compared against the
102
+ // process name, which is the only identity channel such a row has.
103
+ if (selfExe) {
104
+ const want = String(selfExe).toLowerCase()
105
+ if (exe && exe.toLowerCase() === want) return undefined
106
+ const base = want.replace(/^.*[\\/]/, '').replace(/\.exe$/, '')
107
+ if (base && processName.toLowerCase() === base) return undefined
108
+ }
109
+ if (SHELL_PROCESSES.test(processName)) return undefined
110
+ if (SHELL_CLASSES.test(typeof row.class === 'string' ? row.class : '')) return undefined
111
+ const rect = row.rect && typeof row.rect === 'object' ? row.rect : undefined
112
+ const minimized = row.minimized === true
113
+ if (rect && !minimized && (!(rect.width >= 64) || !(rect.height >= 32))) return undefined
114
+ return {
115
+ hwnd,
116
+ pid,
117
+ title,
118
+ process: processName,
119
+ exe,
120
+ class: typeof row.class === 'string' ? row.class : '',
121
+ minimized,
122
+ active: row.active === true,
123
+ rect: rect ? { x: Number(rect.x) || 0, y: Number(rect.y) || 0, width: Number(rect.width) || 0, height: Number(rect.height) || 0 } : undefined,
124
+ }
125
+ }
126
+
127
+ /** Does a native candidate match an @ query? NFKC + case folding, every keyword must hit. */
128
+ export function matchesAppQuery (app, query) {
129
+ const needle = String(query == null ? '' : query).normalize('NFKC').trim().toLowerCase()
130
+ if (!needle) return true
131
+ const haystack = `${app.title} ${app.process} ${app.exe} ${app.class}`.normalize('NFKC').toLowerCase()
132
+ return needle.split(/\s+/).filter(Boolean).every(word => haystack.includes(word))
133
+ }
134
+
135
+ /**
136
+ * The process creation-time probe.
137
+ *
138
+ * One PowerShell invocation answers for every pid in an inventory, and results are cached for
139
+ * START_TTL_MS so a LISTING stays cheap (the sidebar refreshes often and asking Windows about every
140
+ * process each time would be wasteful).
141
+ *
142
+ * THE CACHE IS FOR DISPLAY ONLY, AND `fresh` IS WHY. A pid's creation time never changes while it
143
+ * lives — but Windows REUSES pids, so a cached entry can describe a process that has since died and
144
+ * whose pid+handle pair now belongs to something else. A plain TTL makes that window observable: for
145
+ * up to START_TTL_MS a recycled pid reports the OLD start time, which is exactly what an identity
146
+ * check compares, so a stale read would let an old window reference bind to a new window.
147
+ *
148
+ * `probe(pids, signal, { fresh: true })` therefore BYPASSES the cache for those pids and asks the
149
+ * OS again. Resolution uses it for the ONE pid it is about to hand to a desktop tool; listings keep
150
+ * the cheap cached path. A fresh probe that cannot answer yields no row for that pid, which callers
151
+ * treat as unverified and refuse.
152
+ */
153
+ export class ProcessStartProbe {
154
+ constructor ({ run = runPowerShell, ttlMs = START_TTL_MS, log = () => {} } = {}) {
155
+ this.run = run
156
+ this.ttlMs = ttlMs
157
+ this.log = log
158
+ this.cache = new Map()
159
+ this.disabled = process.env.DSH_COMPUTER_USE_WINDOW_START_PROBE === '0'
160
+ }
161
+
162
+ /**
163
+ * @param {number[]} pids
164
+ * @param {AbortSignal} [signal]
165
+ * @param {{fresh?: boolean}} [options] `fresh` re-reads those pids from the OS instead of the cache
166
+ * @returns {Promise<Map<number, {started: string, path: string}|null>>}
167
+ */
168
+ async probe (pids, signal, { fresh = false } = {}) {
169
+ const unique = [...new Set(pids.filter(pid => Number.isSafeInteger(pid) && pid > 0))]
170
+ const answer = new Map()
171
+ const missing = []
172
+ for (const pid of unique) {
173
+ const hit = fresh ? undefined : this.cache.get(pid)
174
+ if (hit && Date.now() - hit.at < this.ttlMs) answer.set(pid, hit.value)
175
+ else missing.push(pid)
176
+ }
177
+ if (!missing.length) return answer
178
+ if (this.disabled || typeof this.run !== 'function') {
179
+ // A disabled probe answers "unknown" for everything it could not answer from cache. A FRESH
180
+ // request must NOT fall back to the cache: its whole purpose is a current reading.
181
+ for (const pid of missing) answer.set(pid, null)
182
+ return answer
183
+ }
184
+ let rows = []
185
+ try {
186
+ rows = await this.run(missing, signal)
187
+ } catch (error) {
188
+ if (signal?.aborted) throw error
189
+ this.log(`[computer-use] process start probe unavailable: ${error?.message ?? error}`)
190
+ rows = []
191
+ }
192
+ const probed = parseStartProbeRows(rows)
193
+ for (const pid of missing) {
194
+ const value = probed.get(pid) ?? null
195
+ // A FRESH read is the authoritative current answer, so it always refreshes the entry — that is
196
+ // what keeps a recycled pid from being re-cached with a stale, still-within-TTL reading. A read
197
+ // that could NOT answer stores `null`, which every caller treats as "unverified" and refuses;
198
+ // it never resurrects an earlier value.
199
+ this.cache.set(pid, { at: Date.now(), value })
200
+ answer.set(pid, value)
201
+ }
202
+ if (this.cache.size > 400) for (const pid of [...this.cache.keys()].slice(0, this.cache.size - 400)) this.cache.delete(pid)
203
+ return answer
204
+ }
205
+
206
+ /**
207
+ * Read ONE pid's creation time from the OS, ignoring and refreshing that pid's cache entry.
208
+ *
209
+ * This is the resolution-time read: the caller is about to bind a handle to a process generation,
210
+ * so an answer must describe the process that exists NOW. `null` means the OS could not vouch for
211
+ * it — the caller must refuse rather than fall back to a remembered value.
212
+ */
213
+ async fresh (pid, signal) {
214
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null
215
+ const answer = await this.probe([pid], signal, { fresh: true })
216
+ const value = answer.get(pid) ?? null
217
+ // A MISSED fresh read also EVICTS the cached value: keeping a stale entry would let the next
218
+ // cached listing report the dead process's start time for a pid it can no longer vouch for.
219
+ if (!value) this.cache.delete(pid)
220
+ return value
221
+ }}
222
+
223
+ /**
224
+ * Read `(pid, process start ticks, image path)` for a set of pids in ONE PowerShell call.
225
+ *
226
+ * THE PIPELINE BUG THIS FIXES (measured on real Windows PowerShell 5.1): `foreach (...) { ... } |
227
+ * ConvertTo-Json` does NOT parse as a pipeline — a `foreach` STATEMENT cannot be piped, so the
228
+ * script failed and every application came back with no start time, i.e. weak identity for all of
229
+ * them. The results are therefore collected into a variable with `@(...)`, and a single object is
230
+ * still emitted as a JSON ARRAY so the caller never has to guess the shape.
231
+ *
232
+ * `StartTime.ToUniversalTime().Ticks` is the same witness the native worker uses for its own target
233
+ * binding, and ticks are culture- and DST-independent, so the value compares equal across calls.
234
+ */
235
+ function runPowerShell (pids, signal) {
236
+ const list = '(' + pids.join(',') + ')'
237
+ // The shape is wrapped in an OBJECT on purpose. In Windows PowerShell 5.1 an empty array serialized
238
+ // directly produces NO output at all, and a one-element array is easy to mistake for a single
239
+ // object — both would turn "the probe ran and found nothing" into an unreadable reply. `{"rows":[…]}` always parses.
240
+ const script = [
241
+ "$ErrorActionPreference='SilentlyContinue'",
242
+ '[Console]::OutputEncoding=[Text.UTF8Encoding]::new()',
243
+ `$ids=${list}`,
244
+ '$rows=@(foreach($p in @(Get-Process -Id $ids -ErrorAction SilentlyContinue)){',
245
+ ' $started=$null',
246
+ ' try{$started=$p.StartTime.ToUniversalTime().Ticks}catch{}',
247
+ ' if($null -ne $started){',
248
+ ' $path=$null; try{$path=$p.Path}catch{}',
249
+ ' [pscustomobject]@{pid=[int]$p.Id;started=$started.ToString();path=$path}',
250
+ ' }',
251
+ '})',
252
+ 'ConvertTo-Json -InputObject @{rows=$rows} -Compress -Depth 4',
253
+ ].join('\n')
254
+ return new Promise((resolve, reject) => {
255
+ execFile('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand',
256
+ Buffer.from(script, 'utf16le').toString('base64')],
257
+ { windowsHide: true, timeout: START_PROBE_TIMEOUT_MS, maxBuffer: 1 << 20, signal },
258
+ (error, stdout, stderr) => {
259
+ if (error) {
260
+ // A probe failure is ALWAYS reported to the caller: it degrades to "unknown identity", which
261
+ // resolution refuses, so it must not be silent.
262
+ reject(Object.assign(new Error(String(stderr || error.message || error).trim().slice(0, 300) || 'start-time probe failed'), { code: 'START_PROBE_FAILED' }))
263
+ return
264
+ }
265
+ const text = String(stdout || '').replace(/^\uFEFF/, '').trim()
266
+ if (!text) {
267
+ reject(Object.assign(new Error('start-time probe produced no output'), { code: 'START_PROBE_EMPTY' }))
268
+ return
269
+ }
270
+ try {
271
+ const parsed = JSON.parse(text)
272
+ const rows = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed.rows : parsed
273
+ resolve(Array.isArray(rows) ? rows : rows && typeof rows === 'object' ? [rows] : [])
274
+ } catch (parseError) {
275
+ reject(Object.assign(new Error(`start-time probe returned unparseable JSON: ${text.slice(0, 120)}`), { code: 'START_PROBE_BAD_JSON' }))
276
+ }
277
+ })
278
+ })
279
+ }
280
+
281
+ /** Validate one probe row: `{pid, started, path}` with decimal FileTime ticks. Exported for tests. */
282
+ export function parseStartProbeRows (rows) {
283
+ const probed = new Map()
284
+ for (const row of Array.isArray(rows) ? rows : []) {
285
+ const pid = Number(row?.pid)
286
+ if (!Number.isSafeInteger(pid) || pid <= 0) continue
287
+ // `started` must be the SAME witness the native worker uses: .NET FileTime ticks, as a decimal
288
+ // string. A missing, empty or non-numeric value is skipped — never stored as a truthy "present".
289
+ const started = row?.started == null ? '' : String(row.started).trim()
290
+ if (!/^\d{6,}$/.test(started)) continue
291
+ probed.set(pid, { started, path: typeof row.path === 'string' ? row.path : '' })
292
+ }
293
+ return probed
294
+ }
295
+
296
+ /**
297
+ * The running-application inventory.
298
+ *
299
+ * Window enumeration is the native worker's OWN production data (`cu.call('windows')`), not a
300
+ * second desktop scanner: the worker already hides its own indicator overlay, its own process and
301
+ * invisible windows. This class only adds identity and filtering.
302
+ */
303
+ export function createAppInventory ({
304
+ cu, log = () => {}, probe = new ProcessStartProbe({ log }), selfPid = process.pid, selfExe = process.execPath,
305
+ windows = undefined, now = () => Date.now(), alive = processAlive,
306
+ } = {}) {
307
+ const runtime = randomUUID()
308
+ const known = new Map()
309
+ let cache = null
310
+
311
+ const enumerate = typeof windows === 'function'
312
+ ? windows
313
+ : async (signal) => {
314
+ if (!cu) throw appError('APP_INVENTORY_UNAVAILABLE', '本机窗口枚举不可用:电脑操控原生组件尚未连接')
315
+ // PASSIVE ON PURPOSE (measured on the real 3.0.0 build): this is the `@` menu's candidate
316
+ // list, so merely typing `@` must not start anything. `cu.call` signs every request as a
317
+ // cycle op, which lit the cyan breathing border and armed the human monitors off a pure
318
+ // read — before the human had picked anything and with no driving call behind it. The
319
+ // passive read keeps the worker's cycle gate shut; picking a row still lights nothing, and
320
+ // the real computer_* call the human then makes opens the cycle as it always did.
321
+ if (typeof cu.callPassive === 'function') return cu.callPassive('windows', {}, WINDOW_TIMEOUT_MS, false)
322
+ if (typeof cu.call !== 'function') throw appError('APP_INVENTORY_UNAVAILABLE', '本机窗口枚举不可用:电脑操控原生组件尚未连接')
323
+ // An injected core (tests) predating the passive seam. The probe is still a plain read, so
324
+ // it is served; the shipped core always offers the passive path above.
325
+ log('[computer-use] references: passive window read unavailable in this core; using its plain read')
326
+ return cu.call('windows', {}, WINDOW_TIMEOUT_MS, false)
327
+ }
328
+
329
+ /**
330
+ * Build the window inventory.
331
+ *
332
+ * @param {{signal?: AbortSignal, refresh?: boolean, freshPids?: number[]}} options
333
+ * `refresh` re-enumerates the HWND list (the listing cache is bypassed);
334
+ * `freshPids` re-reads those pids' creation times from the OS, bypassing the start-time cache.
335
+ * The second option exists for RESOLUTION: it asks about the one pid it is about to bind, and
336
+ * about no other, so an ordinary listing stays a single cheap probe.
337
+ */
338
+ async function snapshot ({ signal, refresh = false, freshPids = null } = {}) {
339
+ // THE CACHED VALUE IS THE SNAPSHOT ITSELF, and the hit path must return THAT OBJECT.
340
+ // (Measured 2026-11-28: this line used to return `cache.value`, but the assignment below stores
341
+ // `const value = {rows, at}` directly in `cache` — so every CACHE HIT returned `undefined` and
342
+ // the very next `snap.rows` threw `TypeError: Cannot read properties of undefined (reading
343
+ // 'rows')`. The visible symptom was the sidebar failing on the SECOND consecutive GET or on a
344
+ // search that reused a fresh snapshot; the first call always worked because it populated the
345
+ // cache and returned `value` directly.)
346
+ if (!refresh && !freshPids && cache && now() - cache.at < SNAPSHOT_TTL_MS) return cache
347
+ let raw
348
+ try {
349
+ raw = await enumerate(signal)
350
+ } catch (error) {
351
+ if (signal?.aborted) throw error
352
+ return { rows: [], at: now(), unavailable: clip(error?.message ?? error, 300) }
353
+ }
354
+ const list = Array.isArray(raw?.windows) ? raw.windows : Array.isArray(raw) ? raw : []
355
+ const base = list.map(row => normalizeWindowRow(row, { selfPid, selfExe })).filter(Boolean)
356
+ const pids = base.map(row => row.pid)
357
+ let starts = new Map()
358
+ try { starts = await probe.probe(pids, signal) } catch (error) { if (signal?.aborted) throw error }
359
+ // THE RESOLUTION RE-READ. Only the pids the caller is about to bind are asked AGAIN, without the
360
+ // TTL, and the answer REPLACES the cached one for those pids. Everything else keeps the cheap
361
+ // cached probe above, so a listing never pays for this and a resolve never re-reads the world.
362
+ if (Array.isArray(freshPids) && freshPids.length) {
363
+ const wanted = [...new Set(freshPids.filter(pid => Number.isSafeInteger(pid) && pid > 0))]
364
+ // A pid that is not in the inventory at all must not reach the OS: it cannot be bound anyway.
365
+ const present = wanted.filter(pid => pids.includes(pid))
366
+ if (present.length) {
367
+ let fresh = new Map()
368
+ try {
369
+ fresh = await probe.probe(present, signal, { fresh: true })
370
+ } catch (error) {
371
+ if (signal?.aborted) throw error
372
+ // A failed fresh read leaves the pid UNVERIFIED rather than silently keeping the old value:
373
+ // the caller must refuse an identity it could not re-establish.
374
+ for (const pid of present) fresh.set(pid, null)
375
+ }
376
+ for (const pid of present) starts.set(pid, fresh.get(pid) ?? null)
377
+ }
378
+ }
379
+ const rows = []
380
+ const seen = new Set()
381
+ for (const row of base) {
382
+ const started = starts.get(row.pid) ?? null
383
+ const exe = row.exe || started?.path || ''
384
+ const identity = hashIdentity([row.pid, started?.started ?? '', row.hwnd, exe.toLowerCase(), row.class])
385
+ const key = `${row.pid}:${row.hwnd}`
386
+ if (seen.has(key)) continue
387
+ seen.add(key)
388
+ rows.push({
389
+ ...row,
390
+ exe,
391
+ started: started?.started ?? null,
392
+ identity,
393
+ ref: `dsh-app://${runtime}/${identity}`,
394
+ // A candidate with no readable start time may still be LISTED (the human should see what is
395
+ // running), but `resolve` refuses it: an unverified handle must never reach a desktop tool.
396
+ identityStrength: started?.started ? 'strong' : 'weak',
397
+ })
398
+ }
399
+ rows.sort((a, b) => Number(b.active) - Number(a.active) || a.title.localeCompare(b.title))
400
+ const value = { rows, at: now() }
401
+ // A snapshot built for a RESOLUTION re-read must not become the cached listing: its start times
402
+ // for the selected pid were obtained under a different (stricter) contract, and a later listing
403
+ // should keep its own cheap view.
404
+ if (!freshPids) cache = value
405
+ return value
406
+ }
407
+
408
+ function remember (app) {
409
+ known.set(app.ref, app)
410
+ while (known.size > KNOWN_LIMIT) known.delete(known.keys().next().value)
411
+ }
412
+
413
+ // ---- "only a real user pick becomes a session reference" -------------------------------------
414
+ // The pick bookkeeping lives host-side, not in the browser: the client reports the pick it made
415
+ // (a row the human chose) and the host remembers (session, ref). Anything that resolves a ref
416
+ // WITHOUT a pick — a chip preview, a pasted mention — is still identity-checked, but it can never
417
+ // create a session entry on its own. Bounded by sessions and refs per session.
418
+ const picks = new Map()
419
+ const PICK_SESSIONS = 200
420
+ const PICK_REFS = 64
421
+
422
+ function recordPick (session, ref) {
423
+ if (!session || !ref) return false
424
+ const key = String(session)
425
+ let set = picks.get(key)
426
+ if (!set) { set = new Set(); picks.set(key, set) }
427
+ set.add(String(ref))
428
+ while (set.size > PICK_REFS) set.delete(set.values().next().value)
429
+ while (picks.size > PICK_SESSIONS) picks.delete(picks.keys().next().value)
430
+ return true
431
+ }
432
+
433
+ function pickedBy (session, ref) {
434
+ if (!session || !ref) return false
435
+ return picks.get(String(session))?.has(String(ref)) === true
436
+ }
437
+
438
+ /** @returns {Promise<{apps: object[], unavailable?: string}>} */
439
+ async function list (query = '', { signal, refresh = false } = {}) {
440
+ const snap = await snapshot({ signal, refresh })
441
+ const apps = []
442
+ for (const app of snap.rows) {
443
+ if (!matchesAppQuery(app, query)) continue
444
+ remember(app)
445
+ apps.push(publicApp(app))
446
+ }
447
+ return { apps, ...(snap.unavailable ? { unavailable: snap.unavailable } : {}), total: snap.rows.length }
448
+ }
449
+
450
+ /**
451
+ * Resolve one reference to the window it named — or refuse.
452
+ *
453
+ * IDENTITY IS PID + PROCESS START TIME + WINDOW HANDLE. The TITLE is deliberately NOT compared:
454
+ * a title changes whenever the human edits or saves (an editor's `*` marker, a document name), and
455
+ * that is the SAME window the human picked. Comparing it would refuse a window that is genuinely
456
+ * still the target.
457
+ *
458
+ * A MISSING START TIME IS A REFUSAL, not a weaker proof. Without it, `pid + hwnd` alone cannot
459
+ * distinguish the same window from a recycled pair, so handing that HWND to a desktop tool would
460
+ * be handing it a window nobody verified. The honest answers are "read the identity or ask the
461
+ * user to select again"; this throws instead of guessing.
462
+ *
463
+ * @param {string} value bare ref or a full `@[label](dsh-app://…)` mention
464
+ */
465
+ async function resolve (value, { signal } = {}) {
466
+ const ref = appRefOf(value)
467
+ if (!ref) throw appError('APP_REFERENCE_STALE', '这不是一个有效的应用引用;请重新用 @ 选择正在运行的应用')
468
+ const match = APP_REF.exec(ref)
469
+ if (!match) throw appError('APP_REFERENCE_STALE', '应用引用格式无效;请重新选择')
470
+ if (match[1].toLowerCase() !== runtime) throw appError('APP_REFERENCE_STALE', '该应用引用来自另一个 DSH 运行期,已失效;请重新选择应用')
471
+ const previous = known.get(ref)
472
+ if (!previous) throw appError('APP_REFERENCE_STALE', '该应用引用没有被本会话选择过;请重新用 @ 选择应用')
473
+ if (!previous.started) {
474
+ throw appError('APP_IDENTITY_UNVERIFIED', '无法读取该应用的进程启动身份,不能安全绑定这个窗口;请重新用 @ 选择(并确认系统允许读取进程信息)')
475
+ }
476
+ // THE ONLY PLACE A REFERENCE IS BOUND, and therefore the only place a CURRENT process identity
477
+ // matters. `refresh` re-enumerates the window list (so a closed or replaced HWND is visible), and
478
+ // `freshPids` re-reads THIS pid's creation time from the OS with no TTL — because Windows reuses
479
+ // pids: a cached reading taken before the app restarted would report the OLD start time for the
480
+ // NEW process and make the identity comparison below pass on a window nobody verified.
481
+ // Only the selected pid is re-read, so this costs one extra query and never re-probes the world.
482
+ const snap = await snapshot({ signal, refresh: true, freshPids: [previous.pid] })
483
+ if (snap.unavailable) throw appError('APP_INVENTORY_UNAVAILABLE', snap.unavailable)
484
+ const current = snap.rows.find(row => row.hwnd === previous.hwnd && row.pid === previous.pid)
485
+ if (!current) {
486
+ if (!alive(previous.pid)) throw appError('APP_PROCESS_EXITED', `应用已退出(${previous.process || previous.pid});不会对可能被复用的窗口执行任何操作`)
487
+ throw appError('APP_WINDOW_CLOSED', '该应用窗口已关闭;请重新用 @ 选择')
488
+ }
489
+ if (!current.started) {
490
+ throw appError('APP_IDENTITY_UNVERIFIED', '这次无法重新读取该应用的进程启动身份;为免对可能被复用的窗口操作,已拒绝。请重新选择应用')
491
+ }
492
+ if (previous.started !== current.started) {
493
+ throw appError('APP_WINDOW_REPLACED', '该 pid/窗口已被另一个进程复用;引用已失效,请重新选择')
494
+ }
495
+ if (previous.class !== current.class || previous.process !== current.process) {
496
+ throw appError('APP_WINDOW_REPLACED', '同一个窗口句柄现在属于另一个窗口;请重新选择')
497
+ }
498
+ // THE LAST GATE BEFORE A HANDLE LEAVES THIS FUNCTION (measured race, 2026-11-28).
499
+ //
500
+ // Everything above describes what the OS reported a moment ago: the window row came back from
501
+ // `windows`, and the creation time came back from the probe. Between those reads and this
502
+ // `return`, the process can EXIT — and a dead process leaves its window row in the inventory we
503
+ // already hold. In that window the identity comparison still SUCCEEDS (the row and the start
504
+ // time both match what was picked), so `!current` is false, `alive()` is never consulted, and an
505
+ // HWND belonging to a process that no longer exists would be handed to a desktop tool.
506
+ //
507
+ // `alive()` is therefore re-checked here, for the SELECTED pid only (one process, not the
508
+ // inventory), immediately before the context is produced. It answers the narrow question "does
509
+ // this process still exist", and `processAlive` deliberately reports EPERM as ALIVE: a process
510
+ // we may not signal is a process that EXISTS, and turning an access-control refusal into "it
511
+ // exited" would refuse a window the human can plainly see. A refusal here is the same
512
+ // APP_PROCESS_EXITED the closed-window path already uses, so callers see one code for one fact.
513
+ if (!alive(previous.pid)) {
514
+ throw appError('APP_PROCESS_EXITED', `应用已退出(${previous.process || previous.pid});不会对可能被复用的窗口执行任何操作`)
515
+ }
516
+ // The title may differ (an edited document changes it); the CURRENT title is what the caller
517
+ // gets, so a model never sees the title the window had when it was picked.
518
+ return describeResolved({ ...current, strength: 'strong' })
519
+ }
520
+
521
+ function publicApp (app) {
522
+ return {
523
+ ref: app.ref,
524
+ name: app.process || app.title,
525
+ label: app.title || app.process || app.exe || '应用',
526
+ title: app.title,
527
+ process: app.process,
528
+ exe: app.exe,
529
+ pid: app.pid,
530
+ hwnd: app.hwnd,
531
+ class: app.class,
532
+ minimized: app.minimized,
533
+ active: app.active,
534
+ rect: app.rect,
535
+ started: app.started,
536
+ identityStrength: app.identityStrength,
537
+ }
538
+ }
539
+
540
+ function describeResolved (app) {
541
+ return {
542
+ ref: app.ref,
543
+ hwnd: app.hwnd,
544
+ pid: app.pid,
545
+ started: app.started,
546
+ identity: app.strength,
547
+ // The CURRENT title, not the one it had when picked: an edited document changes its title,
548
+ // and a model must never be told the old one while acting on the new window.
549
+ title: app.title,
550
+ process: app.process,
551
+ exe: app.exe,
552
+ class: app.class,
553
+ minimized: app.minimized,
554
+ rect: app.rect,
555
+ // The exact context an existing desktop tool needs; no driver, no activation, no focus.
556
+ desktop: { tool: 'computer_shot', args: { hwnd: app.hwnd }, also: ['computer_window', 'computer_uia', 'computer_uia_elements', 'computer_ocr'], focus: false },
557
+ }
558
+ }
559
+
560
+ return { runtime, list, resolve, snapshot, describeResolved, publicApp, recordPick, pickedBy }
561
+ }
562
+
563
+ function processAlive (pid) {
564
+ try {
565
+ process.kill(pid, 0)
566
+ return true
567
+ } catch (error) {
568
+ return error?.code === 'EPERM'
569
+ }
570
+ }
571
+
572
+ /** The short, model-visible context block a serialized app reference carries. */
573
+ export function appContextText (resolved) {
574
+ const body = JSON.stringify({
575
+ ref: resolved.ref,
576
+ title: clip(resolved.title, 160),
577
+ process: resolved.process || null,
578
+ exe: resolved.exe || null,
579
+ pid: resolved.pid,
580
+ hwnd: resolved.hwnd,
581
+ identity: resolved.identity,
582
+ tools: resolved.desktop,
583
+ ...(resolved.warning ? { warning: resolved.warning } : {}),
584
+ })
585
+ return `<computer_use_app>\n${clip(body, 1200)}\n</computer_use_app>`
586
+ }
@@ -0,0 +1,77 @@
1
+ // references-files.js — keep FILES visible in the native @ list.
2
+ //
3
+ // THE PROBLEM (the same one upstream DoYourWeb src/file-references.js documents): the local
4
+ // file-reference provider ranks directories first and caps the whole result at
5
+ // `fileReferences.config.maxResults`. A workspace with more directories than that cap therefore
6
+ // answers a BARE `@` with nothing but folders — the user cannot reach a file at all without
7
+ // typing a name they already know. The cap is host-side budget, so the fix belongs host-side:
8
+ // wrap `ctx.fileReferences.list` and, only in the case where the cap has excluded every file,
9
+ // replace the tail of the list with a bounded file share (half the budget), read from the
10
+ // session's working directory through `ctx.workingDirectory.ensure()`.
11
+ //
12
+ // The wrapper is deliberately narrow, so it can never change an ordinary answer:
13
+ // * only when the query is empty (a typed query is a targeted search, not a browse);
14
+ // * only when the raw list is FULL (the cap was reached) and every entry is a directory;
15
+ // * only for a provider whose `list` is a plain own/Prototype function;
16
+ // * and it always returns at most `maxResults` entries.
17
+ // Unload restores the original property descriptor, so a plugin unload — or a second copy of this
18
+ // plugin — cannot leave the host provider decorated.
19
+ import { readdir } from 'node:fs/promises'
20
+
21
+ const FILE_SHARE = 2
22
+
23
+ const isDirectory = item => !!item && (item.kind === 'directory' || item.kind === 'folder')
24
+
25
+ /**
26
+ * Does this answer show the starvation the backfill exists for?
27
+ * @param {readonly object[]} items provider answer
28
+ * @param {number} limit the provider's configured result cap
29
+ */
30
+ export function filesExcludedByCap (items, limit) {
31
+ return Array.isArray(items) && Number.isSafeInteger(limit) && limit > 0 &&
32
+ items.length >= limit && items.length > 0 && items.every(isDirectory)
33
+ }
34
+
35
+ /**
36
+ * Decorate the host file-reference provider so a folder-flooded bare @ still lists files.
37
+ * @param {object} service host `ctx.fileReferences`
38
+ * @param {object} workingDirectory host `ctx.workingDirectory`
39
+ * @param {{readdir?: typeof readdir}} [options] injection point for tests
40
+ * @returns {() => void} restore (idempotent, keeps a newer decoration intact)
41
+ */
42
+ export function balanceFileReferences (service, workingDirectory, options = {}) {
43
+ const limit = service?.config?.maxResults
44
+ const read = typeof options.readdir === 'function' ? options.readdir : readdir
45
+ if (typeof service?.list !== 'function' || typeof workingDirectory?.ensure !== 'function') return () => {}
46
+ if (!Number.isSafeInteger(limit) || limit < FILE_SHARE) return () => {}
47
+ const descriptor = Object.getOwnPropertyDescriptor(service, 'list')
48
+ const original = service.list
49
+ const wrapped = async function (agent, query, signal) {
50
+ const items = await original.call(this, agent, query, signal)
51
+ if (query !== '' || !filesExcludedByCap(items, limit)) return items
52
+ signal?.throwIfAborted?.()
53
+ try {
54
+ const root = await workingDirectory.ensure(agent, signal)
55
+ if (!root) return items
56
+ const entries = await read(root, { withFileTypes: true })
57
+ signal?.throwIfAborted?.()
58
+ const files = (entries || [])
59
+ .filter(entry => entry && typeof entry.isFile === 'function' && entry.isFile() && !String(entry.name).startsWith('.'))
60
+ .map(entry => String(entry.name))
61
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
62
+ .slice(0, Math.floor(limit / FILE_SHARE))
63
+ .map(name => ({ path: name, kind: 'file' }))
64
+ if (!files.length) return items
65
+ return [...items.slice(0, Math.max(0, limit - files.length)), ...files]
66
+ } catch (error) {
67
+ if (signal?.aborted) throw error
68
+ return items
69
+ }
70
+ }
71
+ Object.defineProperty(service, 'list', { configurable: true, writable: true, value: wrapped })
72
+ return () => {
73
+ if (Object.getOwnPropertyDescriptor(service, 'list')?.value !== wrapped) return
74
+ if (descriptor) Object.defineProperty(service, 'list', descriptor)
75
+ else delete service.list
76
+ }
77
+ }