@abhishek944/pi-classifier 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +344 -30
  4. package/dist/auth.d.ts +4 -2
  5. package/dist/auth.js +18 -2
  6. package/dist/box-tool.d.ts +4 -0
  7. package/dist/box-tool.js +79 -0
  8. package/dist/box.d.ts +32 -0
  9. package/dist/box.js +148 -0
  10. package/dist/choices.js +35 -1
  11. package/dist/classify.d.ts +6 -0
  12. package/dist/classify.js +4 -4
  13. package/dist/computer-use-state.d.ts +9 -0
  14. package/dist/computer-use-state.js +160 -0
  15. package/dist/computer-use-tool.d.ts +52 -0
  16. package/dist/computer-use-tool.js +78 -0
  17. package/dist/computer-use-types.d.ts +132 -0
  18. package/dist/computer-use-types.js +1 -0
  19. package/dist/computer-use.d.ts +22 -0
  20. package/dist/computer-use.js +223 -0
  21. package/dist/config.d.ts +140 -3
  22. package/dist/config.js +405 -20
  23. package/dist/cost.js +42 -4
  24. package/dist/durable.d.ts +34 -0
  25. package/dist/durable.js +237 -0
  26. package/dist/extension.d.ts +2 -247
  27. package/dist/extension.js +53 -190
  28. package/dist/extract.d.ts +11 -0
  29. package/dist/extract.js +191 -0
  30. package/dist/http.d.ts +6 -1
  31. package/dist/http.js +64 -28
  32. package/dist/image-content.d.ts +12 -0
  33. package/dist/image-content.js +90 -0
  34. package/dist/index.d.ts +10 -1
  35. package/dist/index.js +3 -0
  36. package/dist/inputs.d.ts +24 -2
  37. package/dist/inputs.js +565 -134
  38. package/dist/mcp-cli.d.ts +2 -0
  39. package/dist/mcp-cli.js +39 -0
  40. package/dist/mcp-server.d.ts +28 -0
  41. package/dist/mcp-server.js +121 -0
  42. package/dist/mcp-tool-definitions.d.ts +19 -0
  43. package/dist/mcp-tool-definitions.js +64 -0
  44. package/dist/providers.d.ts +1 -0
  45. package/dist/providers.js +1218 -124
  46. package/dist/tool-contracts.d.ts +785 -0
  47. package/dist/tool-contracts.js +530 -0
  48. package/dist/tree.js +1 -1
  49. package/dist/types.d.ts +314 -20
  50. package/dist/validation.js +181 -44
  51. package/package.json +33 -5
  52. package/src/auth.ts +26 -2
  53. package/src/box-tool.ts +110 -0
  54. package/src/box.ts +253 -0
  55. package/src/choices.ts +44 -2
  56. package/src/classify.ts +10 -6
  57. package/src/computer-use-state.ts +145 -0
  58. package/src/computer-use-tool.ts +76 -0
  59. package/src/computer-use-types.ts +127 -0
  60. package/src/computer-use.ts +216 -0
  61. package/src/config.ts +454 -23
  62. package/src/cost.ts +42 -4
  63. package/src/durable.ts +298 -0
  64. package/src/extension.ts +79 -265
  65. package/src/extract.ts +228 -0
  66. package/src/http.ts +63 -32
  67. package/src/image-content.ts +77 -0
  68. package/src/index.ts +25 -0
  69. package/src/inputs.ts +603 -184
  70. package/src/mcp-cli.ts +44 -0
  71. package/src/mcp-server.ts +179 -0
  72. package/src/mcp-tool-definitions.ts +104 -0
  73. package/src/providers.ts +1398 -144
  74. package/src/tool-contracts.ts +785 -0
  75. package/src/tree.ts +1 -1
  76. package/src/types.ts +248 -11
  77. package/src/validation.ts +169 -96
package/src/box.ts ADDED
@@ -0,0 +1,253 @@
1
+ import sharp, { type Sharp } from "sharp";
2
+ import { loadLocalImage } from "./inputs.js";
3
+ import { ClassifierError, isRecord } from "./types.js";
4
+
5
+ export type ClassifierBoxMode = "overlay" | "crop";
6
+
7
+ export type ClassifierBoxEdges = {
8
+ top: number;
9
+ bottom: number;
10
+ left: number;
11
+ right: number;
12
+ };
13
+
14
+ /** Pixel coordinates in the source image. */
15
+ export type ClassifierBoxPixelBox = {
16
+ left: number;
17
+ top: number;
18
+ width: number;
19
+ height: number;
20
+ };
21
+
22
+ export type ClassifierBoxResult = {
23
+ data: string;
24
+ mimeType: "image/png";
25
+ width: number;
26
+ height: number;
27
+ pixelBox: ClassifierBoxPixelBox;
28
+ mode: ClassifierBoxMode;
29
+ };
30
+
31
+ type ClassifierBoxParams = {
32
+ image: string;
33
+ box: ClassifierBoxEdges;
34
+ mode: ClassifierBoxMode;
35
+ };
36
+
37
+ const MAX_PIXELS = 16_777_216;
38
+ const MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
39
+ const RENDER_TIMEOUT_SECONDS = 10;
40
+ const RENDER_TIMEOUT_MS = RENDER_TIMEOUT_SECONDS * 1000;
41
+ const MAX_PATH_LENGTH = 4096;
42
+
43
+ /**
44
+ * Render a normalized box on a local image, or crop to it, without a provider
45
+ * request or disk write. File containment, byte limits and full decoding are
46
+ * owned by loadLocalImage; this module owns coordinates, rendering and output
47
+ * limits.
48
+ */
49
+ export async function renderClassifierBox(
50
+ params: unknown,
51
+ options: { cwd: string; signal?: AbortSignal },
52
+ ): Promise<ClassifierBoxResult> {
53
+ cancelled(options.signal);
54
+ const parsed = validateBoxParams(params);
55
+ const image = await loadLocalImage(
56
+ parsed.image,
57
+ options.cwd,
58
+ options.signal,
59
+ );
60
+ cancelled(options.signal);
61
+ const pixelBox = toPixelBox(parsed.box, image.width, image.height);
62
+
63
+ let rendered: { data: Buffer; width: number; height: number };
64
+ try {
65
+ const source = sharp(Buffer.from(image.data, "base64"), {
66
+ limitInputPixels: MAX_PIXELS,
67
+ failOn: "warning",
68
+ }).timeout({ seconds: RENDER_TIMEOUT_SECONDS });
69
+ rendered =
70
+ parsed.mode === "crop"
71
+ ? await renderPng(source.extract(pixelBox), options.signal)
72
+ : await renderPng(
73
+ source.composite([
74
+ {
75
+ input: Buffer.from(
76
+ overlaySvg(image.width, image.height, pixelBox),
77
+ ),
78
+ top: 0,
79
+ left: 0,
80
+ },
81
+ ]),
82
+ options.signal,
83
+ );
84
+ } catch (error) {
85
+ cancelled(options.signal);
86
+ if (error instanceof ClassifierError) throw error;
87
+ if (error instanceof Error && /time(d)?\s*out/i.test(error.message))
88
+ throw new ClassifierError("input", "Box rendering timed out.");
89
+ throw new ClassifierError(
90
+ "input",
91
+ "Could not render the box image. Use a non-animated PNG/JPEG/WebP inside cwd and a valid box.",
92
+ );
93
+ }
94
+ cancelled(options.signal);
95
+ if (rendered.data.length > MAX_OUTPUT_BYTES)
96
+ throw new ClassifierError(
97
+ "input",
98
+ "The box output PNG is larger than 10 MiB. Use crop or a smaller region.",
99
+ );
100
+ return {
101
+ data: rendered.data.toString("base64"),
102
+ mimeType: "image/png",
103
+ width: rendered.width,
104
+ height: rendered.height,
105
+ pixelBox,
106
+ mode: parsed.mode,
107
+ };
108
+ }
109
+
110
+ function validateBoxParams(value: unknown): ClassifierBoxParams {
111
+ if (
112
+ !isRecord(value) ||
113
+ Object.keys(value).some((key) => !["image", "box", "mode"].includes(key))
114
+ )
115
+ invalid("Expected image, box and optional mode; unknown fields are rejected.");
116
+ const image = value.image;
117
+ if (
118
+ typeof image !== "string" ||
119
+ !image.trim() ||
120
+ image.length > MAX_PATH_LENGTH
121
+ )
122
+ invalid("image must be a local PNG/JPEG/WebP path inside cwd.");
123
+ const candidate = value.box;
124
+ if (
125
+ !isRecord(candidate) ||
126
+ Object.keys(candidate).some(
127
+ (key) => !["top", "bottom", "left", "right"].includes(key),
128
+ )
129
+ )
130
+ invalid("box must contain only top, bottom, left and right.");
131
+ const { top, bottom, left, right } = candidate;
132
+ if (
133
+ !isNormalized(top) ||
134
+ !isNormalized(bottom) ||
135
+ !isNormalized(left) ||
136
+ !isNormalized(right)
137
+ )
138
+ invalid(
139
+ "box edges must be finite normalized numbers between 0 and 1.",
140
+ );
141
+ if (top >= bottom || left >= right)
142
+ invalid("box must have top < bottom and left < right.");
143
+ const mode = value.mode ?? "overlay";
144
+ if (mode !== "overlay" && mode !== "crop")
145
+ invalid("mode must be overlay or crop.");
146
+ return { image, box: { top, bottom, left, right }, mode };
147
+ }
148
+
149
+ function isNormalized(value: unknown): value is number {
150
+ return (
151
+ typeof value === "number" &&
152
+ Number.isFinite(value) &&
153
+ value >= 0 &&
154
+ value <= 1
155
+ );
156
+ }
157
+
158
+ /** Floor/ceil edges, then clamp to the source so the region always has pixels. */
159
+ function toPixelBox(
160
+ box: ClassifierBoxEdges,
161
+ width: number,
162
+ height: number,
163
+ ): ClassifierBoxPixelBox {
164
+ const left = Math.min(Math.max(Math.floor(box.left * width), 0), width - 1);
165
+ const top = Math.min(Math.max(Math.floor(box.top * height), 0), height - 1);
166
+ const right = Math.min(
167
+ Math.max(Math.ceil(box.right * width), left + 1),
168
+ width,
169
+ );
170
+ const bottom = Math.min(
171
+ Math.max(Math.ceil(box.bottom * height), top + 1),
172
+ height,
173
+ );
174
+ return { left, top, width: right - left, height: bottom - top };
175
+ }
176
+
177
+ /** Fixed rectangle built only from computed integers, so no caller text enters the SVG. */
178
+ function overlaySvg(
179
+ width: number,
180
+ height: number,
181
+ box: ClassifierBoxPixelBox,
182
+ ): string {
183
+ const stroke = Math.max(
184
+ 2,
185
+ Math.min(8, Math.round(Math.min(width, height) / 200)),
186
+ );
187
+ const inset = Math.floor(stroke / 2);
188
+ const insetFits = box.width > inset * 2 && box.height > inset * 2;
189
+ const x = insetFits ? box.left + inset : box.left;
190
+ const y = insetFits ? box.top + inset : box.top;
191
+ const rectWidth = Math.max(1, box.width - (insetFits ? inset * 2 : 0));
192
+ const rectHeight = Math.max(1, box.height - (insetFits ? inset * 2 : 0));
193
+ return (
194
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
195
+ `<rect x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}" fill="none" stroke="#ff2d55" stroke-width="${stroke}"/>` +
196
+ `</svg>`
197
+ );
198
+ }
199
+
200
+ async function renderPng(
201
+ pipeline: Sharp,
202
+ signal?: AbortSignal,
203
+ ): Promise<{ data: Buffer; width: number; height: number }> {
204
+ cancelled(signal);
205
+ let cancel = () => {};
206
+ let timer: ReturnType<typeof setTimeout> | undefined;
207
+ try {
208
+ return await new Promise<{ data: Buffer; width: number; height: number }>(
209
+ (resolve, reject) => {
210
+ let settled = false;
211
+ const settle = (action: () => void) => {
212
+ if (settled) return;
213
+ settled = true;
214
+ action();
215
+ };
216
+ cancel = () => {
217
+ pipeline.destroy();
218
+ settle(() =>
219
+ reject(
220
+ new ClassifierError("aborted", "Box rendering was cancelled."),
221
+ ),
222
+ );
223
+ };
224
+ signal?.addEventListener("abort", cancel, { once: true });
225
+ timer = setTimeout(() => {
226
+ pipeline.destroy();
227
+ settle(() =>
228
+ reject(new ClassifierError("input", "Box rendering timed out.")),
229
+ );
230
+ }, RENDER_TIMEOUT_MS);
231
+ pipeline.png().toBuffer({ resolveWithObject: true }).then(
232
+ ({ data, info }) =>
233
+ settle(() =>
234
+ resolve({ data, width: info.width, height: info.height }),
235
+ ),
236
+ (error: unknown) => settle(() => reject(error)),
237
+ );
238
+ },
239
+ );
240
+ } finally {
241
+ if (timer) clearTimeout(timer);
242
+ signal?.removeEventListener("abort", cancel);
243
+ }
244
+ }
245
+
246
+ function invalid(message: string): never {
247
+ throw new ClassifierError("input", message);
248
+ }
249
+
250
+ function cancelled(signal?: AbortSignal): void {
251
+ if (signal?.aborted)
252
+ throw new ClassifierError("aborted", "Box rendering was cancelled.");
253
+ }
package/src/choices.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  type ClassifierSettings,
8
8
  type PreparedInput,
9
9
  type Question,
10
+ type QuestionContent,
10
11
  type ResolvedModel,
11
12
  } from "./types.js";
12
13
 
@@ -29,7 +30,7 @@ export function choicePolicy(settings: ClassifierSettings): ChoicePolicy {
29
30
 
30
31
  type ChoicePlan = {
31
32
  question: Extract<Question, { type: "choice" }>;
32
- entries: [string, string][];
33
+ entries: [string, QuestionContent][];
33
34
  offset: number;
34
35
  sentinel: string;
35
36
  };
@@ -37,6 +38,33 @@ type ChoicePlan = {
37
38
  const NONE_DESCRIPTION =
38
39
  "None of the other options in this question applies to the supplied state. Select this only when every listed real option is unsuitable.";
39
40
 
41
+ /**
42
+ * Each provider call returns its own web evidence. `searchResult` indexes that call's array,
43
+ * so spans must be rebased onto the accumulated evidence assembled by this orchestrator.
44
+ */
45
+ function remapGroundedAnswers(
46
+ answers: Record<string, Answer>,
47
+ offset: number,
48
+ ): Record<string, Answer> {
49
+ if (offset === 0) return answers;
50
+ const mapped = Object.create(null) as Record<string, Answer>;
51
+ for (const [id, answer] of Object.entries(answers)) {
52
+ if (answer.type !== "locate" || !answer.spans.some((span) => span.searchResult !== undefined)) {
53
+ mapped[id] = answer;
54
+ continue;
55
+ }
56
+ mapped[id] = {
57
+ ...answer,
58
+ spans: answer.spans.map((span) =>
59
+ span.searchResult === undefined
60
+ ? span
61
+ : { ...span, searchResult: span.searchResult + offset },
62
+ ),
63
+ };
64
+ }
65
+ return mapped;
66
+ }
67
+
40
68
  /** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
41
69
  export async function executeChoices(
42
70
  input: PreparedInput,
@@ -80,6 +108,7 @@ export async function executeChoices(
80
108
  let last: ClassifierResult | undefined;
81
109
  let usage: ClassifierResult["usage"];
82
110
  let cost: ClassifierCost | undefined;
111
+ let webGrounding: NonNullable<ClassifierResult["webGrounding"]> | undefined;
83
112
  while (plans.size > 0) {
84
113
  if (signal?.aborted)
85
114
  throw new ClassifierError("aborted", "Classification was cancelled.");
@@ -121,9 +150,21 @@ export async function executeChoices(
121
150
  }
122
151
  usage = calls === 0 ? result.usage : sumUsage(usage, result.usage);
123
152
  cost = cost === undefined ? result.cost : sumCost(cost, result.cost);
153
+ const callAnswers = remapGroundedAnswers(
154
+ result.answers,
155
+ webGrounding?.searchResults.length ?? 0,
156
+ );
157
+ if (result.webGrounding !== undefined) {
158
+ webGrounding ??= { searchResults: [] };
159
+ webGrounding.searchResults.push(...result.webGrounding.searchResults);
160
+ if (result.webGrounding.fetchedResults?.length) {
161
+ webGrounding.fetchedResults ??= [];
162
+ webGrounding.fetchedResults.push(...result.webGrounding.fetchedResults);
163
+ }
164
+ }
124
165
  calls++;
125
166
  last = result;
126
- for (const [id, answer] of Object.entries(result.answers)) {
167
+ for (const [id, answer] of Object.entries(callAnswers)) {
127
168
  const plan = plans.get(id);
128
169
  if (!plan) {
129
170
  answers[id] = answer;
@@ -167,6 +208,7 @@ export async function executeChoices(
167
208
  cost: cost!,
168
209
  };
169
210
  if (usage !== undefined) combined.usage = usage;
211
+ if (webGrounding !== undefined) combined.webGrounding = webGrounding;
170
212
  if (calls === 1 && last!.requestId !== undefined)
171
213
  combined.requestId = last!.requestId;
172
214
  return combined;
package/src/classify.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { performance } from "node:perf_hooks";
2
- import { resolveApiKey } from "./auth.js";
2
+ import { resolveApiKey, type CredentialSource } from "./auth.js";
3
3
  import { configuredDefault, configuredRoutes, resolveModel } from "./config.js";
4
- import { prepareInput } from "./inputs.js";
4
+ import { prepareInput, type MemoryImage } from "./inputs.js";
5
5
  import { choicePolicy, executeChoices } from "./choices.js";
6
6
  import { classifyWithProvider } from "./providers.js";
7
7
  import {
@@ -20,6 +20,10 @@ export type ClassifyOptions = {
20
20
  settings: ClassifierSettings;
21
21
  cwd: string;
22
22
  signal?: AbortSignal;
23
+ /** Credential origin. Desktop keeps the default; the native Durable factory passes "explicit". */
24
+ credentialSource?: CredentialSource;
25
+ /** Trusted programmatic ingress; all bytes still pass normal image validation. */
26
+ memoryImages?: readonly MemoryImage[];
23
27
  };
24
28
 
25
29
  function checkCancelled(signal?: AbortSignal): void {
@@ -41,9 +45,9 @@ async function classifyOnce(
41
45
  options: ClassifyOptions,
42
46
  ): Promise<ClassifierResult> {
43
47
  checkCancelled(options.signal);
44
- const prepared = await prepareInput(input, route, options.cwd, options.signal);
48
+ const prepared = await prepareInput(input, route, options.cwd, options.signal, options.memoryImages);
45
49
  checkCancelled(options.signal);
46
- const key = resolveApiKey(route);
50
+ const key = resolveApiKey(route, options.credentialSource ?? "pi-store");
47
51
  const result = await executeChoices(
48
52
  prepared,
49
53
  route,
@@ -84,7 +88,7 @@ export async function classify(
84
88
  let lastError: unknown;
85
89
  for (const candidate of candidates) {
86
90
  checkCancelled(options.signal);
87
- const route = resolveModel(options.settings, candidate);
91
+ const route = resolveModel(options.settings, candidate, options.credentialSource ?? "pi-store");
88
92
  const key = routeKey(route);
89
93
  if (seen.has(key)) continue;
90
94
  seen.add(key);
@@ -128,7 +132,7 @@ export async function compareClassifiers(
128
132
  const start = performance.now();
129
133
  let selected = candidate;
130
134
  try {
131
- const route = resolveModel(options.settings, candidate);
135
+ const route = resolveModel(options.settings, candidate, options.credentialSource ?? "pi-store");
132
136
  selected = routePair(route);
133
137
  const key = routeKey(route);
134
138
  if (seen.has(key))
@@ -0,0 +1,145 @@
1
+ import { ClassifierError, isRecord } from "./types.js";
2
+ import type {
3
+ ComputerCandidate, ComputerControl, ComputerUseParams, DriverElement,
4
+ DriverObservation, DriverReply,
5
+ } from "./computer-use-types.js";
6
+ import type { MemoryImage } from "./inputs.js";
7
+
8
+ export const KEY_NAMES = ["return", "tab", "escape", "up", "down", "left", "right", "space", "home", "end", "pageup", "pagedown"];
9
+ const SECRET = /secure|password|passcode|one.time|\botp\b|secret|security.code|api.key|access.token|auth.token|recovery.code|credit.card|card.number|\bcvv\b/i;
10
+ const EDITABLE = /^(AXTextField|AXTextArea|AXComboBox|textbox|combobox|text field|text area)$/i;
11
+ const CLICKABLE = /^(AXButton|AXCheckBox|AXRadioButton|AXMenuItem|AXLink|AXPopUpButton|AXTab|AXDisclosureTriangle|AXRow|button|checkbox|radio|menuitem|link|tab|switch)$/i;
12
+
13
+ export function validateComputerParams(params: ComputerUseParams): void {
14
+ const invalid = () => { throw new ClassifierError("input", "Invalid computer-use goal, exact target, controls, values, expectations or limits."); };
15
+ if (!isRecord(params) || typeof params.goal !== "string" || !params.goal.trim() || params.goal.length > 4096 ||
16
+ !isRecord(params.target) || !Number.isSafeInteger(params.target.pid) || params.target.pid < 1 ||
17
+ !Number.isSafeInteger(params.target.window_id) || params.target.window_id < 0 ||
18
+ !Array.isArray(params.controls) || params.controls.length < 1 || params.controls.length > 120) invalid();
19
+ const ids = new Set<string>();
20
+ for (const c of params.controls) {
21
+ if (!isRecord(c) || typeof c.id !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(c.id) || ids.has(c.id) ||
22
+ !isRecord(c.selector) || typeof c.selector.role !== "string" || !c.selector.role || c.selector.role.length > 128 ||
23
+ typeof c.selector.label !== "string" || !c.selector.label.trim() || c.selector.label.length > 512 ||
24
+ !["click", "fill", "key"].includes(c.operation)) invalid();
25
+ ids.add(c.id);
26
+ if (c.operation === "fill" && (typeof c.valueKey !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(c.valueKey))) invalid();
27
+ if (c.operation === "key" && !KEY_NAMES.includes(c.key)) invalid();
28
+ if (SECRET.test(c.selector.role + " " + c.selector.label))
29
+ throw new ClassifierError("input", "Credential and secure controls must remain with the user, outside the classifier loop.");
30
+ }
31
+ if (params.values !== undefined && (!isRecord(params.values) || Object.keys(params.values).length > 64 ||
32
+ Object.entries(params.values).some(([k, v]) => !/^[a-zA-Z0-9_-]{1,64}$/.test(k) || typeof v !== "string" || v.length > 4096 || /[\r\n\t\x00-\x1f]/.test(v)))) invalid();
33
+ if (params.expect !== undefined && (!Array.isArray(params.expect) || params.expect.length < 1 || params.expect.length > 8)) invalid();
34
+ for (const p of params.expect ?? []) {
35
+ const e = p?.element;
36
+ if (!isRecord(e) || !isRecord(e.selector) || typeof e.selector.role !== "string" || !e.selector.role ||
37
+ typeof e.selector.label_contains !== "string" || !e.selector.label_contains ||
38
+ e.selector.role.length > 128 || e.selector.label_contains.length > 512 ||
39
+ (e.exists !== undefined && e.exists !== true) ||
40
+ (e.value_equals !== undefined && (typeof e.value_equals !== "string" || e.value_equals.length > 4096)) ||
41
+ (e.enabled !== undefined && typeof e.enabled !== "boolean") ||
42
+ (e.selected !== undefined && typeof e.selected !== "boolean") ||
43
+ [e.exists, e.value_equals, e.enabled, e.selected].every((v) => v === undefined)) invalid();
44
+ }
45
+ if ((params.context !== undefined && (typeof params.context !== "string" || params.context.length > 4096)) ||
46
+ (params.previousActions !== undefined && (!Array.isArray(params.previousActions) || params.previousActions.length > 20 || params.previousActions.some((v) => typeof v !== "string" || v.length > 256))) ||
47
+ (params.maxActions !== undefined && (!Number.isSafeInteger(params.maxActions) || params.maxActions < 1 || params.maxActions > 100)) ||
48
+ (params.timeoutMs !== undefined && (!Number.isSafeInteger(params.timeoutMs) || params.timeoutMs < 1000 || params.timeoutMs > 300000)) ||
49
+ (params.deliveryMode !== undefined && !["background", "foreground"].includes(params.deliveryMode))) invalid();
50
+ }
51
+
52
+ export function driverState(reply: DriverReply): Record<string, unknown> {
53
+ if (reply.isError) throw new ClassifierError("driver", "Driver call failed or was blocked. Inspect the target and permissions before resuming.");
54
+ if (!isRecord(reply.structuredContent)) throw new ClassifierError("driver", "Driver returned no structured state; no input was attempted from that response.");
55
+ return reply.structuredContent;
56
+ }
57
+
58
+ export function observation(reply: DriverReply, target: ComputerUseParams["target"]): DriverObservation {
59
+ const state = driverState(reply);
60
+ if (state.pid !== target.pid || state.window_id !== target.window_id || !Array.isArray(state.elements))
61
+ throw new ClassifierError("driver", "Driver observation did not establish the exact requested window and element list.");
62
+ const elements: DriverElement[] = [];
63
+ const menuIndices = new Set<number>();
64
+ for (const raw of state.elements) {
65
+ if (!isRecord(raw)) continue;
66
+ if (raw.role === "AXMenuBar" || (typeof raw.parent_index === "number" && menuIndices.has(raw.parent_index))) {
67
+ if (typeof raw.element_index === "number") menuIndices.add(raw.element_index);
68
+ }
69
+ }
70
+ for (const raw of state.elements.slice(0, 200)) {
71
+ if (isRecord(raw) && typeof raw.element_index === "number" && menuIndices.has(raw.element_index)) continue;
72
+ if (!isRecord(raw) || typeof raw.role !== "string" || SECRET.test(raw.role + " " + String(raw.label ?? ""))) continue;
73
+ const e: DriverElement = {
74
+ role: raw.role.slice(0, 128), label: typeof raw.label === "string" ? raw.label.slice(0, 1024) : "",
75
+ actions: Array.isArray(raw.actions) ? raw.actions.filter((v): v is string => typeof v === "string").slice(0, 20) : [],
76
+ index: typeof raw.element_index === "number" ? raw.element_index : -1,
77
+ };
78
+ if (typeof raw.value === "string") e.value = raw.value.slice(0, 4096);
79
+ if (typeof raw.enabled === "boolean") e.enabled = raw.enabled;
80
+ if (typeof raw.selected === "boolean") e.selected = raw.selected;
81
+ if (typeof raw.element_token === "string" && /^s[0-9a-f]{8}:[0-9]+$/.test(raw.element_token)) e.token = raw.element_token;
82
+ elements.push(e);
83
+ }
84
+ return {
85
+ elements, truncated: state.truncated === true || state.elements.length > 200,
86
+ degraded: state.degraded === true || Boolean(state.degraded_reason),
87
+ title: typeof state.window_title === "string" ? state.window_title.slice(0, 512) : "",
88
+ // Driver indexes actionable rows only; retain passive state without the global menu subtree.
89
+ text: windowText(state.tree_markdown),
90
+ };
91
+ }
92
+
93
+ /** Root order changes when an app backgrounds; select the window branch, not a prefix. */
94
+ function windowText(markdown: unknown): string {
95
+ if (typeof markdown !== "string") return "";
96
+ let inWindow = false;
97
+ const lines: string[] = [];
98
+ for (const line of markdown.split("\n")) {
99
+ if (/^- /.test(line)) inWindow = /^- (?:\[\d+\] )?AXWindow\b/.test(line);
100
+ if (inWindow && !SECRET.test(line)) lines.push(line);
101
+ }
102
+ return lines.join("\n").slice(0, 16000);
103
+ }
104
+
105
+ export function candidates(params: ComputerUseParams, state: DriverObservation): ComputerCandidate[] {
106
+ // Truncated trees cannot establish selector uniqueness; hand back instead of guessing.
107
+ if (state.truncated || state.degraded) return [];
108
+ const result: ComputerCandidate[] = [];
109
+ for (const control of params.controls) {
110
+ const matches = state.elements.filter((e) => e.role === control.selector.role && e.label === control.selector.label);
111
+ if (matches.length !== 1) continue;
112
+ const element = matches[0]!;
113
+ if (!element.token || element.enabled === false || !compatible(control, element)) continue;
114
+ const missingValue = control.operation === "fill" && !Object.hasOwn(params.values ?? {}, control.valueKey);
115
+ if (control.operation === "fill" && !missingValue && element.value === params.values![control.valueKey]) continue;
116
+ result.push({
117
+ id: control.id, control, element, missingValue,
118
+ description: `${control.operation} ${element.role} ${JSON.stringify(element.label)}` +
119
+ (control.operation === "fill" ? ` using supplied value ${control.valueKey}${missingValue ? " (MISSING: hand back for text)" : ""}` : control.operation === "key" ? ` ${control.key}` : ""),
120
+ });
121
+ }
122
+ return result;
123
+ }
124
+
125
+ function compatible(control: ComputerControl, element: DriverElement): boolean {
126
+ if (control.operation === "fill") return EDITABLE.test(element.role);
127
+ if (control.operation === "key") return EDITABLE.test(element.role) || CLICKABLE.test(element.role);
128
+ return CLICKABLE.test(element.role) || element.actions.some((a) => /^(AXPress|press|invoke)$/i.test(a));
129
+ }
130
+
131
+ export function modelElements(state: DriverObservation): unknown[] {
132
+ return state.elements.map(({ token: _token, actions: _actions, index: _index, ...e }) => e);
133
+ }
134
+
135
+ export function captureImage(reply: DriverReply): MemoryImage[] {
136
+ const blocks = (reply.content ?? []).filter((b) => isRecord(b) && b.type === "image");
137
+ if (blocks.length !== 1) throw new ClassifierError("driver", "Expected one window screenshot. No image was silently omitted.");
138
+ const block = blocks[0];
139
+ if (!isRecord(block) || !["image/png", "image/jpeg", "image/webp"].includes(String(block.mimeType)) ||
140
+ typeof block.data !== "string" || block.data.length > 6990508 || (block.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(block.data)))
141
+ throw new ClassifierError("input", "Driver screenshot exceeds image limits or is not canonical base64.");
142
+ const bytes = Buffer.from(block.data, "base64");
143
+ if (bytes.toString("base64") !== block.data) throw new ClassifierError("input", "Driver image encoding was not canonical base64.");
144
+ return [{ bytes, mimeType: block.mimeType as MemoryImage["mimeType"] }];
145
+ }
@@ -0,0 +1,76 @@
1
+ import { isProjectTrusted } from "@amaster.ai/pi-shared/settings";
2
+ import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { Type } from "typebox";
4
+ import { loadClassifierSettings } from "./config.js";
5
+ import { runComputerUse, DRIVER_TOOLS } from "./computer-use.js";
6
+ import { KEY_NAMES } from "./computer-use-state.js";
7
+ import { ClassifierError, isRecord, userError } from "./types.js";
8
+ import type { ComputerUseParams, DriverReply } from "./computer-use-types.js";
9
+
10
+ const selector = Type.Object({ role: Type.String({ minLength: 1, maxLength: 128 }), label: Type.String({ minLength: 1, maxLength: 512 }) }, { additionalProperties: false });
11
+ const id = Type.String({ pattern: "^[a-zA-Z0-9_-]{1,64}$" });
12
+ const control = Type.Union([
13
+ Type.Object({ id, selector, operation: Type.Literal("click") }, { additionalProperties: false }),
14
+ Type.Object({ id, selector, operation: Type.Literal("fill"), valueKey: id }, { additionalProperties: false }),
15
+ Type.Object({ id, selector, operation: Type.Literal("key"), key: Type.Union(KEY_NAMES.map((k) => Type.Literal(k))) }, { additionalProperties: false }),
16
+ ]);
17
+ const expectation = Type.Object({ element: Type.Object({
18
+ selector: Type.Object({ role: Type.String({ minLength: 1, maxLength: 128 }), label_contains: Type.String({ minLength: 1, maxLength: 512 }) }, { additionalProperties: false }),
19
+ exists: Type.Optional(Type.Literal(true)),
20
+ value_equals: Type.Optional(Type.String({ maxLength: 4096 })),
21
+ enabled: Type.Optional(Type.Boolean()), selected: Type.Optional(Type.Boolean()),
22
+ }, { additionalProperties: false }) }, { additionalProperties: false });
23
+
24
+ export const computerUseParameters = Type.Object({
25
+ goal: Type.String({ minLength: 1, maxLength: 4096 }),
26
+ target: Type.Object({ pid: Type.Integer({ minimum: 1 }), window_id: Type.Integer({ minimum: 0 }) }, { additionalProperties: false }),
27
+ controls: Type.Array(control, { minItems: 1, maxItems: 120, description: "Only controls authorized for this goal. Exact role and label; controls may span later screens. This is an allowlist, not an ordered script. Never include unapproved consequential or credential actions." }),
28
+ values: Type.Optional(Type.Record(id, Type.String({ maxLength: 4096 }), { maxProperties: 64, description: "Supplied nonsecret single-line text, never generated by Decisions. Missing values hand back. Do not include credentials." })),
29
+ expect: Type.Optional(Type.Array(expectation, { minItems: 1, maxItems: 8, description: "All predicates must cover the full desired outcome. Without them DONE hands back for supervisor verification." })),
30
+ context: Type.Optional(Type.String({ maxLength: 4096, description: "Supervisor note after a handoff or unsupported action; not evidence of completion or new authorization." })),
31
+ previousActions: Type.Optional(Type.Array(Type.String({ maxLength: 256 }), { maxItems: 20 })),
32
+ maxActions: Type.Optional(Type.Integer({ minimum: 1, maximum: 100 })),
33
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1000, maximum: 300000 })),
34
+ deliveryMode: Type.Optional(Type.Union([Type.Literal("background"), Type.Literal("foreground")], { description: "Default background. Choose foreground only after observed background failure, within the same authorized target and scope." })),
35
+ }, { additionalProperties: false });
36
+
37
+ export function registerComputerUseTool(pi: ExtensionAPI): void {
38
+ let running = false;
39
+ pi.registerTool(defineTool({
40
+ name: "classifier_computer_use",
41
+ label: "Computer use · Decisions",
42
+ description: "Run a bounded OpenAI Decisions observe/select/act/verify loop on one exact Cua Driver window. Uses configured pi-classifier.computerUse, never the generic classifier default. Supply permitted semantic controls and nonsecret typing values. Decisions chooses from grounded candidates; it cannot invent coordinates or text. Returns explicit handoff and continuation when supervisor help is needed. Completion requires fresh independent Driver predicates; otherwise needs_verification. Existing Driver permissions and Pi tool hooks remain active. Window text and optional screenshots are sent to the configured OpenAI endpoint.",
43
+ promptSnippet: "Delegate repeated permitted computer actions to OpenAI Decisions; handle explicit supervisor handoffs and independently verify outcomes.",
44
+ promptGuidelines: [
45
+ "Resolve the intended app/account/window and observe semantic control names before calling. Supply only controls and effects authorized by the user's goal; an allowlist is not user consent.",
46
+ "Keep the goal bounded and values nonsecret. Keep content generation, credentials, CAPTCHAs, unsupported surfaces and consequential approvals with the supervisor or user.",
47
+ "On handoff inspect the reason, attempted actions and current state. Supply missing values or perform the unsupported step, then call again using handoff.continuation with an updated context note. Never replay a possibly applied action blindly.",
48
+ "Do not call other tools that observe or mutate the same window concurrently. Every continuation reobserves; never pass element tokens, screenshots or pending actions between chunks.",
49
+ "Only report verified completion when expect covers the whole user goal. Without independent predicates, inspect fresh evidence after needs_verification. Do not lower confidence or change provider to force progress.",
50
+ ],
51
+ parameters: computerUseParameters,
52
+ outputSchema: Type.Object({ status: Type.Union([Type.Literal("completed"), Type.Literal("handoff"), Type.Literal("stopped")]) }, { additionalProperties: true }),
53
+ reachesTools: () => Object.values(DRIVER_TOOLS),
54
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
55
+ async execute(_id, params, signal, onUpdate, ctx) {
56
+ if (running) throw new Error("Another computer-use chunk is running in this extension. Serialize access to the desktop.");
57
+ running = true;
58
+ try {
59
+ const result = await runComputerUse(params as ComputerUseParams, {
60
+ settings: loadClassifierSettings(ctx.cwd, isProjectTrusted(ctx)), cwd: ctx.cwd, ...(signal ? { signal } : {}),
61
+ callTool: async (name, args, nestedSignal): Promise<DriverReply> => {
62
+ const outcome = await ctx.executeTool(name, args, { signal: nestedSignal });
63
+ // Pi's MCP wrapper exposes the raw CallToolResult inside result.structuredContent.
64
+ const raw = outcome.result.structuredContent;
65
+ if (outcome.isError || !isRecord(raw)) return { isError: true };
66
+ return raw as DriverReply;
67
+ },
68
+ onProgress: (progress) => onUpdate?.({ content: [{ type: "text", text: `${progress.phase}: ${progress.actions} actions, ${progress.decisions} decisions` }], details: progress }),
69
+ });
70
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: result, structuredContent: JSON.parse(JSON.stringify(result)) };
71
+ } catch (error) {
72
+ throw new Error(error instanceof ClassifierError ? userError(error) : "Computer use could not start. Check computerUse settings and Driver availability.");
73
+ } finally { running = false; }
74
+ },
75
+ }));
76
+ }