dsh-codex-style-computer-use 2.3.0 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/tools.js CHANGED
@@ -17,7 +17,7 @@
17
17
 
18
18
  import { runBatch, actionRefusal } from './batch.js'
19
19
  import { saveOwnedShot } from './artifacts.js'
20
- import { attachScreenshot, renderScreenshot, selectBatchScreenshot, screenshotMetadata } from './image-output.js'
20
+ import { attachScreenshot, renderScreenshot, selectBatchScreenshot, screenshotMetadata, screenshotPathOnly } from './image-output.js'
21
21
  import { ObservationStore } from './observations.js'
22
22
  import { feedbackPolicy, feedbackActions, feedbackVerification, selectFeedbackDetail } from './feedback.js'
23
23
  import { collectCompactState, limitCompactFeedback, feedbackViewport } from './compact-feedback.js'
@@ -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'])
@@ -86,33 +99,108 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
86
99
  }
87
100
 
88
101
  // Shared by direct calls, explicit batch steps, and the batch checkpoint.
89
- const takeScreenshot = async (args, exec) => {
90
- // Refuse a bad value BEFORE the capture: a refused request that already wrote a file and
91
- // reports outcome:"not-dispatched" is a false receipt.
92
- const delivery = deliveryMode(args.delivery)
102
+ const captureFile = async (args, exec) => {
103
+ const hwnd = checkedWindow(args.hwnd)
104
+ if (hwnd && (args.region !== undefined || args.preset !== undefined)) throw new Error('Choose hwnd or region/preset for this capture')
93
105
  const r = rect(args.region)
94
106
  const shot = await cu.screenshot({
107
+ hwnd, clickWitness: !!hwnd,
95
108
  x: r && r.x, y: r && r.y, width: r && r.width, height: r && r.height,
96
109
  preset: args.preset, format: args.png ? 'png' : 'jpeg', cursor: true, wait: args.wait,
97
110
  maxWidth: r && r.width <= 900 ? r.width : 1280,
98
111
  })
112
+ syncObservationEpoch()
99
113
  const path = saveShot(shot.image, shot.mime === 'image/png' ? 'png' : 'jpg')
100
- const res = { path, mime: shot.mime, region: shot.region, ...screenshotMetadata(shot) }
101
- return attachScreenshot(ctx, exec, res, shot.image, { rules: config.feedbackRules, delivery })
114
+ return { value: { path, mime: shot.mime, region: shot.region, ...screenshotMetadata(shot) },
115
+ bytes: shot.image, geometry: shot.shotGeometry, witness: shot.shotWitness, hwnd: shot.hwnd, epoch: observationEpoch,
116
+ cycle: hooks?.contextOf?.(exec)?.cycleId ?? null, inputEpoch: cu.cooperation?.inputEpoch ?? null }
117
+ }
118
+ // Host attachments may be resized. Bind the delivered dimensions after routing.
119
+ const bindShot = (frame, exec) => {
120
+ const { value, geometry, hwnd } = frame
121
+ syncObservationEpoch()
122
+ if (geometry && hwnd && value.settled !== false && frame.epoch === observationEpoch &&
123
+ frame.inputEpoch === (cu.cooperation?.inputEpoch ?? null)) {
124
+ const stored = observations.publish(exec, 'screenshot', [], {
125
+ geometry, witness: frame.witness, hwnd, region: value.region, imageSize: value.imageSize, cycle: frame.cycle, inputEpoch: frame.inputEpoch,
126
+ })
127
+ if (stored.observation) {
128
+ value.screenshotId = stored.observation
129
+ value.hwnd = hwnd
130
+ value.pointUnits = 'With screenshotId, use pixels of imageSize. Request delivery:path for the saved file dimensions.'
131
+ } else delete value.screenshotId
132
+ } else delete value.screenshotId
133
+ return value
134
+ }
135
+ const takeScreenshot = async (args, exec) => {
136
+ const delivery = deliveryMode(args.delivery)
137
+ const frame = await captureFile(args, exec)
138
+ await attachScreenshot(ctx, exec, frame.value, frame.bytes, { rules: config.feedbackRules, delivery })
139
+ return bindShot(frame, exec)
102
140
  }
103
141
 
104
- const clickTarget = async (args) => {
105
- const target = args.mark ? { mark: args.mark } : pt(args.at)
106
- if (args.shift || args.dx !== undefined || args.dy !== undefined) {
142
+ const screenshotTarget = (args, exec) => {
143
+ syncObservationEpoch()
144
+ let frame
145
+ try { frame = observations.get(exec, args.screenshotId, 'screenshot') } catch {}
146
+ if (!frame?.targetsValid || frame.cycle !== (hooks?.contextOf?.(exec)?.cycleId ?? null) ||
147
+ frame.inputEpoch !== (cu.cooperation?.inputEpoch ?? null) || (args.hwnd !== undefined && args.hwnd !== frame.hwnd))
148
+ throw Object.assign(new Error('STALE_SCREENSHOT: capture the target window again in this Agent'), { code: 'STALE_SCREENSHOT', outcome: 'not-dispatched' })
149
+ const point = value => {
150
+ if (typeof value !== 'string' || !/^\s*\d+\s*,\s*\d+\s*$/.test(value)) throw Error('screenshotId requires an image point "x,y"')
151
+ const [x, y] = value.split(',').map(Number)
152
+ const [width, height] = frame.imageSize
153
+ const region = frame.region
154
+ if (x >= width || y >= height) throw Error('point outside screenshot imageSize')
155
+ return { x: region.x + Math.floor((x + 0.5) * region.width / width),
156
+ y: region.y + Math.floor((y + 0.5) * region.height / height) }
157
+ }
158
+ return { point, options: { expectHwnd: frame.hwnd, shotGeometry: frame.geometry, ...(frame.witness ? { shotWitness: frame.witness } : {}) } }
159
+ }
160
+ const clickTarget = async (args, exec) => {
161
+ const at = coordinatePair(args.at, args.x, args.y)
162
+ if (args.mark !== undefined && args.x !== undefined) throw Error('Choose a mark or a coordinate pair')
163
+ if (args.screenshotId !== undefined) {
164
+ if (args.mark !== undefined || args.dx !== undefined || args.dy !== undefined) throw Error('Use an exact image point with screenshotId')
165
+ const frame = screenshotTarget(args, exec)
166
+ return cu.click(frame.point(at), { ...args, ...frame.options })
167
+ }
168
+ const target = args.mark ? { mark: args.mark } : pt(at)
169
+ if (args.hwnd !== undefined || args.shift || args.dx !== undefined || args.dy !== undefined) {
107
170
  const p = await cu.resolveTarget(target)
171
+ if (p.expectHwnd && args.hwnd !== undefined && p.expectHwnd !== args.hwnd)
172
+ throw Error('Mark belongs to another window')
108
173
  const x = p.x + (args.dx || 0), y = p.y + (args.dy || 0)
109
- const options = { ...args, ...(p.expectHwnd ? { expectHwnd: p.expectHwnd } : {}) }
110
- return args.shift ? cu.shiftClick(x, y, options) : cu.click({ x, y }, options)
174
+ const options = { ...args, ...receiver(args), ...(p.expectHwnd ? { expectHwnd: p.expectHwnd } : {}) }
175
+ if (args.shift && args.hwnd === undefined && !args.ctrl && args.durationMs === undefined) return cu.shiftClick(x, y, options)
176
+ return cu.click({ x, y }, options)
111
177
  }
112
178
  return cu.click(target, args)
113
179
  }
180
+ const dragTarget = async (args, exec) => {
181
+ if (args.screenshotId !== undefined) {
182
+ const frame = screenshotTarget(args, exec)
183
+ return cu.drag(frame.point(args.from), frame.point(args.to), { ...frame.options, expectCursor: args.expectCursor })
184
+ }
185
+ return cu.drag(await cu.resolveTarget(pt(args.from)), await cu.resolveTarget(pt(args.to)), { expectCursor: args.expectCursor, expectHwnd: args.hwnd })
186
+ }
187
+ const scrollTarget = (args, exec) => {
188
+ const point = coordinatePair(args.at, args.x, args.y)
189
+ if (args.screenshotId !== undefined) {
190
+ const frame = screenshotTarget(args, exec)
191
+ return cu.scroll(args.dir, args.lines || 3, { ...frame.options, at: frame.point(point) })
192
+ }
193
+ const at = pt(point)
194
+ if (args.hwnd !== undefined && !at) throw Error('Specify a point or mark with an explicit scroll window')
195
+ return cu.scroll(args.dir, args.lines || 3, { ...(at ? { at } : {}), ...receiver(args) })
196
+ }
114
197
 
115
198
  const queryUia = async (args, exec) => {
199
+ if (args.focused) {
200
+ if (!checkedWindow(args.hwnd) || Object.keys(args).some(k => args[k] != null && !['focused', 'hwnd'].includes(k)))
201
+ throw Error('focused requires hwnd and reads only the current field')
202
+ return cu.call('uia', { hwnd: args.hwnd, focused: true })
203
+ }
116
204
  if (args.snapshot) return observations.get(exec, args.snapshot, 'uia', { offset: args.offset, limit: args.limit })
117
205
  const p = pt(args.at)
118
206
  if (p && p.x !== undefined) return cu.call('uiaFromPoint', { x: p.x, y: p.y })
@@ -125,15 +213,66 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
125
213
  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],
126
214
  { 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)
127
215
  }
216
+ const receiver = args => args.hwnd === undefined ? {} : { expectHwnd: checkedWindow(args.hwnd), strictHwnd: true }
217
+ const keyTarget = args => cu.key(args.combo, { durationMs: args.durationMs, ...receiver(args) })
218
+ const typeField = (args, exec) => {
219
+ if (args.expectTarget !== undefined && !observations.ownsTarget(exec, args.expectTarget)) {
220
+ throw Object.assign(new Error('TARGET_NOT_OBSERVED: query the expected field in this Agent before typing'), { code: 'TARGET_NOT_OBSERVED', outcome: 'not-dispatched' })
221
+ }
222
+ return cu.type(args.text, { mode: args.mode, allowPassword: args.allowPassword, expectTarget: args.expectTarget, ...receiver(args) })
223
+ }
128
224
  const actUia = (args, exec) => {
129
225
  if (args.target && !observations.ownsTarget(exec, args.target)) {
130
226
  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' })
131
227
  }
132
228
  return cu.uiaAct({ hwnd: args.hwnd, nameContains: args.name, automationId: args.id, target: args.target, allowRebind: args.rebind === true,
133
- role: args.role, action: args.action, value: args.value, requireUnique: true,
229
+ role: args.role, action: args.action, value: args.value, prefix: args.prefix, suffix: args.suffix, requireUnique: true,
134
230
  depth: args.depth ?? 6, maxNodes: 300, anchor: args.anchor, budgetMs: args.budgetMs ?? 1200 })
135
231
  }
232
+ const readMarks = async (args) => {
233
+ const res = await cu.landmarks({ hwnd: args.hwnd, refresh: args.refresh, uiaOnly: args.uiaOnly })
234
+ const res2 = {
235
+ count: res.count, reused: !!res.reused, hwnd: res.hwnd,
236
+ marks: res.marks.map(m => ({ id: m.id, role: m.role, name: m.name, center: [m.cx, m.cy] })),
237
+ }
238
+ if (args.shot) {
239
+ const m = await cu.marks({ annotated: true, hwnd: args.hwnd, landmarkMap: res })
240
+ if (m.annotated) res2.annotatedShot = saveShot(m.annotated)
241
+ }
242
+ return res2
243
+ }
244
+ const manageWindow = async (args, exec) => {
245
+ const op = args.op || 'activate'
246
+ if (args.workHwnd !== undefined) {
247
+ if (op !== 'move' || args.rect !== undefined || args.observe) throw Error('workHwnd requires move without rect or observe')
248
+ return cu.windowOp({ hwnd: checkedWindow(args.hwnd) }, 'move', { workHwnd: checkedWindow(args.workHwnd) })
249
+ }
250
+ if (op !== 'activate') {
251
+ if (args.observe) throw Error('observe requires window activation')
252
+ return cu.windowOp({ hwnd: args.hwnd }, op, rect(args.rect) || {})
253
+ }
254
+ const result = await cu.activateWindow({ hwnd: args.hwnd })
255
+ if (!args.observe || !result.activated) return result
256
+ try {
257
+ hooks?.assertOwnership?.(exec)
258
+ if (feedbackBlocked(exec)) return { ...result, observationSkipped: 'cancelled-or-paused' }
259
+ const observation = await queryUia({ hwnd: result.hwnd, limit: 16, targets: true }, exec)
260
+ return { ...result, observation }
261
+ } catch (error) { return { ...result, observationError: String(error.message || error) } }
262
+ }
263
+ const readOcr = async args => {
264
+ const hwnd = checkedWindow(args.hwnd)
265
+ if (args.region !== undefined && String(args.region).trim().split(/[,\s]+/).length !== 4) throw Error('region must be "x,y,w,h"')
266
+ const region = args.region === undefined ? undefined : rect(args.region)
267
+ if (args.region !== undefined && (!region || region.width <= 0 || region.height <= 0)) throw Error('region must be "x,y,w,h"')
268
+ return cu.ocr(hwnd ? { ...region, hwnd } : region)
269
+ }
136
270
  const observeState = async (args, exec) => {
271
+ if (args.appQuery !== undefined) {
272
+ if (Object.keys(args).some(k => args[k] != null && k !== 'appQuery')) throw Error('Use appQuery by itself')
273
+ return cu.call('windows', { appQuery: args.appQuery })
274
+ }
275
+ if (args.hwnd !== undefined) return cu.call('windows', { inspectHwnd: checkedWindow(args.hwnd) })
137
276
  if (args.snapshot) return observations.get(exec, args.snapshot, 'state', { offset: args.offset, limit: args.limit })
138
277
  const result = args.windows ? await cu.call('windows', {}) : await cu.screenState({ uiaDepth: args.depth })
139
278
  syncObservationEpoch()
@@ -172,6 +311,46 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
172
311
  if (feedbackBlocked(exec)) throw new Error('compact observation cancelled-or-paused')
173
312
  hooks?.assertOwnership?.(exec)
174
313
  }
314
+ const args = context.args || {}, receipt = context.receipt || {}
315
+ let owner = args.hwnd || receipt.actionHwnd
316
+ if (!owner && args.screenshotId) owner = observations.get(exec, args.screenshotId, 'screenshot')?.hwnd
317
+ owner ||= receipt.startHwnd || receipt.focus?.expected || receipt.hwnd
318
+ // Explicit verification rectangles retain their desktop-coordinate contract.
319
+ if (owner && !feedbackViewport(args, receipt).region) {
320
+ checkAllowed()
321
+ const view = await cu.call('windows', { feedbackHwnd: owner })
322
+ const target = view.target
323
+ if (!target?.hwnd) throw Error('Feedback window unavailable. Observe the intended window again.')
324
+ const identity = { ownerHwnd: view.owner, ownerTitle: view.ownerTitle, hwnd: target.hwnd, title: target.title, windowClass: target.class, popup: view.popup }
325
+ const controls = async () => {
326
+ checkAllowed()
327
+ const ui = await queryUia({ hwnd: target.hwnd, targets: true, limit: compact ? 12 : 48, budgetMs: compact ? 400 : 1000 }, exec)
328
+ const result = { ...identity, snapshot: ui.observation, truncated: ui.truncated,
329
+ controls: compact ? (ui.elements || []).map(({ name, role, automationId, target, enabled }) => ({ name, role, automationId, target, enabled })) : ui.elements }
330
+ if (!view.popup && (context.tool === 'computer_type' || context.tool === 'computer_key') && target.active) {
331
+ try { result.focused = await queryUia({ hwnd: target.hwnd, focused: true }, exec) }
332
+ catch (error) { result.focusError = String(error.message).slice(0, 200) }
333
+ }
334
+ return result
335
+ }
336
+ if (policy.kind === 'state') {
337
+ const envelope = { observation: await controls(), feedback: policy, verification: feedbackVerification }
338
+ return compact ? limitCompactFeedback(envelope) : envelope
339
+ }
340
+ checkAllowed()
341
+ let observation
342
+ try { observation = await takeScreenshot({ hwnd: target.hwnd, delivery }, exec) }
343
+ catch (error) {
344
+ if (!view.popup || !/CAPTURE_UNAVAILABLE|SCREENSHOT_WINDOW_UNAVAILABLE/.test(error.message)) throw error
345
+ return { observation: await controls(), feedback: { ...policy, kind: 'state', reason: 'popup capture unavailable' }, verification: feedbackVerification }
346
+ }
347
+ Object.assign(observation, identity)
348
+ if (view.popup) {
349
+ try { Object.assign(observation, await controls()) }
350
+ catch (error) { observation.controlsError = String(error.message).slice(0, 200) }
351
+ }
352
+ return { observation, feedback: policy, verification: feedbackVerification }
353
+ }
175
354
  const observation = policy.kind === 'state'
176
355
  ? compact ? await collectCompactState(cu, { ...context, checkAllowed,
177
356
  archive: raw => hooks?.archiveFeedback ? hooks.archiveFeedback(exec, raw) : archiveFeedback(exec, raw) }) : await observeState({}, exec)
@@ -365,6 +544,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
365
544
  name: 'computer_shot',
366
545
  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.",
367
546
  parameters: {
547
+ hwnd: P('number', 'capture this visible window and return screenshotId for image-pixel actions'),
368
548
  region: P('string', 'crop "x,y,w,h" (default: whole screen)'),
369
549
  preset: P('string', 'taskbar'),
370
550
  png: P('boolean', 'PNG instead of JPEG'),
@@ -381,11 +561,12 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
381
561
  name: 'computer_ocr',
382
562
  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.",
383
563
  parameters: {
564
+ hwnd: windowParam,
384
565
  region: P('string', 'crop "x,y,w,h" (default: whole screen)'),
385
566
  },
386
567
  output: out((a, v) => {
387
568
  if (!v || !v.lines) return [{ type: 'text', text: 'no text' }]
388
- const head = `ocr ${v.language} region=${v.region ? v.region.join(',') : ''} lines=${v.lines.length}`
569
+ const head = `ocr ${v.language}${v.hwnd ? ' hwnd=' + v.hwnd : ''} region=${v.region ? v.region.join(',') : ''} lines=${v.lines.length}`
389
570
  const body = v.lines.map(l => {
390
571
  const w0 = l.words[0]
391
572
  return `${w0 ? `@${w0.x},${w0.y} ` : ''}${l.text}`
@@ -394,21 +575,15 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
394
575
  }),
395
576
  isConcurrencySafe: () => false,
396
577
  timeoutMs: 30_000,
397
- async execute (args) {
398
- let region
399
- if (args.region) {
400
- const parts = String(args.region).split(',').map(Number)
401
- if (parts.length !== 4 || parts.some(n => !Number.isFinite(n))) throw new Error('region must be "x,y,w,h"')
402
- region = { x: parts[0], y: parts[1], width: parts[2], height: parts[3] }
403
- }
404
- return cu.ocr(region)
405
- },
578
+ execute: readOcr,
406
579
  })
407
580
 
408
581
  reg({
409
582
  name: 'computer_state',
410
583
  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.",
411
584
  parameters: {
585
+ appQuery: P('string', 'search registered Start apps by name or AppID; includes matching visible windows'),
586
+ hwnd: P('number', 'inspect one window, owned popups, work areas and sampled pixel receivers'),
412
587
  windows: P('boolean', 'windows only (no tree)'),
413
588
  depth: P('number', 'tree depth (default 6)'),
414
589
  since: P('string', 'base observation ID for changes; invalid base returns full'),
@@ -438,24 +613,14 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
438
613
  }),
439
614
  isConcurrencySafe: () => false,
440
615
  timeoutMs: 45_000,
441
- async execute (args) {
442
- const res = await cu.landmarks({ hwnd: args.hwnd, refresh: args.refresh, uiaOnly: args.uiaOnly })
443
- const res2 = {
444
- count: res.count, reused: !!res.reused, hwnd: res.hwnd,
445
- marks: res.marks.map(m => ({ id: m.id, role: m.role, name: m.name, center: [m.cx, m.cy] })),
446
- }
447
- if (args.shot) {
448
- const m = await cu.marks({ annotated: true, hwnd: args.hwnd, landmarkMap: res })
449
- if (m.annotated) res2.annotatedShot = saveShot(m.annotated)
450
- }
451
- return res2
452
- },
616
+ execute: readMarks,
453
617
  })
454
618
 
455
619
  reg({
456
620
  name: 'computer_uia',
457
621
  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.",
458
622
  parameters: {
623
+ focused: P('boolean', 'with hwnd only: read the focused field and selection'),
459
624
  at: P('string', 'hit test at "x,y"'),
460
625
  hwnd: P('number', 'required window scope for a tree query; at needs no tree'),
461
626
  role: P('string', 'Button | Edit | Hyperlink | TabItem | ...'),
@@ -485,8 +650,10 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
485
650
  name: P('string', 'element name substring'),
486
651
  id: P('string', 'exact AutomationId from UIA; scope with hwnd'),
487
652
  role: P('string', 'TabItem | Button | ListItem | ComboBox | Edit | MenuItem'),
488
- action: P('string', 'invoke (default) | select | expand | collapse | toggle | setValue | focus | scrollIntoView'),
489
- value: P('string', 'value for setValue'),
653
+ action: P('string', 'invoke | select | addToSelection | removeFromSelection | selectText | expand | collapse | toggle | setValue | focus | scrollIntoView | scroll (value: up/down/left/right)'),
654
+ value: P('string', 'setValue: text or slider number; selectText: exact text to select'),
655
+ prefix: P('string', 'selectText: immediately preceding context for repeated text'),
656
+ suffix: P('string', 'selectText: immediately following context for repeated text'),
490
657
  depth: P('number', 'tree depth, default 6; broader traversal needs anchor'),
491
658
  anchor: P('string', 'observed "x,y" inside hwnd; narrow selector search'),
492
659
  budgetMs: P('number', 'soft traversal budget 100–5000 ms (default 1200)'),
@@ -504,6 +671,9 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
504
671
  name: 'computer_click',
505
672
  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.",
506
673
  parameters: {
674
+ screenshotId: screenshotIdParam,
675
+ hwnd: windowParam,
676
+ x: P('number', 'coordinate pair, alternative to at'), y: P('number', 'coordinate pair'),
507
677
  mark: P('string', 'mark id, e.g. "M7" (preferred)'),
508
678
  at: P('string', '"x,y" instead of a mark'),
509
679
  dx: P('number', 'offset from the mark centre: +x px'),
@@ -511,6 +681,8 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
511
681
  button: P('string', 'left (default) | right | middle'),
512
682
  clicks: P('number', '1 | 2 (double) | 3 (triple)'),
513
683
  shift: P('boolean', 'hold SHIFT (range selection)'),
684
+ ctrl: P('boolean', 'hold CTRL during the click (multi-select)'),
685
+ durationMs: P('number', 'mouse button hold time in milliseconds, 20–2000'),
514
686
  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'),
515
687
  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'),
516
688
  },
@@ -538,6 +710,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
538
710
  name: 'computer_drag',
539
711
  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.",
540
712
  parameters: {
713
+ screenshotId: screenshotIdParam,
541
714
  from: P('string', '"M3" or "x,y"', { required: true }),
542
715
  to: P('string', '"M7" or "x,y"', { required: true }),
543
716
  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.'),
@@ -546,15 +719,16 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
546
719
  output: outJSON(),
547
720
  isConcurrencySafe: () => false,
548
721
  timeoutMs: 15_000,
549
- async execute (args) {
550
- return cu.drag(await cu.resolveTarget(pt(args.from)), await cu.resolveTarget(pt(args.to)), { expectCursor: args.expectCursor, expectHwnd: args.hwnd })
551
- },
722
+ execute: dragTarget,
552
723
  })
553
724
 
554
725
  reg({
555
726
  name: 'computer_scroll',
556
727
  description: "Wheel at a mark/point, or at the current pointer when at is omitted. Refresh marks after scrolling.",
557
728
  parameters: {
729
+ screenshotId: screenshotIdParam,
730
+ hwnd: windowParam,
731
+ x: P('number', 'coordinate pair, alternative to at'), y: P('number', 'coordinate pair'),
558
732
  dir: P('string', 'up | down | left | right', { required: true }),
559
733
  at: P('string', 'scroll at "M3" or "x,y"'),
560
734
  lines: P('number', 'notches (default 3)'),
@@ -562,10 +736,7 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
562
736
  output: outJSON(),
563
737
  isConcurrencySafe: () => false,
564
738
  timeoutMs: 15_000,
565
- async execute (args) {
566
- const at = pt(args.at)
567
- return cu.scroll(args.dir, args.lines || 3, at ? { at } : {})
568
- },
739
+ execute: scrollTarget,
569
740
  })
570
741
 
571
742
  reg({
@@ -593,25 +764,29 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
593
764
  reg({
594
765
  name: 'computer_key',
595
766
  description: "Press a key combo, e.g. ctrl+shift+t. Activate the target first; missing target or failed refocus refuses input.",
596
- parameters: { combo: P('string', 'e.g. "ctrl+a"', { required: true }) },
767
+ parameters: { combo: P('string', 'e.g. "Control_L+a" or "KP_0"', { required: true }),
768
+ hwnd: windowParam,
769
+ durationMs: P('number', 'key hold time in milliseconds, 20–2000') },
597
770
  output: outJSON(),
598
771
  isConcurrencySafe: () => false,
599
772
  timeoutMs: 15_000,
600
- async execute (args) { return cu.key(args.combo) },
773
+ execute: keyTarget,
601
774
  })
602
775
 
603
776
  reg({
604
777
  name: 'computer_type',
605
778
  description: "Type into the focused field; target it first. CJK/long text uses paste. Check receiver/readback. Passwords require existing explicit consent and allowPassword.",
606
779
  parameters: {
780
+ hwnd: windowParam,
607
781
  text: P('string', 'text to type', { required: true }),
608
782
  mode: P('string', 'unicode | paste (default: auto)'),
783
+ expectTarget: P('string', 'observed UIA field that must still have keyboard focus'),
609
784
  allowPassword: P('boolean', 'human consented to typing a password'),
610
785
  },
611
786
  output: outJSON(),
612
787
  isConcurrencySafe: () => false,
613
788
  timeoutMs: 30_000,
614
- async execute (args) { return cu.type(args.text, { mode: args.mode, allowPassword: args.allowPassword }) },
789
+ execute: typeField,
615
790
  })
616
791
 
617
792
  reg({
@@ -619,18 +794,15 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
619
794
  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.",
620
795
  parameters: {
621
796
  hwnd: P('number', 'window handle', { required: true }),
797
+ observe: P('boolean', 'after activation, return controls of the confirmed receiver'),
622
798
  op: P('string', 'activate (default) | minimize | maximize | restore | close | move'),
623
799
  rect: P('string', 'for move: "x,y,w,h"'),
800
+ workHwnd: P('number', 'move target inside the work area of this observed window'),
624
801
  },
625
802
  output: outJSON(),
626
803
  isConcurrencySafe: () => false,
627
804
  timeoutMs: 15_000,
628
- async execute (args) {
629
- const sel = { hwnd: args.hwnd }
630
- const op = args.op || 'activate'
631
- if (op === 'activate') return cu.activateWindow(sel)
632
- return cu.windowOp(sel, op, rect(args.rect) || {})
633
- },
805
+ execute: manageWindow,
634
806
  })
635
807
 
636
808
  reg({
@@ -766,9 +938,20 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
766
938
  let automatic, feedback, lastContext = {}
767
939
  const detail = selectFeedbackDetail(args.feedback,
768
940
  config.actionFeedback === false ? 'none' : config.actionFeedbackDetail ?? 'compact')
941
+ // Keep only the latest eligible frame's bytes until we know whether a checkpoint
942
+ // supersedes it. All completed explicit captures have their own local file.
943
+ let pendingFrame
944
+ const captureStep = async input => {
945
+ const stepDelivery = deliveryMode(input.delivery)
946
+ const frame = await captureFile(input, exec)
947
+ const pathOnly = delivery === 'path' || stepDelivery === 'path'
948
+ pendingFrame = pathOnly ? undefined : frame
949
+ screenshotPathOnly(frame.value, pathOnly ? 'delivery-path' : 'earlier-batch-image')
950
+ return bindShot(frame, exec)
951
+ }
769
952
  // Batch still observes once at its final checkpoint. Capture the actual
770
953
  // result coordinates without re-resolving potentially stale mark ids.
771
- const feedbackHandlers = Object.fromEntries(Object.entries(HANDLERS).map(([name, handler]) => [name,
954
+ const feedbackHandlers = Object.fromEntries(Object.entries({ ...HANDLERS, computer_shot: captureStep }).map(([name, handler]) => [name,
772
955
  async (input, context) => {
773
956
  const receipt = await handler(input, context)
774
957
  lastContext = { args: input, receipt, tool: name }
@@ -786,12 +969,20 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
786
969
  if (policy.kind === 'state') { feedback = await captureFeedback(exec, policy, lastContext, delivery); return null }
787
970
  const captured = await captureFeedback(exec, policy, lastContext, delivery)
788
971
  const { observation, ...details } = captured
972
+ if (details.feedback?.kind === 'state') { feedback = captured; return null }
789
973
  automatic = observation
790
974
  feedback = details
791
975
  if (!automatic) return null
792
976
  return automatic.path
793
977
  } })
794
- return { ...selectBatchScreenshot(result, feedback?.observation ?? automatic, feedback?.feedback?.kind, delivery), ...feedback }
978
+ const checkpoint = feedback?.observation ?? automatic
979
+ if (!checkpoint && pendingFrame) {
980
+ await attachScreenshot(ctx, exec, pendingFrame.value, pendingFrame.bytes, {
981
+ rules: config.feedbackRules, blocked: () => feedbackBlocked(exec),
982
+ })
983
+ bindShot(pendingFrame, exec)
984
+ }
985
+ return { ...selectBatchScreenshot(result, checkpoint, feedback?.feedback?.kind), ...feedback }
795
986
  },
796
987
  })
797
988
 
@@ -852,15 +1043,15 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
852
1043
  const HANDLERS = {
853
1044
  computer_click: clickTarget,
854
1045
  computer_move: (a) => { const p = pt(a.at); return cu.move(p.x, p.y) },
855
- computer_drag: async (a) => cu.drag(await cu.resolveTarget(pt(a.from)), await cu.resolveTarget(pt(a.to)), { expectCursor: a.expectCursor, expectHwnd: a.hwnd }),
856
- computer_scroll: (a) => cu.scroll(a.dir, a.lines || 3, pt(a.at) ? { at: pt(a.at) } : {}),
1046
+ computer_drag: dragTarget,
1047
+ computer_scroll: scrollTarget,
857
1048
  computer_select: async (a) => {
858
1049
  const f = await cu.resolveTarget(pt(a.from)); const t = await cu.resolveTarget(pt(a.to))
859
1050
  return cu.selectRange({ fromX: f.x, fromY: f.y, toX: t.x, toY: t.y, fromClicks: a.clicks, toClicks: a.clicks, scrollClicks: a.scroll })
860
1051
  },
861
- computer_key: (a) => cu.key(a.combo),
862
- computer_type: (a) => cu.type(a.text, { mode: a.mode, allowPassword: a.allowPassword }),
863
- computer_window: (a) => ((a.op || 'activate') === 'activate' ? cu.activateWindow({ hwnd: a.hwnd }) : cu.windowOp({ hwnd: a.hwnd }, a.op, rect(a.rect) || {})),
1052
+ computer_key: keyTarget,
1053
+ computer_type: typeField,
1054
+ computer_window: manageWindow,
864
1055
  computer_clip: (a) => (a.text === undefined ? cu.clipRead() : cu.clipWrite(a.text)),
865
1056
  computer_launch: (a) => cu.launch(validateLaunchTarget(a.target), { args: validateLaunchArgs(a.args) }),
866
1057
  computer_focus: (a) => cu.focusField({ x: a.x, y: a.y, ...(a.hwnd !== undefined ? { hwnd: a.hwnd } : {}), ...(a.verifyCaret !== undefined ? { verifyCaret: a.verifyCaret } : {}) }),
@@ -871,29 +1062,9 @@ export function registerTools ({ ctx, cu, config, dataDir, log, snapshotPath, de
871
1062
  // The observation tools and the meta tool were missing from this map, so a batch could not
872
1063
  // take a screenshot: "unknown tool computer_shot" (reported 2026-09-12). The map must cover
873
1064
  // the WHOLE surface — a caller should never have to know which subset happens to be wired.
874
- computer_shot: takeScreenshot,
875
- computer_ocr: async (a) => {
876
- let region
877
- if (a.region) {
878
- const parts = String(a.region).split(',').map(Number)
879
- if (parts.length !== 4 || parts.some(n => !Number.isFinite(n))) throw new Error('region must be "x,y,w,h"')
880
- region = { x: parts[0], y: parts[1], width: parts[2], height: parts[3] }
881
- }
882
- return cu.ocr(region)
883
- },
1065
+ computer_ocr: readOcr,
884
1066
  computer_state: observeState,
885
- computer_marks: async (a) => {
886
- const res = await cu.landmarks({ hwnd: a.hwnd, refresh: a.refresh })
887
- const res2 = {
888
- count: res.count, reused: !!res.reused, hwnd: res.hwnd,
889
- marks: res.marks.map(m => ({ id: m.id, role: m.role, name: m.name, center: [m.cx, m.cy] })),
890
- }
891
- if (a.shot) {
892
- const m = await cu.marks({ annotated: true, hwnd: a.hwnd, landmarkMap: res })
893
- if (m.annotated) res2.annotatedShot = saveShot(m.annotated)
894
- }
895
- return res2
896
- },
1067
+ computer_marks: readMarks,
897
1068
  computer_uia: queryUia,
898
1069
  computer_ctrl: (a, exec) => {
899
1070
  switch (a.action) {
package/mcp/src/tools.js CHANGED
@@ -115,6 +115,8 @@ const tools = [
115
115
  x: { type: 'integer' }, y: { type: 'integer' },
116
116
  button: { type: 'string', enum: ['left', 'right', 'middle'] },
117
117
  clicks: { type: 'integer', minimum: 1, maximum: 3, description: '2=double 3=triple' },
118
+ ctrl: { type: 'boolean' }, shift: { type: 'boolean' },
119
+ durationMs: { type: 'integer', minimum: 20, maximum: 2000 },
118
120
  verificationRegion: { type: 'string', description: 'Expected effect rectangle "x,y,w,h" in screen pixels, independent of click location. Pixel change does not prove semantic success.' },
119
121
  },
120
122
  }),
@@ -139,7 +141,8 @@ const tools = [
139
141
  }),
140
142
  tool('cu_key', 'Press a key combo, e.g. "ctrl+shift+t", "enter", "alt+f4", "win".', {
141
143
  type: 'object', additionalProperties: false, required: ['combo'],
142
- properties: { combo: { type: 'string' }, holdMs: { type: 'integer', maximum: 5000 } },
144
+ properties: { combo: { type: 'string' }, holdMs: { type: 'integer', maximum: 5000 },
145
+ durationMs: { type: 'integer', minimum: 20, maximum: 2000 } },
143
146
  }),
144
147
  tool('cu_type', 'Type text. CJK/long text is auto-pasted via clipboard (IME-proof); ASCII short text uses SendInput unicode events. Refuses password fields unless allowPassword is set (ask the human first).', {
145
148
  type: 'object', additionalProperties: false, required: ['text'],
@@ -210,7 +213,7 @@ const handlers = {
210
213
  cu_drag: a => cu.drag(targetOf({ mark: a.fromMark, x: a.fromX, y: a.fromY }),
211
214
  targetOf({ mark: a.toMark, x: a.toX, y: a.toY }), { durationMs: a.durationMs, expectCursor: a.expectCursor, expectHwnd: a.hwnd }),
212
215
  cu_scroll: a => cu.scroll(a.direction, a.lines ?? 3, a.mark || a.x !== undefined ? { at: targetOf(a) } : {}),
213
- cu_key: a => cu.key(parseKeyCommand(a.combo).combo, { holdMs: a.holdMs }),
216
+ cu_key: a => cu.key(parseKeyCommand(a.combo).combo, { holdMs: a.holdMs, durationMs: a.durationMs }),
214
217
  cu_type: a => cu.type(a.text, { mode: a.mode, allowPassword: a.allowPassword }),
215
218
  cu_clipboard_write: a => cu.clipWrite(a.text),
216
219
  cu_activate_window: a => cu.activateWindow(a),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-codex-style-computer-use",
3
- "version": "2.3.0",
3
+ "version": "2.3.2",
4
4
  "description": "Codex-style Computer Use for DeepSeek Harness: Windows desktop control, screenshots, UI Automation, human input handoff, approval gates and prebuilt native workers. Install and update from dsh-market without PowerShell 7 or build steps.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -99,4 +99,4 @@
99
99
  "url": "https://github.com/ltmroberthk915/dsh-computer-use/issues"
100
100
  },
101
101
  "icon": "./icon.svg"
102
- }
102
+ }
@@ -31,7 +31,7 @@ const excluded = {
31
31
  'test-approval-attention.mjs': 'alias imports test-attention.mjs, which is already run directly',
32
32
  }
33
33
  const reviewed = new Set([
34
- 'action-feedback', 'agent-pointer', 'approval-attribution', 'approval-channel', 'ask-invariants', 'ask-merge', 'ask-orphan', 'ask-release',
34
+ 'action-feedback', 'agent-pointer', 'argument-recovery', 'approval-attribution', 'approval-channel', 'ask-invariants', 'ask-merge', 'ask-orphan', 'ask-release',
35
35
  'attention-native', 'attention', 'audit-completion', 'batch-coverage', 'buildusermessage', 'bundled-skill', 'client-export',
36
36
  'coactive', 'compact-feedback', 'control-targets', 'core-system-recovery', 'cursor', 'cycle-completion',
37
37
  'cycle-no-timeout', 'cycle-open', 'desktop-acceptance-io', 'desktop-ownership', 'drag-options', 'evidence-protocol',
@@ -42,6 +42,7 @@ const reviewed = new Set([
42
42
  'release-channel', 'renders', 'root-integration', 'session-identity', 'skill-gate', 'steer-message-shape',
43
43
  'task-rules', 'terminal-cleanup', 'timeout-branch', 'turnend-agent', 'turnend-rootagent',
44
44
  'ui-geometry', 'uia-budget', 'uia-read-timeout', 'uia-native', 'uia-targets-native', 'verification-region', 'window-management-key',
45
+ 'window-screenshot',
45
46
  ].map(name => `test-${name}.mjs`))
46
47
  const files = fs.readdirSync(path.join(root, 'build')).filter(name => /^test-.+\.mjs$/.test(name)).sort()
47
48
  const unreviewed = files.filter(name => !reviewed.has(name) && !excluded[name])