@abhishek944/pi-classifier 0.3.0 → 0.4.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 (46) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +82 -6
  4. package/dist/box-tool.d.ts +26 -0
  5. package/dist/box-tool.js +109 -0
  6. package/dist/box.d.ts +32 -0
  7. package/dist/box.js +148 -0
  8. package/dist/classify.d.ts +3 -0
  9. package/dist/classify.js +1 -1
  10. package/dist/computer-use-state.d.ts +9 -0
  11. package/dist/computer-use-state.js +160 -0
  12. package/dist/computer-use-tool.d.ts +52 -0
  13. package/dist/computer-use-tool.js +78 -0
  14. package/dist/computer-use-types.d.ts +132 -0
  15. package/dist/computer-use-types.js +1 -0
  16. package/dist/computer-use.d.ts +22 -0
  17. package/dist/computer-use.js +223 -0
  18. package/dist/config.js +4 -0
  19. package/dist/extension.d.ts +38 -10
  20. package/dist/extension.js +36 -11
  21. package/dist/image-content.d.ts +12 -0
  22. package/dist/image-content.js +90 -0
  23. package/dist/index.d.ts +8 -1
  24. package/dist/index.js +2 -0
  25. package/dist/inputs.d.ts +9 -2
  26. package/dist/inputs.js +154 -130
  27. package/dist/providers.js +90 -87
  28. package/dist/types.d.ts +30 -12
  29. package/dist/validation.js +63 -38
  30. package/package.json +2 -1
  31. package/src/box-tool.ts +145 -0
  32. package/src/box.ts +253 -0
  33. package/src/choices.ts +2 -1
  34. package/src/classify.ts +4 -2
  35. package/src/computer-use-state.ts +145 -0
  36. package/src/computer-use-tool.ts +76 -0
  37. package/src/computer-use-types.ts +127 -0
  38. package/src/computer-use.ts +216 -0
  39. package/src/config.ts +4 -0
  40. package/src/extension.ts +39 -12
  41. package/src/image-content.ts +77 -0
  42. package/src/index.ts +10 -0
  43. package/src/inputs.ts +163 -185
  44. package/src/providers.ts +92 -105
  45. package/src/types.ts +20 -9
  46. package/src/validation.ts +62 -94
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - Added the opt-in OpenAI Decisions `classifier_computer_use` tool for a bounded observe/select/act/verify loop through existing Cua Driver MCP tools and Pi permission hooks, without changing the normal classifier default.
6
+ - Added task-scoped semantic controls, supplied nonsecret fill values, explicit supervisor handoff/continuation, fresh observation on resume, cancellation and action limits, no-progress handback, and independent Driver completion predicates. Unknown input outcomes are never automatically replayed.
7
+ - Added validated programmatic in-memory image inputs shared with existing classifier adapters, avoiding per-step screenshot files. Window-only passive text supplements indexed controls, and unrelated global menu-bar branches are excluded.
8
+ - Added bounded decision evidence, stage timings and accumulated provider usage/cost estimates, plus computer-use setup, privacy, supported-scope and handoff guidance in `COMPUTER_USE.md`.
9
+
10
+ - Added named local images and explicit `{$image:id}` references in shared state, Jev/OpenAI question instructions and Jev criteria, while retaining legacy shared image paths.
11
+ - Added OpenAI hosted HTTP(S) image descriptors without local downloads. Unsupported image placements fail before provider requests; Jev batching includes only assets used by the current batch.
12
+ - Added the local-only `classifier_box_image` tool and `renderClassifierBox` export for inline PNG box overlays or crops, without provider calls or automatic file writes.
13
+ - Added current Perplexity v1.2/Flash/latest model catalog entries and support for up to eight Perplexity images. Corrected Jev's minimum side length to 280 pixels.
14
+ - Documented capability differences, image-reference semantics, remote-image limits, experimental box caveats and user-owned verification steps. Video and unverified gateway image support remain excluded.
15
+
16
+ Verification: typecheck, build, package dry run/content checks and whitespace checks passed. Real registered-tool Pi SDK/OpenAI/Cua Driver scenarios on a controlled native macOS window verified multi-action completion, missing-value handoff and supervisor resumption, no-predicate handback, nested hook blocking, action limits and cancellation. Direct source review passed; independent review was unavailable because of session-path tooling. No unit tests were added or run. General browser/Electron typing, arbitrary canvas targets and broad third-party-app coverage remain unverified; no comparative speedup is claimed.
17
+
3
18
  ## 0.3.0
4
19
 
5
20
  - Added `classify_tree` and `classifyTree` for nested `roots`/`id`/`description`/`children` classification trees supplied inline or as bounded local UTF-8 JSON files. Results contain selected Level1/Level2/etc, model-versus-automatic steps, partial statuses and accumulated token/cost/provider-call totals.
@@ -0,0 +1,117 @@
1
+ # Computer use with OpenAI Decisions
2
+
3
+ `classifier_computer_use` runs repeated observations, decisions, and Cua Driver actions inside one Pi tool invocation. Pi's main agent remains the supervisor: it owns planning, authorization, content generation, unsupported controls, and final task-level review. The classifier chooses only among supplied, currently grounded controls.
4
+
5
+ This first release supports **one exact accessibility-backed native window per chunk**. Screenshots can supplement semantic state; they do not enable arbitrary pixel targeting. OpenAI Decisions does not generate text, coordinates, scripts, or bounding boxes.
6
+
7
+ ## Enable explicitly
8
+
9
+ Add this to trusted Pi settings, preserving your existing classifier configuration:
10
+
11
+ ```json
12
+ {
13
+ "pi-classifier": {
14
+ "computerUse": {
15
+ "enabled": true,
16
+ "route": { "provider": "openai-api", "model": "gpt-6-luna" },
17
+ "screenshots": true,
18
+ "minConfidence": 0.75
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Only `openai-api` is supported for computer use initially. Its normal configured endpoint and independent API-key resolution are reused. Missing credentials fail before a window observation. No provider fallback, automatic retry, comparison, sequential choice batching, or global default changes occur. Ordinary `classify` can continue using Jev.
25
+
26
+ The Cua Driver MCP server must already be configured and accessible as `mcp__cua_driver__*`. This extension does not install, launch, or reconfigure the daemon or request OS permissions. After installing/loading the updated extension, use `/reload` to expose the new tool.
27
+
28
+ **Privacy:** the selected endpoint receives the supplied goal, nonsecret values, bounded window labels/values, recent action summaries, and optional window screenshot. Use only the intended authorized window. Structured secure/password controls are excluded, but screenshots are not automatically redacted. Set `screenshots: false` for tree-only use. No screenshots or trajectory files are written by this feature. Do not pass passwords, tokens, payment information, or other secrets.
29
+
30
+ ## Supervisor workflow
31
+
32
+ 1. Resolve the intended app/account/window through Driver. Inspect its semantic controls. Prefer an existing app API or typed browser route when that is the reliable boundary.
33
+ 2. Define one bounded goal and permitted controls. Exact role and label are re-resolved on every observation. Controls can span later screens; their order is not a script. Duplicate matches are never selected arbitrarily.
34
+ 3. Supply reusable nonsecret values. Fill uses Driver `set_value`, which replaces native field values. It is not a reliable general browser/Electron typing implementation; use the supervisor's supported browser/input route for those widgets.
35
+ 4. Supply Driver completion predicates covering the entire requested result when possible. Every predicate requires an actual condition such as value, selection, enabled state, or existence.
36
+ 5. Call the tool and handle its result. Do not observe or mutate the same window in parallel; newer observations invalidate element tokens.
37
+
38
+ Example (replace PID, window ID, and semantic names with your actual observation):
39
+
40
+ ```js
41
+ classifier_computer_use({
42
+ goal: "Set City to Lisbon, apply it, and leave the resulting city visible.",
43
+ target: { pid: 1234, window_id: 5678 },
44
+ controls: [
45
+ { id: "city", operation: "fill", selector: { role: "AXTextField", label: "City" }, valueKey: "city" },
46
+ { id: "apply", operation: "click", selector: { role: "AXButton", label: "Apply" } }
47
+ ],
48
+ values: { city: "Lisbon" },
49
+ expect: [{ element: { selector: { role: "AXTextField", label_contains: "Result" }, value_equals: "Lisbon" } }],
50
+ maxActions: 10,
51
+ timeoutMs: 60000
52
+ });
53
+ ```
54
+
55
+ Actions supported:
56
+
57
+ - `click`: exact observed invokable/native control.
58
+ - `fill`: exact editable native field and supplied `valueKey`. Already matching values are not offered again. Values are single-line strings; control characters are rejected to avoid implicit submission/focus changes.
59
+ - `key`: one explicit permitted key addressed to an exact observed field/control. No global hotkeys or arbitrary modifiers.
60
+
61
+ The tool defaults to background delivery for clicks/keys. `deliveryMode: "foreground"` is an explicit supervisor choice after an observed background-delivery failure within the same authorized target. Announce the brief focus change and preserve user scope. Do not use it to bypass a refusal. Native `fill` uses Driver's semantic value route regardless of delivery mode; unsupported typing needs a handoff.
62
+
63
+ An allowlist scopes actions; **it does not grant consent**. The main agent must stop before unapproved purchases, sends, publishing, deleting valuable data, account/security changes, credentials, CAPTCHA, or OS consent. Existing Pi nested tool hooks and Driver authorization remain active. A model safety judgment is only additional evidence, not the permission boundary.
64
+
65
+ ## Explicit handoff and resumption
66
+
67
+ The result contains:
68
+
69
+ - `status`: `completed`, `handoff`, or `stopped`.
70
+ - `reason` and `message`: verified completion, missing value, supervisor help, low confidence, no progress, incomplete observation, loading timeout, action limit, cancellation/deadline, Driver failure, or failed verification.
71
+ - `actions`: every attempted action, including an interrupted action with `effect: "unknown"`.
72
+ - `metrics`: completed provider calls, token/cost estimates when available, stage durations, and `accountingIncomplete` when an interrupted/failed provider request might have been billed.
73
+ - `decision`: the last selected candidate, confidence, and selected probability, when available. These explain a handback without exposing raw model payloads.
74
+ - `handoff.continuation`: plain task arguments and bounded previous action summaries, **not** an executable capability, saved snapshot, queued action, or authorization token.
75
+
76
+ On missing text or unsupported work:
77
+
78
+ ```js
79
+ const next = result.handoff.continuation;
80
+ // The supervisor obtains/writes the nonsecret text or handles the unsupported step.
81
+ classifier_computer_use({
82
+ ...next,
83
+ values: { ...next.values, city: "Lisbon" },
84
+ context: "The requested city value is now supplied. Continue the original goal."
85
+ });
86
+ ```
87
+
88
+ Every chunk takes a fresh observation and asks for a new decision. No snapshot, pixel capture, or element token survives a handoff. The supervisor may adjust controls to match a later screen only when the original task authorizes those effects. If the application switched to a different native window, resolve it explicitly before updating the target.
89
+
90
+ **Unknown action outcome:** inspect application state before resuming. A timeout or tool error does not mean input was not applied. The extension records the attempt and never automatically retries it. No-progress after unverified input returns control rather than replaying a possible submission. Do not lower confidence simply to force progress; the threshold is an uncalibrated handback heuristic.
91
+
92
+ ## Completion and stopping
93
+
94
+ A Decisions `DONE` choice is only a claim. It may request read-only verification even below the mutation confidence threshold; it never dispatches uncertain input. With `expect`, the tool requests fresh `verify_state` evidence with two stable satisfied samples. Only all satisfied predicates yield `completed`. Unknown, ambiguous, or unsatisfied results hand back. The supervisor must still check that the predicates cover the **whole** goal and use application-owned state/reopen checks for saves when appropriate.
95
+
96
+ Without `expect`, `DONE` returns `handoff / needs_verification`. This supports visual or semantic goals that Driver predicates cannot independently express without making a false success claim.
97
+
98
+ The observation is bounded to 180 elements, depth 14, and a 1.5-second AX budget. Explicitly truncated/degraded trees hand back. Driver's indexed list omits passive text, so `elements_complete: false` alone is not treated as a truncated walk or evidence of absence. Bounded window-only passive text supplements indexed controls; global menu-bar branches are excluded, independently of their ordering. Missing or duplicate eligible control matches are never guessed. The default chunk is 20 actions and 60 seconds, with bounded waits and model decisions. Caller cancellation/deadline propagates to nested tools and HTTP, but cannot undo an OS event already dispatched. No blind batches or automatic rollback are attempted.
99
+
100
+ ## Programmatic use
101
+
102
+ The package exports `runComputerUse(params, { settings, cwd, callTool, signal?, onProgress? })`. `callTool` must dispatch through the host's real approval/tool pipeline and return the raw MCP `CallToolResult`. The Pi tool does this through `ctx.executeTool()`, unwrapping Pi's MCP result envelope. Do not substitute another SDK connection to evade approvals.
103
+
104
+ `classify(params, options)` additionally supports `options.memoryImages`, an array of `{bytes: Uint8Array, mimeType}`. These transient images pass the same byte/pixel/full-decode and route checks as files. They supplement shared input; named references still refer only to normal named descriptors. Model-facing `classify` parameters remain path/descriptor-based. New image ingress does not weaken local-path validation.
105
+
106
+ ## Design references
107
+
108
+ This is original implementation, not vendored code. Useful patterns were curated from:
109
+
110
+ - [Browser Use Jev Ultrafast](https://github.com/browser-use/jev-ultrafast): indexed grounded actions, code-owned loop, single decision round trip.
111
+ - [Ying-Kai-Liao/jev-browser](https://github.com/Ying-Kai-Liao/jev-browser): caller values and explicit handback statuses.
112
+ - [Decision Luna Browser Lab](https://github.com/humanity-forever/decision-luna-browse-control): independent completion and waiting evidence.
113
+ - [CUA-JEV](https://github.com/ZJU-REAL/CUA-JEV): legal candidate/executor boundary.
114
+ - [Jev Browser Use](https://github.com/wy-coliney/jev-browser-use): supervisor allowlists and resumption inside an existing connection.
115
+ - [0x7067/jev-browse](https://github.com/0x7067/jev-browse): explicit action phases and bounded progress history.
116
+
117
+ Their speed/reliability results are not performance claims for this extension. Driver pacing is unchanged; stage metrics should identify whether model inference, observation, or Driver waits dominate the actual workload.
package/README.md CHANGED
@@ -9,7 +9,7 @@ One configured default, optional selective fallback, and explicit model comparis
9
9
  Requires Node.js 22.19+ and Pi 1.2+. Install the tagged release from GitHub:
10
10
 
11
11
  ```sh
12
- pi install git:github.com/abhishek944/pi-classifier@v0.3.0
12
+ pi install git:github.com/abhishek944/pi-classifier@v0.4.0
13
13
  ```
14
14
 
15
15
  The Pi package entrypoint is TypeScript source, so Git installs do not depend on committed build artifacts or a TypeScript compiler. Runtime dependencies are installed by Pi. The compiled `dist` exports remain available for library consumers after a build.
@@ -30,7 +30,7 @@ To install persistently after trying it:
30
30
  pi install /absolute/path/to/pi-classifier
31
31
  ```
32
32
 
33
- The package version and Git tag are `0.3.0` / `v0.3.0`. Installation is explicit. This release is prepared for GitHub; npm publication is a separate manual step.
33
+ The package version and Git tag are `0.4.0` / `v0.4.0`. Installation is explicit. This release is prepared for GitHub; npm publication is a separate manual step.
34
34
 
35
35
  ## Configuration: same shape as pi-image-gen
36
36
 
@@ -84,7 +84,7 @@ Stored API-key values support literal strings and `$NAME`/`${NAME}` references,
84
84
  | ---------------- | --------------------- | ------------------------------------------------------------------ | -------------------- |
85
85
  | `microsoft-api` | `microsoft` | `Microsoft-Decision-1` (select your actual deployment name) | `AZURE_API_KEY` |
86
86
  | `openai-api` | `openai` | `gpt-6-luna` | `OPENAI_API_KEY` |
87
- | `perplexity-api` | `perplexity` | `pplx-decider-v1.1-27b`, `pplx-decider-v1-27b` | `PERPLEXITY_API_KEY` |
87
+ | `perplexity-api` | `perplexity` | `pplx-decider-v1.2`, `pplx-decider-flash-v1.2`, latest aliases, legacy v1/v1.1 IDs | `PERPLEXITY_API_KEY` |
88
88
  | `typesafe-api` | `typesafe` | `jev-latest`, `jev-1.13.0`, `jev-preview`, `jev-1.14.0` | `TYPESAFE_API_KEY` |
89
89
  | `cloudflare-api` | `cloudflare` | `@cf/cloudflare/clef`, `@cf/cloudflare/clef-flash`, `typesafe/jev` | `CLOUDFLARE_API_KEY` |
90
90
  | `openrouter-api` | `openrouter` | `typesafe/jev-1.13`, `~typesafe/jev-latest` | `OPENROUTER_API_KEY` |
@@ -179,7 +179,7 @@ classify_tree({
179
179
  });
180
180
  ```
181
181
 
182
- `instructions` is optional and at most 8192 characters. Text/JSON `state` and optional local `images` use the existing classifier input rules. No provider/model override is accepted. The library exports `classifyTree(params, { settings, cwd, signal? })` and the `ClassificationTree`, `ClassificationTreeNode`, `ClassifyTreeParams`, `TreeStep` and `ClassifierTreeResult` types.
182
+ `instructions` is optional and at most 8192 characters. Text/JSON `state` and optional `images` use the existing classifier input rules, including named images referenced in state. Tree definitions and tree instructions remain text-only. No provider/model override is accepted. The library exports `classifyTree(params, { settings, cwd, signal? })` and the `ClassificationTree`, `ClassificationTreeNode`, `ClassifyTreeParams`, `TreeStep` and `ClassifierTreeResult` types.
183
183
 
184
184
  ### Traversal and results
185
185
 
@@ -358,9 +358,11 @@ The library exports `compareClassifiers(params, { settings, cwd, signal? })`. Ne
358
358
 
359
359
  Pass `images: ["photo.png"]`. Images are attached in order alongside state. OpenAI, Perplexity and Clef/Clef Flash support images. Cloudflare-hosted Jev and the built-in OpenRouter route are text-only in this package.
360
360
 
361
- Image inputs are local non-animated PNG/JPEG/WebP regular files inside the session cwd, with no symlink components, URLs or inline base64. Safe descriptor-based loading currently supports macOS (requires the OS `/usr/sbin/lsof`) and Linux (`/proc`); other platforms support text classification only. Images are fully decoded locally before upload. Limits: five images; 5 MiB each, 10 MiB total and 16 megapixels each. Clef has stricter limits: four images, 4 MiB each and 8 MiB total. Perplexity requires at most 2048 tiles of 32×32 pixels per image; resize before sending. Images are not silently resized. Text/JSON plus questions are limited to 2 MiB, with at most 32 questions per call.
361
+ Local image inputs are non-animated PNG/JPEG/WebP regular files inside the session cwd, with no symlink components or inline base64. Safe descriptor-based loading supports macOS (requires the OS `/usr/sbin/lsof`) and Linux (`/proc`). Images are fully decoded locally before upload. Limits: five images on OpenAI/Jev, eight on Perplexity; 5 MiB each, 10 MiB total and 16 megapixels each. Clef has stricter limits: four images, 4 MiB each and 8 MiB total. Perplexity allows at most eight image occurrences in shared state, including repeated references, and requires at most 2048 tiles of 32×32 pixels per image. Images are not silently resized. Text/JSON plus questions remain limited to 2 MiB and 32 questions.
362
362
 
363
- TypeSafe Jev images are experimental and require opt-in. Use PNG/JPEG. Each side must be 256–1568 pixels, with total area 78,400–2,458,624 pixels; resize or pad beforehand. These limits also apply to custom SystemOne image routes using Jev's assets protocol:
363
+ Named hosted URLs on OpenAI do not require local file loading and work on other platforms. They are passed directly to the selected OpenAI-compatible endpoint, never downloaded by this package. The provider must be able to access them and enforces remote image format/size limits; local byte/pixel validation cannot inspect them. URLs must use HTTP(S), with no credentials or fragment. Do not send sensitive URLs unless you intend to share them with that endpoint.
364
+
365
+ TypeSafe Jev images are experimental and require opt-in. Use PNG/JPEG. Each side must be **280–1568 pixels**, with total area 78,400–2,458,624 pixels; resize or pad beforehand. These limits also apply to custom SystemOne image routes using Jev's assets protocol:
364
366
 
365
367
  ```json
366
368
  {
@@ -379,6 +381,73 @@ TypeSafe Jev images are experimental and require opt-in. Use PNG/JPEG. Each side
379
381
 
380
382
  With an image, a question such as `{ "type": "box", "instructions": "Find the mug in the first image." }` returns normalized `top`, `bottom`, `left`, `right` edges and confidence. Box needs Jev 1.14 (`jev-preview` or `jev-1.14.0`) and both opt-ins. It is not production-grade localization. A box does not mean the object exists: pair it with a bool existence question when necessary.
381
383
 
384
+ ### Named images and composable image content
385
+
386
+ Existing `images: ["photo.png"]` still attaches every image to shared state in order. Alternatively, use named descriptors:
387
+
388
+ ```json
389
+ {
390
+ "state": { "scene": { "$image": "scene" } },
391
+ "images": [
392
+ { "id": "scene", "path": "scene.png" },
393
+ { "id": "target", "path": "reference.jpg" }
394
+ ],
395
+ "questions": {
396
+ "present": {
397
+ "type": "bool",
398
+ "instructions": ["Does the scene contain the object shown here? ", { "$image": "target" }]
399
+ }
400
+ }
401
+ }
402
+ ```
403
+
404
+ Image IDs must be unique, 1–64 letters/digits/underscores/hyphens. Each named image must be referenced, and every reference must resolve. The exact object `{"$image":"id"}` is reserved for image references, not ordinary JSON data. Named images are not also attached automatically. Ordinary provider-looking JSON, such as an `image_url` key, remains text/data and cannot inject native image parts.
405
+
406
+ `instructions` and criterion descriptions accept either the existing text string or an ordered array of strings and image references. Jev preserves these as structured arrays with asset references. Other supported adapters concatenate adjacent text parts; include spaces/newlines where needed. For Jev, criterion descriptions can include visual examples:
407
+
408
+ ```json
409
+ {
410
+ "type": "choice",
411
+ "instructions": "Which reference most resembles the scene?",
412
+ "criteria": {
413
+ "good": ["Correct assembly: ", { "$image": "good_example" }],
414
+ "bad": ["Incorrect assembly: ", { "$image": "bad_example" }]
415
+ }
416
+ }
417
+ ```
418
+
419
+ Declare these images in the surrounding request's `images` list. The same content form works for each score level and bool true/false descriptions on Jev.
420
+
421
+ | Placement | Jev assets protocol | OpenAI Decisions | Perplexity Decisions | Clef / Flash |
422
+ | --- | --- | --- | --- | --- |
423
+ | Legacy shared local paths | Yes, opt-in | Yes | Yes | Yes |
424
+ | Named references in shared state | Yes, opt-in | Yes | Yes | No |
425
+ | Images in question instructions | Yes, opt-in | Yes | No | No |
426
+ | Images in criteria | Yes, opt-in | No | No | No |
427
+ | Named hosted URL descriptors | No | Yes | No | No |
428
+
429
+ For OpenAI, replace a named local descriptor with `{"id":"target","url":"https://example.com/reference.jpg"}` and reference it in state or instructions. Nested JSON state is represented as text fragments interleaved with the referenced images; it is not an upstream JSON object containing embedded native parts. Unsupported placements fail locally before a request, including on fallback and comparison routes. No image is silently dropped or moved.
430
+
431
+ Jev uploads each used named image once per provider call. Choice batching sends only assets referenced by that batch, so images used only by settled questions or later criteria are not sent unnecessarily. Reusing an image reference still counts each occurrence against Jev's expanded request limits; the server may reject a request after re-encoding/expansion. No automatic image splitting, resizing or multipart upload is performed.
432
+
433
+ ### Local bounding-box visualization and cropping
434
+
435
+ Use **`classifier_box_image`** with a local image and a returned normalized box:
436
+
437
+ ```json
438
+ {
439
+ "image": "scene.png",
440
+ "box": { "top": 0.25, "bottom": 0.82, "left": 0.44, "right": 0.84 },
441
+ "mode": "overlay"
442
+ }
443
+ ```
444
+
445
+ The default `overlay` mode draws the box. Set `mode: "crop"` to extract its region. This tool is local-only: no classifier request, provider charge, URL download or file write. It returns an inline PNG plus dimensions and the pixel-space box. Local input limits are 5 MiB and 16 megapixels; the PNG output is limited to 10 MiB. Coordinates refer to stored image dimensions, without automatic EXIF rotation. Verify you are using the same image that the provider evaluated.
446
+
447
+ The library exports `renderClassifierBox(params, { cwd, signal? })`, which returns PNG base64 data, MIME type, dimensions, pixel box and mode. Saving the result is the caller's responsibility. A box is not proof that an object exists; check existence separately.
448
+
449
+ Video descriptions in Cloudflare's model pages do not establish a hosted video API contract. Video, segmentation masks, multi-object box lists, image generation/editing and gateway image parity are not implemented.
450
+
382
451
  ## Custom providers
383
452
 
384
453
  Like image-gen, `customProviders` adds a named endpoint and explicit model list. Supported protocols are `openai-decisions`, `perplexity-decisions`, `system-one`, `cloudflare-system-one`, and `microsoft-system-one` (Foundry resource root and API-key authentication). A custom URL cannot make an arbitrary API compatible. Custom IDs must not shadow built-in provider/route IDs.
@@ -402,6 +471,10 @@ Like image-gen, `customProviders` adds a named endpoint and explicit model list.
402
471
 
403
472
  Custom endpoints use their route ID as the Pi stored-credential provider ID. They have no implicit environment variable; use an explicit key reference. SystemOne image endpoints must implement Jev's assets protocol, declare image input and opt into `experimentalImages`. Box additionally requires `box: true` on the model and `experimentalBox: true` on the provider.
404
473
 
474
+ ## Goal-running computer use (OpenAI Decisions)
475
+
476
+ The optional `classifier_computer_use` tool runs a bounded Cua Driver loop inside Pi, selecting only supervisor-permitted controls and returning explicit handoff/continuation when help is needed. It has a separate opt-in OpenAI route, preserves the normal classifier default, accepts transient Driver screenshots without disk files, and verifies completion through fresh Driver predicates. See [COMPUTER_USE.md](COMPUTER_USE.md) for setup, real input/output examples, safety limits, supervisor resumption and verification.
477
+
405
478
  ## Development and live verification
406
479
 
407
480
  ```sh
@@ -420,6 +493,9 @@ No provider calls are made by these commands. Live tests belong to the user:
420
493
  6. Configure your Foundry endpoint and deployment name, select `microsoft-api`, and verify bool/choice/score responses and token usage. Verify an image is rejected locally.
421
494
  7. Configure two `compare` pairs and explicitly invoke `classify_compare`; confirm labeled successes/errors, duration, unchanged defaults, and that cancellation prevents subsequent calls. Each valid entry may be billed.
422
495
  8. In your own controlled deployment, verify missing keys and HTTP 401/404/429 allow only configured fallbacks; duplicate routes are never called twice. Verify low confidence and refusals return normally without switching models.
496
+ 9. On Jev, enable the image/box flags and try the named scene/reference example above. Compare visual choice/score criteria, then a box plus a separate existence question. Verify repeated references and choice batching do not leave unreferenced assets. Try a 279-pixel side and confirm local rejection.
497
+ 10. On OpenAI, try one shared named local image plus a question-specific local image, then replace the latter with a public HTTPS descriptor. Confirm references stay in their intended placements. On Perplexity, try named state references and eight small images; instruction/criterion images should fail locally.
498
+ 11. Invoke `classifier_box_image` with the exact local scene and a returned box in both overlay and crop modes. Confirm pixel bounds and orientation visually, no files are written, invalid/reversed edges are rejected, and cancellation interrupts processing. Check EXIF-oriented photos carefully: no automatic rotation is applied.
423
499
 
424
500
  Provider schemas and previews can change; no live entitlement or model-accuracy claim is made by a local build.
425
501
 
@@ -0,0 +1,26 @@
1
+ import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ export declare const boxParameters: Type.TObject<{
4
+ image: Type.TString;
5
+ box: Type.TObject<{
6
+ top: Type.TNumber;
7
+ bottom: Type.TNumber;
8
+ left: Type.TNumber;
9
+ right: Type.TNumber;
10
+ }>;
11
+ mode: Type.TOptional<Type.TUnion<[Type.TLiteral<"overlay">, Type.TLiteral<"crop">]>>;
12
+ }>;
13
+ export declare const boxOutput: Type.TObject<{
14
+ mode: Type.TUnion<[Type.TLiteral<"overlay">, Type.TLiteral<"crop">]>;
15
+ mimeType: Type.TLiteral<"image/png">;
16
+ width: Type.TInteger;
17
+ height: Type.TInteger;
18
+ pixelBox: Type.TObject<{
19
+ left: Type.TInteger;
20
+ top: Type.TInteger;
21
+ width: Type.TInteger;
22
+ height: Type.TInteger;
23
+ }>;
24
+ byteLength: Type.TInteger;
25
+ }>;
26
+ export declare function registerBoxTool(pi: ExtensionAPI): void;
@@ -0,0 +1,109 @@
1
+ import { defineTool, } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { renderClassifierBox, } from "./box.js";
4
+ import { ClassifierError, userError } from "./types.js";
5
+ export const boxParameters = Type.Object({
6
+ image: Type.String({
7
+ minLength: 1,
8
+ maxLength: 4096,
9
+ description: "Local PNG, JPEG or WebP file inside cwd. No URLs, symlinks or inline base64.",
10
+ }),
11
+ box: Type.Object({
12
+ top: Type.Number({ minimum: 0, maximum: 1 }),
13
+ bottom: Type.Number({ minimum: 0, maximum: 1 }),
14
+ left: Type.Number({ minimum: 0, maximum: 1 }),
15
+ right: Type.Number({ minimum: 0, maximum: 1 }),
16
+ }, {
17
+ additionalProperties: false,
18
+ description: "Normalized edges between 0 and 1, with top < bottom and left < right.",
19
+ }),
20
+ mode: Type.Optional(Type.Union([Type.Literal("overlay"), Type.Literal("crop")], {
21
+ description: "overlay draws the box on the image (default); crop returns only the boxed region.",
22
+ })),
23
+ }, { additionalProperties: false });
24
+ export const boxOutput = Type.Object({
25
+ mode: Type.Union([Type.Literal("overlay"), Type.Literal("crop")]),
26
+ mimeType: Type.Literal("image/png"),
27
+ width: Type.Integer({ minimum: 1 }),
28
+ height: Type.Integer({ minimum: 1 }),
29
+ pixelBox: Type.Object({
30
+ left: Type.Integer({ minimum: 0 }),
31
+ top: Type.Integer({ minimum: 0 }),
32
+ width: Type.Integer({ minimum: 1 }),
33
+ height: Type.Integer({ minimum: 1 }),
34
+ }),
35
+ byteLength: Type.Integer({ minimum: 1 }),
36
+ });
37
+ export function registerBoxTool(pi) {
38
+ pi.registerTool(defineTool({
39
+ name: "classifier_box_image",
40
+ label: "Box image",
41
+ description: "Render a normalized bounding box on a local image, or crop to it, entirely locally. Use to inspect a box answer from classify. overlay keeps the image and draws a rectangle; crop returns only the clamped region. Returns a PNG plus exact source-pixel box metadata. No provider request, upload, resizing or disk write. A box is a localization hint, not proof that the object exists.",
42
+ promptSnippet: "Render or crop a local image using normalized box coordinates.",
43
+ promptGuidelines: [
44
+ "Use classifier_box_image only for local images inside cwd and normalized boxes between 0 and 1.",
45
+ "A returned box does not by itself confirm that the object exists.",
46
+ ],
47
+ parameters: boxParameters,
48
+ outputSchema: boxOutput,
49
+ annotations: {
50
+ readOnlyHint: true,
51
+ destructiveHint: false,
52
+ openWorldHint: false,
53
+ },
54
+ async execute(_id, params, signal, _onUpdate, ctx) {
55
+ try {
56
+ const result = await renderClassifierBox(params, {
57
+ cwd: ctx.cwd,
58
+ ...(signal ? { signal } : {}),
59
+ });
60
+ const byteLength = Buffer.from(result.data, "base64").byteLength;
61
+ const details = {
62
+ mode: result.mode,
63
+ mimeType: result.mimeType,
64
+ width: result.width,
65
+ height: result.height,
66
+ pixelBox: result.pixelBox,
67
+ byteLength,
68
+ };
69
+ const box = result.pixelBox;
70
+ return {
71
+ content: [
72
+ {
73
+ type: "text",
74
+ text: "Rendered " +
75
+ result.mode +
76
+ " box as a " +
77
+ result.width +
78
+ "×" +
79
+ result.height +
80
+ " PNG (" +
81
+ byteLength +
82
+ " bytes). Source pixel box: left=" +
83
+ box.left +
84
+ ", top=" +
85
+ box.top +
86
+ ", width=" +
87
+ box.width +
88
+ ", height=" +
89
+ box.height +
90
+ ". A box is a localization hint, not proof that the object exists.",
91
+ },
92
+ {
93
+ type: "image",
94
+ data: result.data,
95
+ mimeType: result.mimeType,
96
+ },
97
+ ],
98
+ details,
99
+ structuredContent: details,
100
+ };
101
+ }
102
+ catch (error) {
103
+ console.error("[pi-classifier] box image failed: " +
104
+ (error instanceof ClassifierError ? error.code : "unexpected"));
105
+ throw new Error(userError(error));
106
+ }
107
+ },
108
+ }));
109
+ }
package/dist/box.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ export type ClassifierBoxMode = "overlay" | "crop";
2
+ export type ClassifierBoxEdges = {
3
+ top: number;
4
+ bottom: number;
5
+ left: number;
6
+ right: number;
7
+ };
8
+ /** Pixel coordinates in the source image. */
9
+ export type ClassifierBoxPixelBox = {
10
+ left: number;
11
+ top: number;
12
+ width: number;
13
+ height: number;
14
+ };
15
+ export type ClassifierBoxResult = {
16
+ data: string;
17
+ mimeType: "image/png";
18
+ width: number;
19
+ height: number;
20
+ pixelBox: ClassifierBoxPixelBox;
21
+ mode: ClassifierBoxMode;
22
+ };
23
+ /**
24
+ * Render a normalized box on a local image, or crop to it, without a provider
25
+ * request or disk write. File containment, byte limits and full decoding are
26
+ * owned by loadLocalImage; this module owns coordinates, rendering and output
27
+ * limits.
28
+ */
29
+ export declare function renderClassifierBox(params: unknown, options: {
30
+ cwd: string;
31
+ signal?: AbortSignal;
32
+ }): Promise<ClassifierBoxResult>;
package/dist/box.js ADDED
@@ -0,0 +1,148 @@
1
+ import sharp from "sharp";
2
+ import { loadLocalImage } from "./inputs.js";
3
+ import { ClassifierError, isRecord } from "./types.js";
4
+ const MAX_PIXELS = 16_777_216;
5
+ const MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
6
+ const RENDER_TIMEOUT_SECONDS = 10;
7
+ const RENDER_TIMEOUT_MS = RENDER_TIMEOUT_SECONDS * 1000;
8
+ const MAX_PATH_LENGTH = 4096;
9
+ /**
10
+ * Render a normalized box on a local image, or crop to it, without a provider
11
+ * request or disk write. File containment, byte limits and full decoding are
12
+ * owned by loadLocalImage; this module owns coordinates, rendering and output
13
+ * limits.
14
+ */
15
+ export async function renderClassifierBox(params, options) {
16
+ cancelled(options.signal);
17
+ const parsed = validateBoxParams(params);
18
+ const image = await loadLocalImage(parsed.image, options.cwd, options.signal);
19
+ cancelled(options.signal);
20
+ const pixelBox = toPixelBox(parsed.box, image.width, image.height);
21
+ let rendered;
22
+ try {
23
+ const source = sharp(Buffer.from(image.data, "base64"), {
24
+ limitInputPixels: MAX_PIXELS,
25
+ failOn: "warning",
26
+ }).timeout({ seconds: RENDER_TIMEOUT_SECONDS });
27
+ rendered =
28
+ parsed.mode === "crop"
29
+ ? await renderPng(source.extract(pixelBox), options.signal)
30
+ : await renderPng(source.composite([
31
+ {
32
+ input: Buffer.from(overlaySvg(image.width, image.height, pixelBox)),
33
+ top: 0,
34
+ left: 0,
35
+ },
36
+ ]), options.signal);
37
+ }
38
+ catch (error) {
39
+ cancelled(options.signal);
40
+ if (error instanceof ClassifierError)
41
+ throw error;
42
+ if (error instanceof Error && /time(d)?\s*out/i.test(error.message))
43
+ throw new ClassifierError("input", "Box rendering timed out.");
44
+ throw new ClassifierError("input", "Could not render the box image. Use a non-animated PNG/JPEG/WebP inside cwd and a valid box.");
45
+ }
46
+ cancelled(options.signal);
47
+ if (rendered.data.length > MAX_OUTPUT_BYTES)
48
+ throw new ClassifierError("input", "The box output PNG is larger than 10 MiB. Use crop or a smaller region.");
49
+ return {
50
+ data: rendered.data.toString("base64"),
51
+ mimeType: "image/png",
52
+ width: rendered.width,
53
+ height: rendered.height,
54
+ pixelBox,
55
+ mode: parsed.mode,
56
+ };
57
+ }
58
+ function validateBoxParams(value) {
59
+ if (!isRecord(value) ||
60
+ Object.keys(value).some((key) => !["image", "box", "mode"].includes(key)))
61
+ invalid("Expected image, box and optional mode; unknown fields are rejected.");
62
+ const image = value.image;
63
+ if (typeof image !== "string" ||
64
+ !image.trim() ||
65
+ image.length > MAX_PATH_LENGTH)
66
+ invalid("image must be a local PNG/JPEG/WebP path inside cwd.");
67
+ const candidate = value.box;
68
+ if (!isRecord(candidate) ||
69
+ Object.keys(candidate).some((key) => !["top", "bottom", "left", "right"].includes(key)))
70
+ invalid("box must contain only top, bottom, left and right.");
71
+ const { top, bottom, left, right } = candidate;
72
+ if (!isNormalized(top) ||
73
+ !isNormalized(bottom) ||
74
+ !isNormalized(left) ||
75
+ !isNormalized(right))
76
+ invalid("box edges must be finite normalized numbers between 0 and 1.");
77
+ if (top >= bottom || left >= right)
78
+ invalid("box must have top < bottom and left < right.");
79
+ const mode = value.mode ?? "overlay";
80
+ if (mode !== "overlay" && mode !== "crop")
81
+ invalid("mode must be overlay or crop.");
82
+ return { image, box: { top, bottom, left, right }, mode };
83
+ }
84
+ function isNormalized(value) {
85
+ return (typeof value === "number" &&
86
+ Number.isFinite(value) &&
87
+ value >= 0 &&
88
+ value <= 1);
89
+ }
90
+ /** Floor/ceil edges, then clamp to the source so the region always has pixels. */
91
+ function toPixelBox(box, width, height) {
92
+ const left = Math.min(Math.max(Math.floor(box.left * width), 0), width - 1);
93
+ const top = Math.min(Math.max(Math.floor(box.top * height), 0), height - 1);
94
+ const right = Math.min(Math.max(Math.ceil(box.right * width), left + 1), width);
95
+ const bottom = Math.min(Math.max(Math.ceil(box.bottom * height), top + 1), height);
96
+ return { left, top, width: right - left, height: bottom - top };
97
+ }
98
+ /** Fixed rectangle built only from computed integers, so no caller text enters the SVG. */
99
+ function overlaySvg(width, height, box) {
100
+ const stroke = Math.max(2, Math.min(8, Math.round(Math.min(width, height) / 200)));
101
+ const inset = Math.floor(stroke / 2);
102
+ const insetFits = box.width > inset * 2 && box.height > inset * 2;
103
+ const x = insetFits ? box.left + inset : box.left;
104
+ const y = insetFits ? box.top + inset : box.top;
105
+ const rectWidth = Math.max(1, box.width - (insetFits ? inset * 2 : 0));
106
+ const rectHeight = Math.max(1, box.height - (insetFits ? inset * 2 : 0));
107
+ return (`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
108
+ `<rect x="${x}" y="${y}" width="${rectWidth}" height="${rectHeight}" fill="none" stroke="#ff2d55" stroke-width="${stroke}"/>` +
109
+ `</svg>`);
110
+ }
111
+ async function renderPng(pipeline, signal) {
112
+ cancelled(signal);
113
+ let cancel = () => { };
114
+ let timer;
115
+ try {
116
+ return await new Promise((resolve, reject) => {
117
+ let settled = false;
118
+ const settle = (action) => {
119
+ if (settled)
120
+ return;
121
+ settled = true;
122
+ action();
123
+ };
124
+ cancel = () => {
125
+ pipeline.destroy();
126
+ settle(() => reject(new ClassifierError("aborted", "Box rendering was cancelled.")));
127
+ };
128
+ signal?.addEventListener("abort", cancel, { once: true });
129
+ timer = setTimeout(() => {
130
+ pipeline.destroy();
131
+ settle(() => reject(new ClassifierError("input", "Box rendering timed out.")));
132
+ }, RENDER_TIMEOUT_MS);
133
+ pipeline.png().toBuffer({ resolveWithObject: true }).then(({ data, info }) => settle(() => resolve({ data, width: info.width, height: info.height })), (error) => settle(() => reject(error)));
134
+ });
135
+ }
136
+ finally {
137
+ if (timer)
138
+ clearTimeout(timer);
139
+ signal?.removeEventListener("abort", cancel);
140
+ }
141
+ }
142
+ function invalid(message) {
143
+ throw new ClassifierError("input", message);
144
+ }
145
+ function cancelled(signal) {
146
+ if (signal?.aborted)
147
+ throw new ClassifierError("aborted", "Box rendering was cancelled.");
148
+ }
@@ -1,8 +1,11 @@
1
+ import { type MemoryImage } from "./inputs.js";
1
2
  import { type ClassifierComparisonResult, type ClassifierResult, type ClassifierSettings } from "./types.js";
2
3
  export type ClassifyOptions = {
3
4
  settings: ClassifierSettings;
4
5
  cwd: string;
5
6
  signal?: AbortSignal;
7
+ /** Trusted programmatic ingress; all bytes still pass normal image validation. */
8
+ memoryImages?: readonly MemoryImage[];
6
9
  };
7
10
  /** Default plus explicitly configured, selective fallback. Never retries a route. */
8
11
  export declare function classify(params: unknown, options: ClassifyOptions): Promise<ClassifierResult>;
package/dist/classify.js CHANGED
@@ -18,7 +18,7 @@ function routePair(route) {
18
18
  }
19
19
  async function classifyOnce(input, route, options) {
20
20
  checkCancelled(options.signal);
21
- const prepared = await prepareInput(input, route, options.cwd, options.signal);
21
+ const prepared = await prepareInput(input, route, options.cwd, options.signal, options.memoryImages);
22
22
  checkCancelled(options.signal);
23
23
  const key = resolveApiKey(route);
24
24
  const result = await executeChoices(prepared, route, choicePolicy(options.settings), (questions) => classifyWithProvider(route, { ...prepared, questions }, key, options.signal), options.signal);
@@ -0,0 +1,9 @@
1
+ import type { ComputerCandidate, ComputerUseParams, DriverObservation, DriverReply } from "./computer-use-types.js";
2
+ import type { MemoryImage } from "./inputs.js";
3
+ export declare const KEY_NAMES: string[];
4
+ export declare function validateComputerParams(params: ComputerUseParams): void;
5
+ export declare function driverState(reply: DriverReply): Record<string, unknown>;
6
+ export declare function observation(reply: DriverReply, target: ComputerUseParams["target"]): DriverObservation;
7
+ export declare function candidates(params: ComputerUseParams, state: DriverObservation): ComputerCandidate[];
8
+ export declare function modelElements(state: DriverObservation): unknown[];
9
+ export declare function captureImage(reply: DriverReply): MemoryImage[];