@copylee/dsh-computer-use 0.16.0 → 0.16.1

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/helper/Program.cs CHANGED
@@ -227,6 +227,7 @@ namespace DshComputerUse
227
227
  case "ocr": return Ocr.Read(r);
228
228
  case "marks": return Uia.Marks(r);
229
229
  case "password_focus": return Uia.PasswordFocus();
230
+ case "focused_value": return Uia.FocusedValue(Math.Max(64, Math.Min(20000, Args.Int(r, "maxChars", 4000))));
230
231
  case "ui_point_click": return Uia.ClickAtPoint(r);
231
232
  case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(r); return null;
232
233
  case "overlay_pause": Overlay.SetPaused(Args.Bool(r, "paused", false)); return null;
package/helper/Uia.cs CHANGED
@@ -815,6 +815,44 @@ namespace DshComputerUse
815
815
  return d;
816
816
  }
817
817
 
818
+ /**
819
+ * The focused control's ValuePattern value (capped), so a `type` can be checked
820
+ * against what the field now holds. Never reads password fields.
821
+ */
822
+ public static object FocusedValue(int maxChars)
823
+ {
824
+ bool readable = false;
825
+ string value = "", role = "", name = "";
826
+ var worker = new Thread(delegate ()
827
+ {
828
+ try
829
+ {
830
+ var focused = AutomationElement.FocusedElement;
831
+ if (focused == null || IsPasswordElement(focused)) return;
832
+ role = focused.Current.ControlType.ProgrammaticName.Replace("ControlType.", "");
833
+ name = focused.Current.Name ?? "";
834
+ object pattern;
835
+ if (focused.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
836
+ {
837
+ string v = ((ValuePattern)pattern).Current.Value ?? "";
838
+ value = v.Length > maxChars ? v.Substring(v.Length - maxChars) : v;
839
+ readable = true;
840
+ }
841
+ }
842
+ catch (Exception) { }
843
+ });
844
+ worker.IsBackground = true;
845
+ worker.SetApartmentState(ApartmentState.MTA);
846
+ worker.Start();
847
+ worker.Join(800);
848
+ var d = new Dictionary<string, object>();
849
+ d["readable"] = readable;
850
+ d["value"] = readable ? value : "";
851
+ d["role"] = role;
852
+ d["name"] = name.Length > 60 ? name.Substring(0, 60) : name;
853
+ return d;
854
+ }
855
+
818
856
  /** Lightweight bounded lookup of the UIA control at physical point (x, y) for user-takeover feedback. */
819
857
  public static void DescribeAtPoint(int x, int y, out string role, out string name, out bool isPassword)
820
858
  {
package/lib/index.js CHANGED
@@ -1768,6 +1768,14 @@ const MUTATING = /* @__PURE__ */ new Set([
1768
1768
  "mouse_move",
1769
1769
  "ui_action"
1770
1770
  ]);
1771
+ /** Whitespace-insensitive tail of typed text, as it should appear in the field afterwards. */
1772
+ function typedTextLanded(typed, fieldValue) {
1773
+ const norm = (v) => v.replace(/\s+/g, "");
1774
+ const want = norm(typed);
1775
+ if (want === "") return true;
1776
+ const tail = want.length > 24 ? want.slice(-24) : want;
1777
+ return norm(fieldValue).includes(tail);
1778
+ }
1771
1779
  /** Actions that wait for the user to stop typing before they run. */
1772
1780
  const INPUT = new Set([...MUTATING].filter((action) => action !== "mouse_move"));
1773
1781
  /** Actions whose input goes to the foreground window. */
@@ -2741,6 +2749,22 @@ var Computer = class Computer {
2741
2749
  }
2742
2750
  return `\nRecent user actions during takeover (screenshot coordinates):\n${lines.join("\n")}\nRespect what the user just did and adapt your plan accordingly (do not undo or overwrite their changes).`;
2743
2751
  }
2752
+ /** Compare the focused field with what was just typed (ValuePattern only; rich editors report 'sent'). */
2753
+ async readBackTyped(text) {
2754
+ const field = await this.helper.call("focused_value", { maxChars: Math.min(2e4, text.length + 4e3) }, 1500).catch(() => null);
2755
+ if (!field?.readable) return {
2756
+ verification: "sent",
2757
+ note: ""
2758
+ };
2759
+ if (typedTextLanded(text, field.value ?? "")) return {
2760
+ verification: "observed",
2761
+ note: " Verified: the focused field contains it."
2762
+ };
2763
+ return {
2764
+ verification: "unconfirmed",
2765
+ note: ` Unconfirmed: the focused ${`${field.role || "field"}${field.name ? ` "${field.name.slice(0, 40)}"` : ""}`} does not show the typed text (autocomplete, an input method or a different focus may have taken it). Check before continuing.`
2766
+ };
2767
+ }
2744
2768
  /** Run one action. Returns text plus an image for screenshot/zoom. */
2745
2769
  async run(input, call) {
2746
2770
  if (call.signal.aborted) throw new Error("Cancelled.");
@@ -2998,7 +3022,12 @@ var Computer = class Computer {
2998
3022
  await this.sendKeys(call, parseKeys("ctrl+a"));
2999
3023
  await setTimeout$1(50, void 0, { signal: call.signal });
3000
3024
  }
3001
- return { text: `${await this.enterText(text, call)}${input.replace === true ? " (replaced existing text)" : ""}${into}` };
3025
+ const entered = `${await this.enterText(text, call)}${input.replace === true ? " (replaced existing text)" : ""}${into}`;
3026
+ const check = await this.readBackTyped(text);
3027
+ return {
3028
+ text: `${entered}${check.note}`,
3029
+ verification: check.verification
3030
+ };
3002
3031
  }
3003
3032
  case "key": {
3004
3033
  const combos = parseKeys(input.text ?? "");
@@ -11105,6 +11134,34 @@ function toJson(ref) {
11105
11134
  } }
11106
11135
  };
11107
11136
  }
11137
+ /** A mouse action aimed by coordinate (not by target): only valid on the screen the model last saw. */
11138
+ function usesScreenCoordinates(input) {
11139
+ if (input.target !== void 0 && input.target !== "") return false;
11140
+ return (input.action === "left_click" || input.action === "right_click" || input.action === "middle_click" || input.action === "double_click" || input.action === "triple_click" || input.action === "mouse_move" || input.action === "left_click_drag" || input.action === "scroll" || input.action === "left_mouse_down") && Array.isArray(input.coordinate);
11141
+ }
11142
+ /** How the foreground changed in a way that invalidates planned coordinates, or undefined. */
11143
+ function screenChange(before, after) {
11144
+ if (!before || !after) return void 0;
11145
+ if (after.hwnd !== before.hwnd) return `the foreground switched to ${after.exe} ("${after.title.slice(0, 50)}") — a new window or dialog`;
11146
+ if (isBrowser(after) && after.title !== before.title) return `${after.exe} navigated to "${after.title.slice(0, 50)}"`;
11147
+ }
11148
+ /** Observation budget for element lists: every row stays short, and the list stops at a size the model can afford. */
11149
+ const OBSERVATION_MAX_CHARS = 12e3;
11150
+ const OBSERVATION_MAX_LINE = 300;
11151
+ function capObservation(text, maxChars = OBSERVATION_MAX_CHARS, maxLine = OBSERVATION_MAX_LINE) {
11152
+ const lines = text.split("\n").map((line) => line.length > maxLine ? `${line.slice(0, maxLine - 1)}…` : line);
11153
+ const out = [];
11154
+ let used = 0;
11155
+ for (const [index, line] of lines.entries()) {
11156
+ if (index > 0 && used + line.length + 1 > maxChars) {
11157
+ out.push(`… ${lines.length - index} more lines omitted (output capped at ${Math.round(maxChars / 1e3)}k characters). Narrow it with query, role, hwnd or max.`);
11158
+ break;
11159
+ }
11160
+ out.push(line);
11161
+ used += line.length + 1;
11162
+ }
11163
+ return out.join("\n");
11164
+ }
11108
11165
  async function withShot(host, text, shot, call) {
11109
11166
  if (shot === void 0) return { text };
11110
11167
  if (shot === "unchanged") return { text: `${text}
@@ -11310,7 +11367,7 @@ function createTools(host) {
11310
11367
  }));
11311
11368
  tools.push(defineTool({
11312
11369
  name: "computer_batch",
11313
- description: "Run several computer actions in order in one call (or replay a saved macro by name), then get one screenshot (taken once the screen settles, so do not end with a wait). Stops at the first failing action and shows you the screen. The screen is not shown to you between actions, so for steps whose target only appears along the way (a menu item, a dialog button) use target instead of coordinate, and wait with until for a window or control to appear. Example: [key \"ctrl+s\", wait until \"window:另存为\", type target \"文件名\" text \"C:\\a.txt\", left_click target \"保存\"].",
11370
+ description: "Run several computer actions in order in one call (or replay a saved macro by name), then get one screenshot (taken once the screen settles, so do not end with a wait). Stops at the first failing action, or before a coordinate action once another window or dialog takes the foreground or the browser navigates, and shows you the screen. The screen is not shown to you between actions, so for steps whose target only appears along the way (a menu item, a dialog button) use target instead of coordinate, and wait with until for a window or control to appear. Example: [key \"ctrl+s\", wait until \"window:另存为\", type target \"文件名\" text \"C:\\a.txt\", left_click target \"保存\"].",
11314
11371
  parameters: {
11315
11372
  actions: {
11316
11373
  type: "array",
@@ -11374,11 +11431,19 @@ function createTools(host) {
11374
11431
  let endedWithZoom = false;
11375
11432
  const lines = [];
11376
11433
  let failure;
11434
+ const startWindow = await computer.foreground().catch(() => void 0);
11377
11435
  for (const [index, input] of actions.entries()) {
11378
11436
  if (input.action === "screenshot" || input.action === "zoom" && index !== actions.length - 1) {
11379
11437
  failure = `#${index + 1} ${input.action}: ${input.action === "zoom" ? "only allowed as the last action of a batch" : "not allowed in a batch"}.`;
11380
11438
  break;
11381
11439
  }
11440
+ if (index > 0 && usesScreenCoordinates(input)) {
11441
+ const change = screenChange(startWindow, await computer.foreground().catch(() => void 0));
11442
+ if (change) {
11443
+ failure = `#${index + 1} ${input.action} not run: ${change} since the batch started, so its coordinates may point at the wrong thing.`;
11444
+ break;
11445
+ }
11446
+ }
11382
11447
  try {
11383
11448
  const stepStart = Date.now();
11384
11449
  if (input.action === "zoom" && index > 0) await computer.settle(call.signal);
@@ -11393,6 +11458,10 @@ function createTools(host) {
11393
11458
  break;
11394
11459
  }
11395
11460
  lines.push(`#${index + 1} ${outcome.text}`);
11461
+ if (outcome.verification === "unconfirmed" && index < actions.length - 1) {
11462
+ failure = `#${index + 1} ${input.action} could not be confirmed; later actions depend on it.`;
11463
+ break;
11464
+ }
11396
11465
  await setTimeout$1(60, void 0, { signal: call.signal });
11397
11466
  if (computer.settings().pauseOnUserInput && (computer.overlay.userTypedSince(stepStart - 1) || computer.overlay.hasUserActions?.())) {
11398
11467
  const notes = await computer.drainUserActionNotes();
@@ -11864,6 +11933,9 @@ function createTools(host) {
11864
11933
  for (const [index, el] of result.elements.entries()) lines.push(await formatEl(`[${index}]`, el));
11865
11934
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": ${result.elements.length} elements${diff === true ? " (baseline captured; next diff: true returns changes only)" : ""}.`;
11866
11935
  return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} This window exposes no UI Automation elements; use ui_elements with ocr: true or screenshots.` };
11936
+ }).then((value) => text === true ? value : {
11937
+ ...value,
11938
+ text: capObservation(value.text)
11867
11939
  });
11868
11940
  },
11869
11941
  presentCall: (args) => {
@@ -130,7 +130,12 @@ export interface ActionOutcome {
130
130
  skipped?: boolean;
131
131
  /** True when a deterministic UIA Control Pattern read back and verified the desired post-state. */
132
132
  verified?: boolean;
133
+ /** For input actions: 'observed' = read back from the control, 'unconfirmed' = read back and it does not match, 'sent' = input sent, nothing to read back. */
134
+ verification?: Verification;
133
135
  }
136
+ export type Verification = 'observed' | 'unconfirmed' | 'sent';
137
+ /** Whitespace-insensitive tail of typed text, as it should appear in the field afterwards. */
138
+ export declare function typedTextLanded(typed: string, fieldValue: string): boolean;
134
139
  export interface ClickResult {
135
140
  x?: number;
136
141
  y?: number;
@@ -348,6 +353,8 @@ export declare class Computer {
348
353
  drainUserActionNotes(): Promise<string>;
349
354
  /** Format physical user takeover actions into concise screenshot-coordinate context for the model. */
350
355
  private formatUserActions;
356
+ /** Compare the focused field with what was just typed (ValuePattern only; rich editors report 'sent'). */
357
+ private readBackTyped;
351
358
  /** Run one action. Returns text plus an image for screenshot/zoom. */
352
359
  run(input: ActionInput, call: CallContext): Promise<ActionOutcome>;
353
360
  /**
@@ -2,7 +2,7 @@ import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
2
2
  import { defineTool } from '@deepseek-ai/dsh-tools';
3
3
  import { type MacroStore } from './macros.js';
4
4
  import { type SkillStore } from './skills.js';
5
- import { Computer, type CallContext, type Shot } from './computer.js';
5
+ import { Computer, type ActionInput, type CallContext, type Shot, type WindowInfo } from './computer.js';
6
6
  type ToolDefinition = ReturnType<typeof defineTool>;
7
7
  export interface ToolHost {
8
8
  computer: Computer;
@@ -17,5 +17,12 @@ export interface ToolHost {
17
17
  /** True when the sibling `@copylee/dsh-office` COM plugin is active in DSH. */
18
18
  hasOfficePlugin?: () => boolean;
19
19
  }
20
+ /** A mouse action aimed by coordinate (not by target): only valid on the screen the model last saw. */
21
+ export declare function usesScreenCoordinates(input: ActionInput): boolean;
22
+ /** How the foreground changed in a way that invalidates planned coordinates, or undefined. */
23
+ export declare function screenChange(before: WindowInfo | undefined, after: WindowInfo | undefined): string | undefined;
24
+ /** Observation budget for element lists: every row stays short, and the list stops at a size the model can afford. */
25
+ export declare const OBSERVATION_MAX_CHARS = 12000;
26
+ export declare function capObservation(text: string, maxChars?: number, maxLine?: number): string;
20
27
  export declare function createTools(host: ToolHost): ToolDefinition[];
21
28
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copylee/dsh-computer-use",
3
- "version": "0.16.0",
3
+ "version": "0.16.1",
4
4
  "description": "DeepSeek Harness Computer Use 插件(Windows):让 AI 看屏幕、点鼠标、敲键盘操控电脑;控制时屏幕泛起橙色光晕并显示“DeepSeek Harness 正在操控你的电脑”,按 Esc 暂停 / 继续。",
5
5
  "icon": "assets/icon.svg",
6
6
  "type": "module",