@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.
- package/CHANGELOG.md +48 -0
- package/COMPUTER_USE.md +117 -0
- package/README.md +344 -30
- package/dist/auth.d.ts +4 -2
- package/dist/auth.js +18 -2
- package/dist/box-tool.d.ts +4 -0
- package/dist/box-tool.js +79 -0
- package/dist/box.d.ts +32 -0
- package/dist/box.js +148 -0
- package/dist/choices.js +35 -1
- package/dist/classify.d.ts +6 -0
- package/dist/classify.js +4 -4
- package/dist/computer-use-state.d.ts +9 -0
- package/dist/computer-use-state.js +160 -0
- package/dist/computer-use-tool.d.ts +52 -0
- package/dist/computer-use-tool.js +78 -0
- package/dist/computer-use-types.d.ts +132 -0
- package/dist/computer-use-types.js +1 -0
- package/dist/computer-use.d.ts +22 -0
- package/dist/computer-use.js +223 -0
- package/dist/config.d.ts +140 -3
- package/dist/config.js +405 -20
- package/dist/cost.js +42 -4
- package/dist/durable.d.ts +34 -0
- package/dist/durable.js +237 -0
- package/dist/extension.d.ts +2 -247
- package/dist/extension.js +53 -190
- package/dist/extract.d.ts +11 -0
- package/dist/extract.js +191 -0
- package/dist/http.d.ts +6 -1
- package/dist/http.js +64 -28
- package/dist/image-content.d.ts +12 -0
- package/dist/image-content.js +90 -0
- package/dist/index.d.ts +10 -1
- package/dist/index.js +3 -0
- package/dist/inputs.d.ts +24 -2
- package/dist/inputs.js +565 -134
- package/dist/mcp-cli.d.ts +2 -0
- package/dist/mcp-cli.js +39 -0
- package/dist/mcp-server.d.ts +28 -0
- package/dist/mcp-server.js +121 -0
- package/dist/mcp-tool-definitions.d.ts +19 -0
- package/dist/mcp-tool-definitions.js +64 -0
- package/dist/providers.d.ts +1 -0
- package/dist/providers.js +1218 -124
- package/dist/tool-contracts.d.ts +785 -0
- package/dist/tool-contracts.js +530 -0
- package/dist/tree.js +1 -1
- package/dist/types.d.ts +314 -20
- package/dist/validation.js +181 -44
- package/package.json +33 -5
- package/src/auth.ts +26 -2
- package/src/box-tool.ts +110 -0
- package/src/box.ts +253 -0
- package/src/choices.ts +44 -2
- package/src/classify.ts +10 -6
- package/src/computer-use-state.ts +145 -0
- package/src/computer-use-tool.ts +76 -0
- package/src/computer-use-types.ts +127 -0
- package/src/computer-use.ts +216 -0
- package/src/config.ts +454 -23
- package/src/cost.ts +42 -4
- package/src/durable.ts +298 -0
- package/src/extension.ts +79 -265
- package/src/extract.ts +228 -0
- package/src/http.ts +63 -32
- package/src/image-content.ts +77 -0
- package/src/index.ts +25 -0
- package/src/inputs.ts +603 -184
- package/src/mcp-cli.ts +44 -0
- package/src/mcp-server.ts +179 -0
- package/src/mcp-tool-definitions.ts +104 -0
- package/src/providers.ts +1398 -144
- package/src/tool-contracts.ts +785 -0
- package/src/tree.ts +1 -1
- package/src/types.ts +248 -11
- package/src/validation.ts +169 -96
package/dist/box-tool.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { defineTool, } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { renderClassifierBox, } from "./box.js";
|
|
3
|
+
import { CLASSIFIER_BOX_TOOL, CLASSIFIER_BOX_TOOL_DESCRIPTION, boxOutput, boxParameters, } from "./tool-contracts.js";
|
|
4
|
+
import { ClassifierError, userError } from "./types.js";
|
|
5
|
+
// Re-exported so existing deep imports from "./box-tool.js" keep working.
|
|
6
|
+
export { boxOutput, boxParameters };
|
|
7
|
+
export function registerBoxTool(pi) {
|
|
8
|
+
pi.registerTool(defineTool({
|
|
9
|
+
name: CLASSIFIER_BOX_TOOL,
|
|
10
|
+
label: "Box image",
|
|
11
|
+
description: CLASSIFIER_BOX_TOOL_DESCRIPTION,
|
|
12
|
+
promptSnippet: "Render or crop a local image using normalized box coordinates.",
|
|
13
|
+
promptGuidelines: [
|
|
14
|
+
"Use classifier_box_image only for local images inside cwd and normalized boxes between 0 and 1.",
|
|
15
|
+
"A returned box does not by itself confirm that the object exists.",
|
|
16
|
+
],
|
|
17
|
+
parameters: boxParameters,
|
|
18
|
+
outputSchema: boxOutput,
|
|
19
|
+
annotations: {
|
|
20
|
+
readOnlyHint: true,
|
|
21
|
+
destructiveHint: false,
|
|
22
|
+
openWorldHint: false,
|
|
23
|
+
},
|
|
24
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
25
|
+
try {
|
|
26
|
+
const result = await renderClassifierBox(params, {
|
|
27
|
+
cwd: ctx.cwd,
|
|
28
|
+
...(signal ? { signal } : {}),
|
|
29
|
+
});
|
|
30
|
+
const byteLength = Buffer.from(result.data, "base64").byteLength;
|
|
31
|
+
const details = {
|
|
32
|
+
mode: result.mode,
|
|
33
|
+
mimeType: result.mimeType,
|
|
34
|
+
width: result.width,
|
|
35
|
+
height: result.height,
|
|
36
|
+
pixelBox: result.pixelBox,
|
|
37
|
+
byteLength,
|
|
38
|
+
};
|
|
39
|
+
const box = result.pixelBox;
|
|
40
|
+
return {
|
|
41
|
+
content: [
|
|
42
|
+
{
|
|
43
|
+
type: "text",
|
|
44
|
+
text: "Rendered " +
|
|
45
|
+
result.mode +
|
|
46
|
+
" box as a " +
|
|
47
|
+
result.width +
|
|
48
|
+
"×" +
|
|
49
|
+
result.height +
|
|
50
|
+
" PNG (" +
|
|
51
|
+
byteLength +
|
|
52
|
+
" bytes). Source pixel box: left=" +
|
|
53
|
+
box.left +
|
|
54
|
+
", top=" +
|
|
55
|
+
box.top +
|
|
56
|
+
", width=" +
|
|
57
|
+
box.width +
|
|
58
|
+
", height=" +
|
|
59
|
+
box.height +
|
|
60
|
+
". A box is a localization hint, not proof that the object exists.",
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
type: "image",
|
|
64
|
+
data: result.data,
|
|
65
|
+
mimeType: result.mimeType,
|
|
66
|
+
},
|
|
67
|
+
],
|
|
68
|
+
details,
|
|
69
|
+
structuredContent: details,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
console.error("[pi-classifier] box image failed: " +
|
|
74
|
+
(error instanceof ClassifierError ? error.code : "unexpected"));
|
|
75
|
+
throw new Error(userError(error));
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
}));
|
|
79
|
+
}
|
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
|
+
}
|
package/dist/choices.js
CHANGED
|
@@ -12,6 +12,28 @@ export function choicePolicy(settings) {
|
|
|
12
12
|
return { none, batch };
|
|
13
13
|
}
|
|
14
14
|
const NONE_DESCRIPTION = "None of the other options in this question applies to the supplied state. Select this only when every listed real option is unsuitable.";
|
|
15
|
+
/**
|
|
16
|
+
* Each provider call returns its own web evidence. `searchResult` indexes that call's array,
|
|
17
|
+
* so spans must be rebased onto the accumulated evidence assembled by this orchestrator.
|
|
18
|
+
*/
|
|
19
|
+
function remapGroundedAnswers(answers, offset) {
|
|
20
|
+
if (offset === 0)
|
|
21
|
+
return answers;
|
|
22
|
+
const mapped = Object.create(null);
|
|
23
|
+
for (const [id, answer] of Object.entries(answers)) {
|
|
24
|
+
if (answer.type !== "locate" || !answer.spans.some((span) => span.searchResult !== undefined)) {
|
|
25
|
+
mapped[id] = answer;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
mapped[id] = {
|
|
29
|
+
...answer,
|
|
30
|
+
spans: answer.spans.map((span) => span.searchResult === undefined
|
|
31
|
+
? span
|
|
32
|
+
: { ...span, searchResult: span.searchResult + offset }),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
return mapped;
|
|
36
|
+
}
|
|
15
37
|
/** Only this operation owns batching. Transport, images, credentials and routes stay with the caller. */
|
|
16
38
|
export async function executeChoices(input, route, policy, call, signal) {
|
|
17
39
|
const plans = new Map();
|
|
@@ -42,6 +64,7 @@ export async function executeChoices(input, route, policy, call, signal) {
|
|
|
42
64
|
let last;
|
|
43
65
|
let usage;
|
|
44
66
|
let cost;
|
|
67
|
+
let webGrounding;
|
|
45
68
|
while (plans.size > 0) {
|
|
46
69
|
if (signal?.aborted)
|
|
47
70
|
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
@@ -79,9 +102,18 @@ export async function executeChoices(input, route, policy, call, signal) {
|
|
|
79
102
|
}
|
|
80
103
|
usage = calls === 0 ? result.usage : sumUsage(usage, result.usage);
|
|
81
104
|
cost = cost === undefined ? result.cost : sumCost(cost, result.cost);
|
|
105
|
+
const callAnswers = remapGroundedAnswers(result.answers, webGrounding?.searchResults.length ?? 0);
|
|
106
|
+
if (result.webGrounding !== undefined) {
|
|
107
|
+
webGrounding ??= { searchResults: [] };
|
|
108
|
+
webGrounding.searchResults.push(...result.webGrounding.searchResults);
|
|
109
|
+
if (result.webGrounding.fetchedResults?.length) {
|
|
110
|
+
webGrounding.fetchedResults ??= [];
|
|
111
|
+
webGrounding.fetchedResults.push(...result.webGrounding.fetchedResults);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
82
114
|
calls++;
|
|
83
115
|
last = result;
|
|
84
|
-
for (const [id, answer] of Object.entries(
|
|
116
|
+
for (const [id, answer] of Object.entries(callAnswers)) {
|
|
85
117
|
const plan = plans.get(id);
|
|
86
118
|
if (!plan) {
|
|
87
119
|
answers[id] = answer;
|
|
@@ -125,6 +157,8 @@ export async function executeChoices(input, route, policy, call, signal) {
|
|
|
125
157
|
};
|
|
126
158
|
if (usage !== undefined)
|
|
127
159
|
combined.usage = usage;
|
|
160
|
+
if (webGrounding !== undefined)
|
|
161
|
+
combined.webGrounding = webGrounding;
|
|
128
162
|
if (calls === 1 && last.requestId !== undefined)
|
|
129
163
|
combined.requestId = last.requestId;
|
|
130
164
|
return combined;
|
package/dist/classify.d.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
+
import { type CredentialSource } from "./auth.js";
|
|
2
|
+
import { type MemoryImage } from "./inputs.js";
|
|
1
3
|
import { type ClassifierComparisonResult, type ClassifierResult, type ClassifierSettings } from "./types.js";
|
|
2
4
|
export type ClassifyOptions = {
|
|
3
5
|
settings: ClassifierSettings;
|
|
4
6
|
cwd: string;
|
|
5
7
|
signal?: AbortSignal;
|
|
8
|
+
/** Credential origin. Desktop keeps the default; the native Durable factory passes "explicit". */
|
|
9
|
+
credentialSource?: CredentialSource;
|
|
10
|
+
/** Trusted programmatic ingress; all bytes still pass normal image validation. */
|
|
11
|
+
memoryImages?: readonly MemoryImage[];
|
|
6
12
|
};
|
|
7
13
|
/** Default plus explicitly configured, selective fallback. Never retries a route. */
|
|
8
14
|
export declare function classify(params: unknown, options: ClassifyOptions): Promise<ClassifierResult>;
|
package/dist/classify.js
CHANGED
|
@@ -18,9 +18,9 @@ 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
|
-
const key = resolveApiKey(route);
|
|
23
|
+
const key = resolveApiKey(route, options.credentialSource ?? "pi-store");
|
|
24
24
|
const result = await executeChoices(prepared, route, choicePolicy(options.settings), (questions) => classifyWithProvider(route, { ...prepared, questions }, key, options.signal), options.signal);
|
|
25
25
|
if (Buffer.byteLength(JSON.stringify(result, null, 2)) > 40 * 1024)
|
|
26
26
|
throw new ClassifierError("response", "Classifier result exceeds the 40 KiB tool output limit. Ask fewer questions.");
|
|
@@ -44,7 +44,7 @@ export async function classify(params, options) {
|
|
|
44
44
|
let lastError;
|
|
45
45
|
for (const candidate of candidates) {
|
|
46
46
|
checkCancelled(options.signal);
|
|
47
|
-
const route = resolveModel(options.settings, candidate);
|
|
47
|
+
const route = resolveModel(options.settings, candidate, options.credentialSource ?? "pi-store");
|
|
48
48
|
const key = routeKey(route);
|
|
49
49
|
if (seen.has(key))
|
|
50
50
|
continue;
|
|
@@ -85,7 +85,7 @@ export async function compareClassifiers(params, options) {
|
|
|
85
85
|
const start = performance.now();
|
|
86
86
|
let selected = candidate;
|
|
87
87
|
try {
|
|
88
|
-
const route = resolveModel(options.settings, candidate);
|
|
88
|
+
const route = resolveModel(options.settings, candidate, options.credentialSource ?? "pi-store");
|
|
89
89
|
selected = routePair(route);
|
|
90
90
|
const key = routeKey(route);
|
|
91
91
|
if (seen.has(key))
|
|
@@ -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[];
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { ClassifierError, isRecord } from "./types.js";
|
|
2
|
+
export const KEY_NAMES = ["return", "tab", "escape", "up", "down", "left", "right", "space", "home", "end", "pageup", "pagedown"];
|
|
3
|
+
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;
|
|
4
|
+
const EDITABLE = /^(AXTextField|AXTextArea|AXComboBox|textbox|combobox|text field|text area)$/i;
|
|
5
|
+
const CLICKABLE = /^(AXButton|AXCheckBox|AXRadioButton|AXMenuItem|AXLink|AXPopUpButton|AXTab|AXDisclosureTriangle|AXRow|button|checkbox|radio|menuitem|link|tab|switch)$/i;
|
|
6
|
+
export function validateComputerParams(params) {
|
|
7
|
+
const invalid = () => { throw new ClassifierError("input", "Invalid computer-use goal, exact target, controls, values, expectations or limits."); };
|
|
8
|
+
if (!isRecord(params) || typeof params.goal !== "string" || !params.goal.trim() || params.goal.length > 4096 ||
|
|
9
|
+
!isRecord(params.target) || !Number.isSafeInteger(params.target.pid) || params.target.pid < 1 ||
|
|
10
|
+
!Number.isSafeInteger(params.target.window_id) || params.target.window_id < 0 ||
|
|
11
|
+
!Array.isArray(params.controls) || params.controls.length < 1 || params.controls.length > 120)
|
|
12
|
+
invalid();
|
|
13
|
+
const ids = new Set();
|
|
14
|
+
for (const c of params.controls) {
|
|
15
|
+
if (!isRecord(c) || typeof c.id !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(c.id) || ids.has(c.id) ||
|
|
16
|
+
!isRecord(c.selector) || typeof c.selector.role !== "string" || !c.selector.role || c.selector.role.length > 128 ||
|
|
17
|
+
typeof c.selector.label !== "string" || !c.selector.label.trim() || c.selector.label.length > 512 ||
|
|
18
|
+
!["click", "fill", "key"].includes(c.operation))
|
|
19
|
+
invalid();
|
|
20
|
+
ids.add(c.id);
|
|
21
|
+
if (c.operation === "fill" && (typeof c.valueKey !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(c.valueKey)))
|
|
22
|
+
invalid();
|
|
23
|
+
if (c.operation === "key" && !KEY_NAMES.includes(c.key))
|
|
24
|
+
invalid();
|
|
25
|
+
if (SECRET.test(c.selector.role + " " + c.selector.label))
|
|
26
|
+
throw new ClassifierError("input", "Credential and secure controls must remain with the user, outside the classifier loop.");
|
|
27
|
+
}
|
|
28
|
+
if (params.values !== undefined && (!isRecord(params.values) || Object.keys(params.values).length > 64 ||
|
|
29
|
+
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))))
|
|
30
|
+
invalid();
|
|
31
|
+
if (params.expect !== undefined && (!Array.isArray(params.expect) || params.expect.length < 1 || params.expect.length > 8))
|
|
32
|
+
invalid();
|
|
33
|
+
for (const p of params.expect ?? []) {
|
|
34
|
+
const e = p?.element;
|
|
35
|
+
if (!isRecord(e) || !isRecord(e.selector) || typeof e.selector.role !== "string" || !e.selector.role ||
|
|
36
|
+
typeof e.selector.label_contains !== "string" || !e.selector.label_contains ||
|
|
37
|
+
e.selector.role.length > 128 || e.selector.label_contains.length > 512 ||
|
|
38
|
+
(e.exists !== undefined && e.exists !== true) ||
|
|
39
|
+
(e.value_equals !== undefined && (typeof e.value_equals !== "string" || e.value_equals.length > 4096)) ||
|
|
40
|
+
(e.enabled !== undefined && typeof e.enabled !== "boolean") ||
|
|
41
|
+
(e.selected !== undefined && typeof e.selected !== "boolean") ||
|
|
42
|
+
[e.exists, e.value_equals, e.enabled, e.selected].every((v) => v === undefined))
|
|
43
|
+
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)))
|
|
50
|
+
invalid();
|
|
51
|
+
}
|
|
52
|
+
export function driverState(reply) {
|
|
53
|
+
if (reply.isError)
|
|
54
|
+
throw new ClassifierError("driver", "Driver call failed or was blocked. Inspect the target and permissions before resuming.");
|
|
55
|
+
if (!isRecord(reply.structuredContent))
|
|
56
|
+
throw new ClassifierError("driver", "Driver returned no structured state; no input was attempted from that response.");
|
|
57
|
+
return reply.structuredContent;
|
|
58
|
+
}
|
|
59
|
+
export function observation(reply, target) {
|
|
60
|
+
const state = driverState(reply);
|
|
61
|
+
if (state.pid !== target.pid || state.window_id !== target.window_id || !Array.isArray(state.elements))
|
|
62
|
+
throw new ClassifierError("driver", "Driver observation did not establish the exact requested window and element list.");
|
|
63
|
+
const elements = [];
|
|
64
|
+
const menuIndices = new Set();
|
|
65
|
+
for (const raw of state.elements) {
|
|
66
|
+
if (!isRecord(raw))
|
|
67
|
+
continue;
|
|
68
|
+
if (raw.role === "AXMenuBar" || (typeof raw.parent_index === "number" && menuIndices.has(raw.parent_index))) {
|
|
69
|
+
if (typeof raw.element_index === "number")
|
|
70
|
+
menuIndices.add(raw.element_index);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
for (const raw of state.elements.slice(0, 200)) {
|
|
74
|
+
if (isRecord(raw) && typeof raw.element_index === "number" && menuIndices.has(raw.element_index))
|
|
75
|
+
continue;
|
|
76
|
+
if (!isRecord(raw) || typeof raw.role !== "string" || SECRET.test(raw.role + " " + String(raw.label ?? "")))
|
|
77
|
+
continue;
|
|
78
|
+
const e = {
|
|
79
|
+
role: raw.role.slice(0, 128), label: typeof raw.label === "string" ? raw.label.slice(0, 1024) : "",
|
|
80
|
+
actions: Array.isArray(raw.actions) ? raw.actions.filter((v) => typeof v === "string").slice(0, 20) : [],
|
|
81
|
+
index: typeof raw.element_index === "number" ? raw.element_index : -1,
|
|
82
|
+
};
|
|
83
|
+
if (typeof raw.value === "string")
|
|
84
|
+
e.value = raw.value.slice(0, 4096);
|
|
85
|
+
if (typeof raw.enabled === "boolean")
|
|
86
|
+
e.enabled = raw.enabled;
|
|
87
|
+
if (typeof raw.selected === "boolean")
|
|
88
|
+
e.selected = raw.selected;
|
|
89
|
+
if (typeof raw.element_token === "string" && /^s[0-9a-f]{8}:[0-9]+$/.test(raw.element_token))
|
|
90
|
+
e.token = raw.element_token;
|
|
91
|
+
elements.push(e);
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
elements, truncated: state.truncated === true || state.elements.length > 200,
|
|
95
|
+
degraded: state.degraded === true || Boolean(state.degraded_reason),
|
|
96
|
+
title: typeof state.window_title === "string" ? state.window_title.slice(0, 512) : "",
|
|
97
|
+
// Driver indexes actionable rows only; retain passive state without the global menu subtree.
|
|
98
|
+
text: windowText(state.tree_markdown),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** Root order changes when an app backgrounds; select the window branch, not a prefix. */
|
|
102
|
+
function windowText(markdown) {
|
|
103
|
+
if (typeof markdown !== "string")
|
|
104
|
+
return "";
|
|
105
|
+
let inWindow = false;
|
|
106
|
+
const lines = [];
|
|
107
|
+
for (const line of markdown.split("\n")) {
|
|
108
|
+
if (/^- /.test(line))
|
|
109
|
+
inWindow = /^- (?:\[\d+\] )?AXWindow\b/.test(line);
|
|
110
|
+
if (inWindow && !SECRET.test(line))
|
|
111
|
+
lines.push(line);
|
|
112
|
+
}
|
|
113
|
+
return lines.join("\n").slice(0, 16000);
|
|
114
|
+
}
|
|
115
|
+
export function candidates(params, state) {
|
|
116
|
+
// Truncated trees cannot establish selector uniqueness; hand back instead of guessing.
|
|
117
|
+
if (state.truncated || state.degraded)
|
|
118
|
+
return [];
|
|
119
|
+
const result = [];
|
|
120
|
+
for (const control of params.controls) {
|
|
121
|
+
const matches = state.elements.filter((e) => e.role === control.selector.role && e.label === control.selector.label);
|
|
122
|
+
if (matches.length !== 1)
|
|
123
|
+
continue;
|
|
124
|
+
const element = matches[0];
|
|
125
|
+
if (!element.token || element.enabled === false || !compatible(control, element))
|
|
126
|
+
continue;
|
|
127
|
+
const missingValue = control.operation === "fill" && !Object.hasOwn(params.values ?? {}, control.valueKey);
|
|
128
|
+
if (control.operation === "fill" && !missingValue && element.value === params.values[control.valueKey])
|
|
129
|
+
continue;
|
|
130
|
+
result.push({
|
|
131
|
+
id: control.id, control, element, missingValue,
|
|
132
|
+
description: `${control.operation} ${element.role} ${JSON.stringify(element.label)}` +
|
|
133
|
+
(control.operation === "fill" ? ` using supplied value ${control.valueKey}${missingValue ? " (MISSING: hand back for text)" : ""}` : control.operation === "key" ? ` ${control.key}` : ""),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
function compatible(control, element) {
|
|
139
|
+
if (control.operation === "fill")
|
|
140
|
+
return EDITABLE.test(element.role);
|
|
141
|
+
if (control.operation === "key")
|
|
142
|
+
return EDITABLE.test(element.role) || CLICKABLE.test(element.role);
|
|
143
|
+
return CLICKABLE.test(element.role) || element.actions.some((a) => /^(AXPress|press|invoke)$/i.test(a));
|
|
144
|
+
}
|
|
145
|
+
export function modelElements(state) {
|
|
146
|
+
return state.elements.map(({ token: _token, actions: _actions, index: _index, ...e }) => e);
|
|
147
|
+
}
|
|
148
|
+
export function captureImage(reply) {
|
|
149
|
+
const blocks = (reply.content ?? []).filter((b) => isRecord(b) && b.type === "image");
|
|
150
|
+
if (blocks.length !== 1)
|
|
151
|
+
throw new ClassifierError("driver", "Expected one window screenshot. No image was silently omitted.");
|
|
152
|
+
const block = blocks[0];
|
|
153
|
+
if (!isRecord(block) || !["image/png", "image/jpeg", "image/webp"].includes(String(block.mimeType)) ||
|
|
154
|
+
typeof block.data !== "string" || block.data.length > 6990508 || (block.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(block.data)))
|
|
155
|
+
throw new ClassifierError("input", "Driver screenshot exceeds image limits or is not canonical base64.");
|
|
156
|
+
const bytes = Buffer.from(block.data, "base64");
|
|
157
|
+
if (bytes.toString("base64") !== block.data)
|
|
158
|
+
throw new ClassifierError("input", "Driver image encoding was not canonical base64.");
|
|
159
|
+
return [{ bytes, mimeType: block.mimeType }];
|
|
160
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
export declare const computerUseParameters: Type.TObject<{
|
|
4
|
+
goal: Type.TString;
|
|
5
|
+
target: Type.TObject<{
|
|
6
|
+
pid: Type.TInteger;
|
|
7
|
+
window_id: Type.TInteger;
|
|
8
|
+
}>;
|
|
9
|
+
controls: Type.TArray<Type.TUnion<[Type.TObject<{
|
|
10
|
+
id: Type.TString;
|
|
11
|
+
selector: Type.TObject<{
|
|
12
|
+
role: Type.TString;
|
|
13
|
+
label: Type.TString;
|
|
14
|
+
}>;
|
|
15
|
+
operation: Type.TLiteral<"click">;
|
|
16
|
+
}>, Type.TObject<{
|
|
17
|
+
id: Type.TString;
|
|
18
|
+
selector: Type.TObject<{
|
|
19
|
+
role: Type.TString;
|
|
20
|
+
label: Type.TString;
|
|
21
|
+
}>;
|
|
22
|
+
operation: Type.TLiteral<"fill">;
|
|
23
|
+
valueKey: Type.TString;
|
|
24
|
+
}>, Type.TObject<{
|
|
25
|
+
id: Type.TString;
|
|
26
|
+
selector: Type.TObject<{
|
|
27
|
+
role: Type.TString;
|
|
28
|
+
label: Type.TString;
|
|
29
|
+
}>;
|
|
30
|
+
operation: Type.TLiteral<"key">;
|
|
31
|
+
key: Type.TUnion<Type.TLiteral<string>[]>;
|
|
32
|
+
}>]>>;
|
|
33
|
+
values: Type.TOptional<Type.TRecord<"^.*$", Type.TString>>;
|
|
34
|
+
expect: Type.TOptional<Type.TArray<Type.TObject<{
|
|
35
|
+
element: Type.TObject<{
|
|
36
|
+
selector: Type.TObject<{
|
|
37
|
+
role: Type.TString;
|
|
38
|
+
label_contains: Type.TString;
|
|
39
|
+
}>;
|
|
40
|
+
exists: Type.TOptional<Type.TLiteral<true>>;
|
|
41
|
+
value_equals: Type.TOptional<Type.TString>;
|
|
42
|
+
enabled: Type.TOptional<Type.TBoolean>;
|
|
43
|
+
selected: Type.TOptional<Type.TBoolean>;
|
|
44
|
+
}>;
|
|
45
|
+
}>>>;
|
|
46
|
+
context: Type.TOptional<Type.TString>;
|
|
47
|
+
previousActions: Type.TOptional<Type.TArray<Type.TString>>;
|
|
48
|
+
maxActions: Type.TOptional<Type.TInteger>;
|
|
49
|
+
timeoutMs: Type.TOptional<Type.TInteger>;
|
|
50
|
+
deliveryMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"background">, Type.TLiteral<"foreground">]>>;
|
|
51
|
+
}>;
|
|
52
|
+
export declare function registerComputerUseTool(pi: ExtensionAPI): void;
|