dsh-codex-style-computer-use 2.3.1 → 2.3.3

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.
@@ -4,7 +4,7 @@ import { captureCoordinates } from './media-contract.js'
4
4
 
5
5
  export function screenshotMetadata (shot) {
6
6
  const value = {}
7
- for (const key of ['capturedAt', 'ts', 'imageSize', 'settled', 'settleMs', 'settleDiffPct', 'settleNote',
7
+ for (const key of ['hwnd', 'captureBackend', 'capturedAt', 'ts', 'imageSize', 'settled', 'settleMs', 'settleDiffPct', 'settleNote',
8
8
  'cursor', 'cursorRequested', 'cursorDrawn', 'cursorScreenPos', 'cursorInImage', 'cursorNote']) {
9
9
  if (shot[key] !== undefined) value[key] = shot[key]
10
10
  }
package/lib/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { installApprovalAttribution } from './approval-attribution.js'
2
+ import { installArgumentRecovery } from './argument-recovery.js'
3
+ import * as hostLlm from '@deepseek-ai/dsh-llm'
2
4
  import { HOST_DEBUG_FILE, noteHostBlocked, readHostDebug, sessionPermission, writeHostDebug } from './host-debug.js'
3
5
  import { installHumanAttention } from './attention.js'
4
6
  // dsh-computer-use — DSH Cordis plugin
@@ -1354,6 +1356,7 @@ export function apply (ctx, config) {
1354
1356
 
1355
1357
  const definitions = []
1356
1358
  registerTools({ ctx, cu, config, dataDir, log, snapshotPath, defineTool, hooks, ensureCycle, register: d => definitions.push(d) })
1359
+ installArgumentRecovery(ctx, new Set([ACTIVATION_TOOL, ...definitions.map(tool => tool.name)]), buildMessage, hostLlm.isAgentLoopRequest)
1357
1360
  installToolExposure({ ctx, definitions, defineTool, scopeOf, log, enabled: config.progressiveTools !== false,
1358
1361
  skillPath: fileURLToPath(new URL('SKILL.md', SKILL_DIR_URL)),
1359
1362
  readSkill: () => fs.readFileSync(fileURLToPath(new URL('SKILL.md', SKILL_DIR_URL)), 'utf8') })
@@ -1,7 +1,7 @@
1
1
  // One command grammar for approval and dispatch. Native parsing implements the
2
2
  // same contract for direct worker clients; cross-language fixtures guard parity.
3
3
  export const KEY_ALIASES = Object.freeze({
4
- control: 'ctrl', lwin: 'win', windows: 'win', meta: 'win',
4
+ control_l: 'ctrl', shift_l: 'shift', alt_l: 'alt', control: 'ctrl', lwin: 'win', windows: 'win', meta: 'win',
5
5
  return: 'enter', escape: 'esc', bksp: 'backspace', del: 'delete',
6
6
  ins: 'insert', pageup: 'pgup', pagedown: 'pgdn', capslock: 'caps', printscreen: 'prtsc',
7
7
  })
@@ -15,8 +15,8 @@ export function parseKeyCommand (combo) {
15
15
  const unique = []
16
16
  for (const part of combo.split('+')) {
17
17
  const raw = part.trim().toLowerCase()
18
- const key = KEY_ALIASES[raw] || raw
19
- if (!key || !(named.has(key) || /^[a-z0-9]$/.test(key) || /^f(?:[1-9]|1\d|2[0-4])$/.test(key))) {
18
+ const key = KEY_ALIASES[raw] || raw.replace(/^(?:numpad_|kp_)([0-9])$/, 'numpad$1')
19
+ if (!key || !(named.has(key) || /^numpad[0-9]$/.test(key) || /^[a-z0-9]$/.test(key) || /^f(?:[1-9]|1\d|2[0-4])$/.test(key))) {
20
20
  throw new Error(`KEY_COMMAND_INVALID: unknown or empty key ${JSON.stringify(raw)}`)
21
21
  }
22
22
  if (!unique.includes(key)) unique.push(key)
package/lib/tools.js CHANGED
@@ -26,6 +26,19 @@ import { validateLaunchArgs, validateLaunchTarget } from './launch.js'
26
26
  import { join } from 'node:path'
27
27
 
28
28
  const P = (type, description, extra = {}) => ({ type, description, ...extra })
29
+ const screenshotIdParam = P('string', 'from computer_shot {hwnd}; points are pixels of that returned image')
30
+ const windowParam = P('number', 'expected window handle')
31
+ const coordinatePair = (text, x, y) => {
32
+ if (x === undefined && y === undefined) return text
33
+ if (text !== undefined || !Number.isSafeInteger(x) || !Number.isSafeInteger(y))
34
+ throw new Error('Supply either a point string or both integer coordinates')
35
+ return x + ',' + y
36
+ }
37
+ const checkedWindow = hwnd => {
38
+ if (hwnd !== undefined && (!Number.isSafeInteger(hwnd) || hwnd <= 0 || hwnd > 0x7fffffff))
39
+ throw new Error('hwnd must be a positive Windows window handle')
40
+ return hwnd
41
+ }
29
42
  const cooperativeTools = new Set(['computer_click', 'computer_move', 'computer_drag', 'computer_scroll',
30
43
  'computer_select', 'computer_key', 'computer_type', 'computer_window', 'computer_uia_act', 'computer_batch', 'computer_clip',
31
44
  'computer_focus'])
@@ -57,6 +70,43 @@ const rect = (v) => {
57
70
  return null
58
71
  }
59
72
 
73
+ // Keep the recognizer's own text within each fragment (including RTL and CJK).
74
+ // Render separately located fragments together when they share a visual baseline.
75
+ function renderOcr(value) {
76
+ if (!value?.lines) return 'no text'
77
+ const head = `ocr ${value.language}${value.hwnd ? ' hwnd=' + value.hwnd : ''} region=${value.region || ''}${value.requestedRegion ? ' clippedFrom=' + value.requestedRegion : ''} scale=${value.scale || 1} @center(x,y)`
78
+ const parts = [], unplaced = []
79
+ for (const line of value.lines) {
80
+ const words = line.words || []
81
+ if (!words.length) { unplaced.push(line.text); continue }
82
+ let group = []
83
+ function flush() {
84
+ const left = Math.min(...group.map(w => w.x)), right = Math.max(...group.map(w => w.x + w.w))
85
+ const top = Math.min(...group.map(w => w.y)), bottom = Math.max(...group.map(w => w.y + w.h))
86
+ parts.push({ x: Math.floor((left+right)/2), y: Math.floor((top+bottom)/2), h: bottom-top,
87
+ text: group.length === words.length ? line.text : group.map(w => w.text).join(' ') })
88
+ group = []
89
+ }
90
+ for (const w of words) {
91
+ const prev = group.at(-1)
92
+ if (prev && Math.max(w.x-prev.x-prev.w, prev.x-w.x-w.w) > 2*Math.max(w.h,prev.h)) flush()
93
+ group.push(w)
94
+ }
95
+ flush()
96
+ }
97
+ const rows = []
98
+ for (const p of parts.sort((a,b) => a.y-b.y || a.x-b.x)) {
99
+ let row = rows.at(-1)
100
+ if (!row || p.y-row.y > Math.max(2, Math.min(row.h,p.h)*0.45)) {
101
+ row = { y:p.y, h:p.h, parts:[] }
102
+ rows.push(row)
103
+ }
104
+ row.parts.push(p)
105
+ }
106
+ const body = rows.map(row => row.parts.sort((a,b) => a.x-b.x).map(p => `@${p.x},${p.y} ${p.text}`).join(' | '))
107
+ return [head, ...body, ...unplaced].join('\n')
108
+ }
109
+
60
110
  export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, defineTool, hooks, ensureCycle, register }) {
61
111
  const observations = new ObservationStore({ archiveDir: typeof dataDir?.root === 'string' ? join(dataDir.root, 'observation-cache') : undefined })
62
112
  let observationEpoch
@@ -86,34 +136,108 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
86
136
  }
87
137
 
88
138
  // Shared by direct calls, explicit batch steps, and the batch checkpoint.
89
- const captureFile = async (args) => {
139
+ const captureFile = async (args, exec) => {
140
+ const hwnd = checkedWindow(args.hwnd)
141
+ if (hwnd && (args.region !== undefined || args.preset !== undefined)) throw new Error('Choose hwnd or region/preset for this capture')
90
142
  const r = rect(args.region)
91
143
  const shot = await cu.screenshot({
144
+ hwnd, clickWitness: !!hwnd,
92
145
  x: r && r.x, y: r && r.y, width: r && r.width, height: r && r.height,
93
146
  preset: args.preset, format: args.png ? 'png' : 'jpeg', cursor: true, wait: args.wait,
94
147
  maxWidth: r && r.width <= 900 ? r.width : 1280,
95
148
  })
149
+ syncObservationEpoch()
96
150
  const path = saveShot(shot.image, shot.mime === 'image/png' ? 'png' : 'jpg')
97
- return { value: { path, mime: shot.mime, region: shot.region, ...screenshotMetadata(shot) }, bytes: shot.image }
151
+ return { value: { path, mime: shot.mime, region: shot.region, ...screenshotMetadata(shot) },
152
+ bytes: shot.image, geometry: shot.shotGeometry, witness: shot.shotWitness, hwnd: shot.hwnd, epoch: observationEpoch,
153
+ cycle: hooks?.contextOf?.(exec)?.cycleId ?? null, inputEpoch: cu.cooperation?.inputEpoch ?? null }
154
+ }
155
+ // Host attachments may be resized. Bind the delivered dimensions after routing.
156
+ const bindShot = (frame, exec) => {
157
+ const { value, geometry, hwnd } = frame
158
+ syncObservationEpoch()
159
+ if (geometry && hwnd && value.settled !== false && frame.epoch === observationEpoch &&
160
+ frame.inputEpoch === (cu.cooperation?.inputEpoch ?? null)) {
161
+ const stored = observations.publish(exec, 'screenshot', [], {
162
+ geometry, witness: frame.witness, hwnd, region: value.region, imageSize: value.imageSize, cycle: frame.cycle, inputEpoch: frame.inputEpoch,
163
+ })
164
+ if (stored.observation) {
165
+ value.screenshotId = stored.observation
166
+ value.hwnd = hwnd
167
+ value.pointUnits = 'With screenshotId, use pixels of imageSize. Request delivery:path for the saved file dimensions.'
168
+ } else delete value.screenshotId
169
+ } else delete value.screenshotId
170
+ return value
98
171
  }
99
172
  const takeScreenshot = async (args, exec) => {
100
173
  const delivery = deliveryMode(args.delivery)
101
- const { value, bytes } = await captureFile(args)
102
- return attachScreenshot(ctx, exec, value, bytes, { rules: config.feedbackRules, delivery })
174
+ const frame = await captureFile(args, exec)
175
+ await attachScreenshot(ctx, exec, frame.value, frame.bytes, { rules: config.feedbackRules, delivery })
176
+ return bindShot(frame, exec)
103
177
  }
104
178
 
105
- const clickTarget = async (args) => {
106
- const target = args.mark ? { mark: args.mark } : pt(args.at)
107
- if (args.shift || args.dx !== undefined || args.dy !== undefined) {
179
+ const screenshotTarget = (args, exec) => {
180
+ syncObservationEpoch()
181
+ let frame
182
+ try { frame = observations.get(exec, args.screenshotId, 'screenshot') } catch {}
183
+ if (!frame?.targetsValid || frame.cycle !== (hooks?.contextOf?.(exec)?.cycleId ?? null) ||
184
+ frame.inputEpoch !== (cu.cooperation?.inputEpoch ?? null) || (args.hwnd !== undefined && args.hwnd !== frame.hwnd))
185
+ throw Object.assign(new Error('STALE_SCREENSHOT: capture the target window again in this Agent'), { code: 'STALE_SCREENSHOT', outcome: 'not-dispatched' })
186
+ const point = value => {
187
+ if (typeof value !== 'string' || !/^\s*\d+\s*,\s*\d+\s*$/.test(value)) throw Error('screenshotId requires an image point "x,y"')
188
+ const [x, y] = value.split(',').map(Number)
189
+ const [width, height] = frame.imageSize
190
+ const region = frame.region
191
+ if (x >= width || y >= height) throw Error('point outside screenshot imageSize')
192
+ return { x: region.x + Math.floor((x + 0.5) * region.width / width),
193
+ y: region.y + Math.floor((y + 0.5) * region.height / height) }
194
+ }
195
+ return { point, options: { expectHwnd: frame.hwnd, shotGeometry: frame.geometry, ...(frame.witness ? { shotWitness: frame.witness } : {}) } }
196
+ }
197
+ const clickTarget = async (args, exec) => {
198
+ const at = coordinatePair(args.at, args.x, args.y)
199
+ if (args.mark !== undefined && args.x !== undefined) throw Error('Choose a mark or a coordinate pair')
200
+ if (args.screenshotId !== undefined) {
201
+ if (args.mark !== undefined || args.dx !== undefined || args.dy !== undefined) throw Error('Use an exact image point with screenshotId')
202
+ const frame = screenshotTarget(args, exec)
203
+ return cu.click(frame.point(at), { ...args, ...frame.options })
204
+ }
205
+ const target = args.mark ? { mark: args.mark } : pt(at)
206
+ if (args.hwnd !== undefined || args.shift || args.dx !== undefined || args.dy !== undefined) {
108
207
  const p = await cu.resolveTarget(target)
208
+ if (p.expectHwnd && args.hwnd !== undefined && p.expectHwnd !== args.hwnd)
209
+ throw Error('Mark belongs to another window')
109
210
  const x = p.x + (args.dx || 0), y = p.y + (args.dy || 0)
110
- const options = { ...args, ...(p.expectHwnd ? { expectHwnd: p.expectHwnd } : {}) }
111
- return args.shift ? cu.shiftClick(x, y, options) : cu.click({ x, y }, options)
211
+ const options = { ...args, ...receiver(args), ...(p.expectHwnd ? { expectHwnd: p.expectHwnd } : {}) }
212
+ if (args.shift && args.hwnd === undefined && !args.ctrl && args.durationMs === undefined) return cu.shiftClick(x, y, options)
213
+ return cu.click({ x, y }, options)
112
214
  }
113
215
  return cu.click(target, args)
114
216
  }
217
+ const dragTarget = async (args, exec) => {
218
+ if (args.screenshotId !== undefined) {
219
+ const frame = screenshotTarget(args, exec)
220
+ return cu.drag(frame.point(args.from), frame.point(args.to), { ...frame.options, expectCursor: args.expectCursor })
221
+ }
222
+ return cu.drag(await cu.resolveTarget(pt(args.from)), await cu.resolveTarget(pt(args.to)), { expectCursor: args.expectCursor, expectHwnd: args.hwnd })
223
+ }
224
+ const scrollTarget = (args, exec) => {
225
+ const point = coordinatePair(args.at, args.x, args.y)
226
+ if (args.screenshotId !== undefined) {
227
+ const frame = screenshotTarget(args, exec)
228
+ return cu.scroll(args.dir, args.lines || 3, { ...frame.options, at: frame.point(point) })
229
+ }
230
+ const at = pt(point)
231
+ if (args.hwnd !== undefined && !at) throw Error('Specify a point or mark with an explicit scroll window')
232
+ return cu.scroll(args.dir, args.lines || 3, { ...(at ? { at } : {}), ...receiver(args) })
233
+ }
115
234
 
116
235
  const queryUia = async (args, exec) => {
236
+ if (args.focused) {
237
+ if (!checkedWindow(args.hwnd) || Object.keys(args).some(k => args[k] != null && !['focused', 'hwnd'].includes(k)))
238
+ throw Error('focused requires hwnd and reads only the current field')
239
+ return cu.call('uia', { hwnd: args.hwnd, focused: true })
240
+ }
117
241
  if (args.snapshot) return observations.get(exec, args.snapshot, 'uia', { offset: args.offset, limit: args.limit })
118
242
  const p = pt(args.at)
119
243
  if (p && p.x !== undefined) return cu.call('uiaFromPoint', { x: p.x, y: p.y })
@@ -126,15 +250,68 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
126
250
  return observations.publish(exec, 'uia', [args.hwnd ?? null, args.depth ?? 6, args.maxNodes ?? 120, args.budgetMs ?? 1200, args.anchor ?? null, args.role ?? null, args.name ?? null, args.id ?? null, args.limit ?? 80, targets],
127
251
  { count: res.count, elements: res.flat || [], scanned: res.scanned, truncated: res.truncated, budget: res.budget, hwnd: res.hwnd ?? args.hwnd, pid: res.pid }, args.since)
128
252
  }
253
+ const receiver = args => args.hwnd === undefined ? {} : { expectHwnd: checkedWindow(args.hwnd), strictHwnd: true }
254
+ const keyTarget = args => cu.key(args.combo, { durationMs: args.durationMs, ...receiver(args) })
255
+ const typeField = (args, exec) => {
256
+ if (args.expectTarget !== undefined && !observations.ownsTarget(exec, args.expectTarget)) {
257
+ throw Object.assign(new Error('TARGET_NOT_OBSERVED: query the expected field in this Agent before typing'), { code: 'TARGET_NOT_OBSERVED', outcome: 'not-dispatched' })
258
+ }
259
+ return cu.type(args.text, { mode: args.mode, allowPassword: args.allowPassword, expectTarget: args.expectTarget, ...receiver(args) })
260
+ }
129
261
  const actUia = (args, exec) => {
130
262
  if (args.target && !observations.ownsTarget(exec, args.target)) {
131
263
  throw Object.assign(new Error('TARGET_NOT_OBSERVED: obtain a fresh computer_uia target in this Agent before acting'), { code: 'TARGET_NOT_OBSERVED', outcome: 'not-dispatched' })
132
264
  }
133
265
  return cu.uiaAct({ hwnd: args.hwnd, nameContains: args.name, automationId: args.id, target: args.target, allowRebind: args.rebind === true,
134
- role: args.role, action: args.action, value: args.value, requireUnique: true,
266
+ role: args.role, action: args.action, value: args.value, prefix: args.prefix, suffix: args.suffix, requireUnique: true,
135
267
  depth: args.depth ?? 6, maxNodes: 300, anchor: args.anchor, budgetMs: args.budgetMs ?? 1200 })
136
268
  }
269
+ const readMarks = async (args) => {
270
+ const res = await cu.landmarks({ hwnd: args.hwnd, refresh: args.refresh, uiaOnly: args.uiaOnly })
271
+ const res2 = {
272
+ count: res.count, reused: !!res.reused, hwnd: res.hwnd,
273
+ marks: res.marks.map(m => ({ id: m.id, role: m.role, name: m.name, center: [m.cx, m.cy] })),
274
+ }
275
+ if (args.shot) {
276
+ const m = await cu.marks({ annotated: true, hwnd: args.hwnd, landmarkMap: res })
277
+ if (m.annotated) res2.annotatedShot = saveShot(m.annotated)
278
+ }
279
+ return res2
280
+ }
281
+ const manageWindow = async (args, exec) => {
282
+ const op = args.op || 'activate'
283
+ if (args.workHwnd !== undefined) {
284
+ if (op !== 'move' || args.rect !== undefined || args.observe) throw Error('workHwnd requires move without rect or observe')
285
+ return cu.windowOp({ hwnd: checkedWindow(args.hwnd) }, 'move', { workHwnd: checkedWindow(args.workHwnd) })
286
+ }
287
+ if (op !== 'activate') {
288
+ if (args.observe) throw Error('observe requires window activation')
289
+ return cu.windowOp({ hwnd: args.hwnd }, op, rect(args.rect) || {})
290
+ }
291
+ const result = await cu.activateWindow({ hwnd: args.hwnd })
292
+ if (!args.observe || !result.activated) return result
293
+ try {
294
+ hooks?.assertOwnership?.(exec)
295
+ if (feedbackBlocked(exec)) return { ...result, observationSkipped: 'cancelled-or-paused' }
296
+ const observation = await queryUia({ hwnd: result.hwnd, limit: 16, targets: true }, exec)
297
+ return { ...result, observation }
298
+ } catch (error) { return { ...result, observationError: String(error.message || error) } }
299
+ }
300
+ const readOcr = async args => {
301
+ const hwnd = checkedWindow(args.hwnd)
302
+ if (args.region !== undefined && String(args.region).trim().split(/[,\s]+/).length !== 4) throw Error('region must be "x,y,w,h"')
303
+ const region = args.region === undefined ? undefined : rect(String(args.region).trim())
304
+ if (args.region !== undefined && (!region || region.width <= 0 || region.height <= 0)) throw Error('region must be "x,y,w,h"')
305
+ if (region && Object.values(region).some(n => !Number.isInteger(n) || n < -2147483648 || n > 2147483647)) throw Error('OCR region requires 32-bit integer screen coordinates and sizes')
306
+ if (args.scale !== undefined && ![1, 2].includes(args.scale)) throw Error('OCR scale must be 1 or 2')
307
+ return cu.ocr({ ...region, ...(hwnd ? { hwnd } : {}), ...(args.scale ? { scale: args.scale } : {}) })
308
+ }
137
309
  const observeState = async (args, exec) => {
310
+ if (args.appQuery !== undefined) {
311
+ if (Object.keys(args).some(k => args[k] != null && k !== 'appQuery')) throw Error('Use appQuery by itself')
312
+ return cu.call('windows', { appQuery: args.appQuery })
313
+ }
314
+ if (args.hwnd !== undefined) return cu.call('windows', { inspectHwnd: checkedWindow(args.hwnd) })
138
315
  if (args.snapshot) return observations.get(exec, args.snapshot, 'state', { offset: args.offset, limit: args.limit })
139
316
  const result = args.windows ? await cu.call('windows', {}) : await cu.screenState({ uiaDepth: args.depth })
140
317
  syncObservationEpoch()
@@ -173,6 +350,46 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
173
350
  if (feedbackBlocked(exec)) throw new Error('compact observation cancelled-or-paused')
174
351
  hooks?.assertOwnership?.(exec)
175
352
  }
353
+ const args = context.args || {}, receipt = context.receipt || {}
354
+ let owner = args.hwnd || receipt.actionHwnd
355
+ if (!owner && args.screenshotId) owner = observations.get(exec, args.screenshotId, 'screenshot')?.hwnd
356
+ owner ||= receipt.startHwnd || receipt.focus?.expected || receipt.hwnd
357
+ // Explicit verification rectangles retain their desktop-coordinate contract.
358
+ if (owner && !feedbackViewport(args, receipt).region) {
359
+ checkAllowed()
360
+ const view = await cu.call('windows', { feedbackHwnd: owner })
361
+ const target = view.target
362
+ if (!target?.hwnd) throw Error('Feedback window unavailable. Observe the intended window again.')
363
+ const identity = { ownerHwnd: view.owner, ownerTitle: view.ownerTitle, hwnd: target.hwnd, title: target.title, windowClass: target.class, popup: view.popup }
364
+ const controls = async () => {
365
+ checkAllowed()
366
+ const ui = await queryUia({ hwnd: target.hwnd, targets: true, limit: compact ? 12 : 48, budgetMs: compact ? 400 : 1000 }, exec)
367
+ const result = { ...identity, snapshot: ui.observation, truncated: ui.truncated,
368
+ controls: compact ? (ui.elements || []).map(({ name, role, automationId, target, enabled }) => ({ name, role, automationId, target, enabled })) : ui.elements }
369
+ if (!view.popup && (context.tool === 'computer_type' || context.tool === 'computer_key') && target.active) {
370
+ try { result.focused = await queryUia({ hwnd: target.hwnd, focused: true }, exec) }
371
+ catch (error) { result.focusError = String(error.message).slice(0, 200) }
372
+ }
373
+ return result
374
+ }
375
+ if (policy.kind === 'state') {
376
+ const envelope = { observation: await controls(), feedback: policy, verification: feedbackVerification }
377
+ return compact ? limitCompactFeedback(envelope) : envelope
378
+ }
379
+ checkAllowed()
380
+ let observation
381
+ try { observation = await takeScreenshot({ hwnd: target.hwnd, delivery }, exec) }
382
+ catch (error) {
383
+ if (!view.popup || !/CAPTURE_UNAVAILABLE|SCREENSHOT_WINDOW_UNAVAILABLE/.test(error.message)) throw error
384
+ return { observation: await controls(), feedback: { ...policy, kind: 'state', reason: 'popup capture unavailable' }, verification: feedbackVerification }
385
+ }
386
+ Object.assign(observation, identity)
387
+ if (view.popup) {
388
+ try { Object.assign(observation, await controls()) }
389
+ catch (error) { observation.controlsError = String(error.message).slice(0, 200) }
390
+ }
391
+ return { observation, feedback: policy, verification: feedbackVerification }
392
+ }
176
393
  const observation = policy.kind === 'state'
177
394
  ? compact ? await collectCompactState(cu, { ...context, checkAllowed,
178
395
  archive: raw => hooks?.archiveFeedback ? hooks.archiveFeedback(exec, raw) : archiveFeedback(exec, raw) }) : await observeState({}, exec)
@@ -366,6 +583,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
366
583
  name: 'computer_shot',
367
584
  description: "Screenshot; inspect its attachment directly, or follow view if path-only. KICKOFF: first computer_state {windows:true}, then activate the target with computer_window; require activated:true. settled:false needs a fresh shot.",
368
585
  parameters: {
586
+ hwnd: P('number', 'capture this visible window and return screenshotId for image-pixel actions'),
369
587
  region: P('string', 'crop "x,y,w,h" (default: whole screen)'),
370
588
  preset: P('string', 'taskbar'),
371
589
  png: P('boolean', 'PNG instead of JPEG'),
@@ -380,36 +598,24 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
380
598
 
381
599
  reg({
382
600
  name: 'computer_ocr',
383
- description: "Read TEXT with coordinates from a screen region (inbox Windows OCR). Returns lines/words with absolute-pixel boxes — locate controls BY NAME in zero-UIA apps instead of spending a screenshot; words' x,y are click-ready centers offset by w/2,h/2. Crop tight (16M px cap); zh/en mixed supported.",
601
+ description: "Read text as spatial rows with absolute screen centers. Start with hwnd alone; use a targeted crop only for ambiguous text. Partially overlapping window crops are clipped to its captured surface. No images.",
384
602
  parameters: {
385
- region: P('string', 'crop "x,y,w,h" (default: whole screen)'),
603
+ hwnd: windowParam,
604
+ region: P('string', 'absolute x,y,w,h (default: target window or desktop)'),
605
+ scale: P('number', 'optional OCR magnification: 1 or 2; default doubles small regions'),
386
606
  },
387
- output: out((a, v) => {
388
- if (!v || !v.lines) return [{ type: 'text', text: 'no text' }]
389
- const head = `ocr ${v.language} region=${v.region ? v.region.join(',') : ''} lines=${v.lines.length}`
390
- const body = v.lines.map(l => {
391
- const w0 = l.words[0]
392
- return `${w0 ? `@${w0.x},${w0.y} ` : ''}${l.text}`
393
- }).join('\n')
394
- return [{ type: 'text', text: head + '\n' + body }]
395
- }),
607
+ output: out((_args, value) => [{ type: 'text', text: renderOcr(value) }]),
396
608
  isConcurrencySafe: () => false,
397
609
  timeoutMs: 30_000,
398
- async execute (args) {
399
- let region
400
- if (args.region) {
401
- const parts = String(args.region).split(',').map(Number)
402
- if (parts.length !== 4 || parts.some(n => !Number.isFinite(n))) throw new Error('region must be "x,y,w,h"')
403
- region = { x: parts[0], y: parts[1], width: parts[2], height: parts[3] }
404
- }
405
- return cu.ocr(region)
406
- },
610
+ execute: readOcr,
407
611
  })
408
612
 
409
613
  reg({
410
614
  name: 'computer_state',
411
615
  description: "Window/UIA state; start with windows:true, then activate the target. since returns fresh changes against that observation; omit for full. snapshot retrieves a retained full observation for this Agent.",
412
616
  parameters: {
617
+ appQuery: P('string', 'search registered Start apps by name or AppID; includes matching visible windows'),
618
+ hwnd: P('number', 'inspect one window, owned popups, work areas and sampled pixel receivers'),
413
619
  windows: P('boolean', 'windows only (no tree)'),
414
620
  depth: P('number', 'tree depth (default 6)'),
415
621
  since: P('string', 'base observation ID for changes; invalid base returns full'),
@@ -439,24 +645,14 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
439
645
  }),
440
646
  isConcurrencySafe: () => false,
441
647
  timeoutMs: 45_000,
442
- async execute (args) {
443
- const res = await cu.landmarks({ hwnd: args.hwnd, refresh: args.refresh, uiaOnly: args.uiaOnly })
444
- const res2 = {
445
- count: res.count, reused: !!res.reused, hwnd: res.hwnd,
446
- marks: res.marks.map(m => ({ id: m.id, role: m.role, name: m.name, center: [m.cx, m.cy] })),
447
- }
448
- if (args.shot) {
449
- const m = await cu.marks({ annotated: true, hwnd: args.hwnd, landmarkMap: res })
450
- if (m.annotated) res2.annotatedShot = saveShot(m.annotated)
451
- }
452
- return res2
453
- },
648
+ execute: readMarks,
454
649
  })
455
650
 
456
651
  reg({
457
652
  name: 'computer_uia',
458
653
  description: "Query hwnd plus role/name/exact id; returns controls and patterns. Scoped name/id queries also return target handles. since gives fresh changes; omit for full. snapshot retrieves a retained full result. at hit-tests. truncated:true is partial evidence.",
459
654
  parameters: {
655
+ focused: P('boolean', 'with hwnd only: read the focused field and selection'),
460
656
  at: P('string', 'hit test at "x,y"'),
461
657
  hwnd: P('number', 'required window scope for a tree query; at needs no tree'),
462
658
  role: P('string', 'Button | Edit | Hyperlink | TabItem | ...'),
@@ -486,8 +682,10 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
486
682
  name: P('string', 'element name substring'),
487
683
  id: P('string', 'exact AutomationId from UIA; scope with hwnd'),
488
684
  role: P('string', 'TabItem | Button | ListItem | ComboBox | Edit | MenuItem'),
489
- action: P('string', 'invoke (default) | select | expand | collapse | toggle | setValue | focus | scrollIntoView'),
490
- value: P('string', 'value for setValue'),
685
+ action: P('string', 'invoke | select | addToSelection | removeFromSelection | selectText | expand | collapse | toggle | setValue | focus | scrollIntoView | scroll (value: up/down/left/right)'),
686
+ value: P('string', 'setValue: text or slider number; selectText: exact text to select'),
687
+ prefix: P('string', 'selectText: immediately preceding context for repeated text'),
688
+ suffix: P('string', 'selectText: immediately following context for repeated text'),
491
689
  depth: P('number', 'tree depth, default 6; broader traversal needs anchor'),
492
690
  anchor: P('string', 'observed "x,y" inside hwnd; narrow selector search'),
493
691
  budgetMs: P('number', 'soft traversal budget 100–5000 ms (default 1200)'),
@@ -505,6 +703,9 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
505
703
  name: 'computer_click',
506
704
  description: "Click mark or screen coordinates; dx/dy offset either form. Mark IDs refer to an observed snapshot, not a moving target. STALE_MARK needs a fresh map and re-selection. Check returned focus and receiver.",
507
705
  parameters: {
706
+ screenshotId: screenshotIdParam,
707
+ hwnd: windowParam,
708
+ x: P('number', 'coordinate pair, alternative to at'), y: P('number', 'coordinate pair'),
508
709
  mark: P('string', 'mark id, e.g. "M7" (preferred)'),
509
710
  at: P('string', '"x,y" instead of a mark'),
510
711
  dx: P('number', 'offset from the mark centre: +x px'),
@@ -512,6 +713,8 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
512
713
  button: P('string', 'left (default) | right | middle'),
513
714
  clicks: P('number', '1 | 2 (double) | 3 (triple)'),
514
715
  shift: P('boolean', 'hold SHIFT (range selection)'),
716
+ ctrl: P('boolean', 'hold CTRL during the click (multi-select)'),
717
+ durationMs: P('number', 'mouse button hold time in milliseconds, 20–2000'),
515
718
  verificationRegion: P('string', 'expected effect region "x,y,w,h" in screen pixels; may differ from click point; a change alone does not prove task success'),
516
719
  allowCovered: P('boolean', 'click a pixel owned by the target app\'s OWN embedded renderer (a descendant process of the target, e.g. a WeChat article panel); an unrelated window on top is still refused and the receipt says COVERED-UNRELATED'),
517
720
  },
@@ -539,6 +742,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
539
742
  name: 'computer_drag',
540
743
  description: "Drag measured screen points. Optional expectCursor checks a recognized Windows standard shape before button-down; browser/custom cursors may be unverifiable. Ground those handles independently. cursorCheck says matched or not-requested; ok is delivery, not layout success. Verify application geometry. Prefer computer_select for text.",
541
744
  parameters: {
745
+ screenshotId: screenshotIdParam,
542
746
  from: P('string', '"M3" or "x,y"', { required: true }),
543
747
  to: P('string', '"M7" or "x,y"', { required: true }),
544
748
  expectCursor: P('string', 'Optional standard shape: resize | resize-ew | resize-ns | resize-nesw | resize-nwse | move | hand. Unknown refuses this check; omit only with independently verified target geometry/hit-test.'),
@@ -547,15 +751,16 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
547
751
  output: outJSON(),
548
752
  isConcurrencySafe: () => false,
549
753
  timeoutMs: 15_000,
550
- async execute (args) {
551
- return cu.drag(await cu.resolveTarget(pt(args.from)), await cu.resolveTarget(pt(args.to)), { expectCursor: args.expectCursor, expectHwnd: args.hwnd })
552
- },
754
+ execute: dragTarget,
553
755
  })
554
756
 
555
757
  reg({
556
758
  name: 'computer_scroll',
557
759
  description: "Wheel at a mark/point, or at the current pointer when at is omitted. Refresh marks after scrolling.",
558
760
  parameters: {
761
+ screenshotId: screenshotIdParam,
762
+ hwnd: windowParam,
763
+ x: P('number', 'coordinate pair, alternative to at'), y: P('number', 'coordinate pair'),
559
764
  dir: P('string', 'up | down | left | right', { required: true }),
560
765
  at: P('string', 'scroll at "M3" or "x,y"'),
561
766
  lines: P('number', 'notches (default 3)'),
@@ -563,10 +768,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
563
768
  output: outJSON(),
564
769
  isConcurrencySafe: () => false,
565
770
  timeoutMs: 15_000,
566
- async execute (args) {
567
- const at = pt(args.at)
568
- return cu.scroll(args.dir, args.lines || 3, at ? { at } : {})
569
- },
771
+ execute: scrollTarget,
570
772
  })
571
773
 
572
774
  reg({
@@ -594,25 +796,29 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
594
796
  reg({
595
797
  name: 'computer_key',
596
798
  description: "Press a key combo, e.g. ctrl+shift+t. Activate the target first; missing target or failed refocus refuses input.",
597
- parameters: { combo: P('string', 'e.g. "ctrl+a"', { required: true }) },
799
+ parameters: { combo: P('string', 'e.g. "Control_L+a" or "KP_0"', { required: true }),
800
+ hwnd: windowParam,
801
+ durationMs: P('number', 'key hold time in milliseconds, 20–2000') },
598
802
  output: outJSON(),
599
803
  isConcurrencySafe: () => false,
600
804
  timeoutMs: 15_000,
601
- async execute (args) { return cu.key(args.combo) },
805
+ execute: keyTarget,
602
806
  })
603
807
 
604
808
  reg({
605
809
  name: 'computer_type',
606
810
  description: "Type into the focused field; target it first. CJK/long text uses paste. Check receiver/readback. Passwords require existing explicit consent and allowPassword.",
607
811
  parameters: {
812
+ hwnd: windowParam,
608
813
  text: P('string', 'text to type', { required: true }),
609
814
  mode: P('string', 'unicode | paste (default: auto)'),
815
+ expectTarget: P('string', 'observed UIA field that must still have keyboard focus'),
610
816
  allowPassword: P('boolean', 'human consented to typing a password'),
611
817
  },
612
818
  output: outJSON(),
613
819
  isConcurrencySafe: () => false,
614
820
  timeoutMs: 30_000,
615
- async execute (args) { return cu.type(args.text, { mode: args.mode, allowPassword: args.allowPassword }) },
821
+ execute: typeField,
616
822
  })
617
823
 
618
824
  reg({
@@ -620,18 +826,15 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
620
826
  description: "Activate a known hwnd and require activated:true before capture/input. Other operations: minimize, maximize, restore, close, move. A failed activation stops a batch.",
621
827
  parameters: {
622
828
  hwnd: P('number', 'window handle', { required: true }),
829
+ observe: P('boolean', 'after activation, return controls of the confirmed receiver'),
623
830
  op: P('string', 'activate (default) | minimize | maximize | restore | close | move'),
624
831
  rect: P('string', 'for move: "x,y,w,h"'),
832
+ workHwnd: P('number', 'move target inside the work area of this observed window'),
625
833
  },
626
834
  output: outJSON(),
627
835
  isConcurrencySafe: () => false,
628
836
  timeoutMs: 15_000,
629
- async execute (args) {
630
- const sel = { hwnd: args.hwnd }
631
- const op = args.op || 'activate'
632
- if (op === 'activate') return cu.activateWindow(sel)
633
- return cu.windowOp(sel, op, rect(args.rect) || {})
634
- },
837
+ execute: manageWindow,
635
838
  })
636
839
 
637
840
  reg({
@@ -772,10 +975,11 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
772
975
  let pendingFrame
773
976
  const captureStep = async input => {
774
977
  const stepDelivery = deliveryMode(input.delivery)
775
- const frame = await captureFile(input)
978
+ const frame = await captureFile(input, exec)
776
979
  const pathOnly = delivery === 'path' || stepDelivery === 'path'
777
980
  pendingFrame = pathOnly ? undefined : frame
778
- return screenshotPathOnly(frame.value, pathOnly ? 'delivery-path' : 'earlier-batch-image')
981
+ screenshotPathOnly(frame.value, pathOnly ? 'delivery-path' : 'earlier-batch-image')
982
+ return bindShot(frame, exec)
779
983
  }
780
984
  // Batch still observes once at its final checkpoint. Capture the actual
781
985
  // result coordinates without re-resolving potentially stale mark ids.
@@ -797,6 +1001,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
797
1001
  if (policy.kind === 'state') { feedback = await captureFeedback(exec, policy, lastContext, delivery); return null }
798
1002
  const captured = await captureFeedback(exec, policy, lastContext, delivery)
799
1003
  const { observation, ...details } = captured
1004
+ if (details.feedback?.kind === 'state') { feedback = captured; return null }
800
1005
  automatic = observation
801
1006
  feedback = details
802
1007
  if (!automatic) return null
@@ -807,6 +1012,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
807
1012
  await attachScreenshot(ctx, exec, pendingFrame.value, pendingFrame.bytes, {
808
1013
  rules: config.feedbackRules, blocked: () => feedbackBlocked(exec),
809
1014
  })
1015
+ bindShot(pendingFrame, exec)
810
1016
  }
811
1017
  return { ...selectBatchScreenshot(result, checkpoint, feedback?.feedback?.kind), ...feedback }
812
1018
  },
@@ -869,15 +1075,15 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
869
1075
  const HANDLERS = {
870
1076
  computer_click: clickTarget,
871
1077
  computer_move: (a) => { const p = pt(a.at); return cu.move(p.x, p.y) },
872
- computer_drag: async (a) => cu.drag(await cu.resolveTarget(pt(a.from)), await cu.resolveTarget(pt(a.to)), { expectCursor: a.expectCursor, expectHwnd: a.hwnd }),
873
- computer_scroll: (a) => cu.scroll(a.dir, a.lines || 3, pt(a.at) ? { at: pt(a.at) } : {}),
1078
+ computer_drag: dragTarget,
1079
+ computer_scroll: scrollTarget,
874
1080
  computer_select: async (a) => {
875
1081
  const f = await cu.resolveTarget(pt(a.from)); const t = await cu.resolveTarget(pt(a.to))
876
1082
  return cu.selectRange({ fromX: f.x, fromY: f.y, toX: t.x, toY: t.y, fromClicks: a.clicks, toClicks: a.clicks, scrollClicks: a.scroll })
877
1083
  },
878
- computer_key: (a) => cu.key(a.combo),
879
- computer_type: (a) => cu.type(a.text, { mode: a.mode, allowPassword: a.allowPassword }),
880
- computer_window: (a) => ((a.op || 'activate') === 'activate' ? cu.activateWindow({ hwnd: a.hwnd }) : cu.windowOp({ hwnd: a.hwnd }, a.op, rect(a.rect) || {})),
1084
+ computer_key: keyTarget,
1085
+ computer_type: typeField,
1086
+ computer_window: manageWindow,
881
1087
  computer_clip: (a) => (a.text === undefined ? cu.clipRead() : cu.clipWrite(a.text)),
882
1088
  computer_launch: (a) => cu.launch(validateLaunchTarget(a.target), { args: validateLaunchArgs(a.args) }),
883
1089
  computer_focus: (a) => cu.focusField({ x: a.x, y: a.y, ...(a.hwnd !== undefined ? { hwnd: a.hwnd } : {}), ...(a.verifyCaret !== undefined ? { verifyCaret: a.verifyCaret } : {}) }),
@@ -888,28 +1094,9 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
888
1094
  // The observation tools and the meta tool were missing from this map, so a batch could not
889
1095
  // take a screenshot: "unknown tool computer_shot" (reported 2026-09-12). The map must cover
890
1096
  // the WHOLE surface — a caller should never have to know which subset happens to be wired.
891
- computer_ocr: async (a) => {
892
- let region
893
- if (a.region) {
894
- const parts = String(a.region).split(',').map(Number)
895
- if (parts.length !== 4 || parts.some(n => !Number.isFinite(n))) throw new Error('region must be "x,y,w,h"')
896
- region = { x: parts[0], y: parts[1], width: parts[2], height: parts[3] }
897
- }
898
- return cu.ocr(region)
899
- },
1097
+ computer_ocr: readOcr,
900
1098
  computer_state: observeState,
901
- computer_marks: async (a) => {
902
- const res = await cu.landmarks({ hwnd: a.hwnd, refresh: a.refresh })
903
- const res2 = {
904
- count: res.count, reused: !!res.reused, hwnd: res.hwnd,
905
- marks: res.marks.map(m => ({ id: m.id, role: m.role, name: m.name, center: [m.cx, m.cy] })),
906
- }
907
- if (a.shot) {
908
- const m = await cu.marks({ annotated: true, hwnd: a.hwnd, landmarkMap: res })
909
- if (m.annotated) res2.annotatedShot = saveShot(m.annotated)
910
- }
911
- return res2
912
- },
1099
+ computer_marks: readMarks,
913
1100
  computer_uia: queryUia,
914
1101
  computer_ctrl: (a, exec) => {
915
1102
  switch (a.action) {