@howaboua/pi-durable-view-image 0.9.1 → 0.11.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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  `createViewImageTool(options)` creates a Durable `view_image` registration. Install it in the ordinary tool registry. Code and Notebook discover the same registration.
4
4
 
5
5
  ```sh
6
- npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.9.1/howaboua-pi-durable-view-image-0.9.1.tgz
6
+ npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.11.0/howaboua-pi-durable-view-image-0.11.0.tgz
7
7
  ```
8
8
 
9
9
  ```ts
@@ -0,0 +1,5 @@
1
+ import { type ComponentInstance, type ComponentRequest } from "@howaboua/pi-durable-components";
2
+ import { createViewImageTool, type ViewImageOptions } from "./index.ts";
3
+ /** Grants native byte codecs and the host's exact Models collection. */
4
+ export declare const viewImageOptions: import("@howaboua/pi-durable-components").ComponentCapability<ViewImageOptions>;
5
+ export declare function createComponent(request: ComponentRequest): ComponentInstance<ReturnType<typeof createViewImageTool>>;
@@ -0,0 +1,275 @@
1
+ // packages/view-image/src/activation.ts
2
+ import { defineExtension } from "@earendil-works/pi-durable";
3
+ import {
4
+ defineCapability,
5
+ isCapabilityObject,
6
+ modelsCapability,
7
+ nodeExecutionCapability
8
+ } from "@howaboua/pi-durable-components";
9
+ import { Type as Type2 } from "typebox";
10
+ import { Check } from "typebox/value";
11
+
12
+ // packages/view-image/src/index.ts
13
+ import {
14
+ defineTool
15
+ } from "@earendil-works/pi-durable";
16
+ import {
17
+ getOrThrow
18
+ } from "@earendil-works/pi-durable/env";
19
+ import { Type } from "typebox";
20
+
21
+ // packages/view-image/src/codec.ts
22
+ import { createHash } from "node:crypto";
23
+ import { Transformer } from "@napi-rs/image";
24
+ import sharp from "sharp";
25
+ var CACHE_ENTRIES = 32;
26
+ var CACHE_BYTES = 64 * 1024 * 1024;
27
+ function createImageCodec() {
28
+ const cache = new Map;
29
+ let cacheBytes = 0;
30
+ return async (bytes, path, signal) => {
31
+ signal?.throwIfAborted();
32
+ const digest = createHash("sha1").update(bytes).digest("hex");
33
+ const cached = cache.get(digest);
34
+ if (cached) {
35
+ cache.delete(digest);
36
+ cache.set(digest, cached);
37
+ return { ...cached.image };
38
+ }
39
+ const input = Buffer.from(bytes);
40
+ const format = detectFormat(input);
41
+ if (!format)
42
+ throw new Error(`unable to process image at \`${path}\`: unsupported image format`);
43
+ let encoded;
44
+ try {
45
+ if (format === "gif") {
46
+ encoded = await decodeGif(input, signal);
47
+ } else {
48
+ await new Transformer(input).metadata(false, signal);
49
+ encoded = input;
50
+ }
51
+ signal?.throwIfAborted();
52
+ } catch (cause) {
53
+ signal?.throwIfAborted();
54
+ throw new Error(`unable to process image at \`${path}\`: failed to decode image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
55
+ }
56
+ const image = {
57
+ type: "image",
58
+ data: encoded.toString("base64"),
59
+ mimeType: format === "gif" ? "image/png" : `image/${format}`,
60
+ detail: "original"
61
+ };
62
+ if (encoded.byteLength <= CACHE_BYTES) {
63
+ const previous = cache.get(digest);
64
+ if (previous)
65
+ cacheBytes -= previous.size;
66
+ cache.delete(digest);
67
+ cache.set(digest, { image: { ...image }, size: encoded.byteLength });
68
+ cacheBytes += encoded.byteLength;
69
+ while (cache.size > CACHE_ENTRIES || cacheBytes > CACHE_BYTES) {
70
+ const oldest = cache.entries().next().value;
71
+ if (!oldest)
72
+ break;
73
+ cache.delete(oldest[0]);
74
+ cacheBytes -= oldest[1].size;
75
+ }
76
+ }
77
+ return image;
78
+ };
79
+ }
80
+ async function decodeGif(input, signal) {
81
+ const decoder = sharp(input, {
82
+ animated: false,
83
+ failOn: "error",
84
+ limitInputPixels: false
85
+ });
86
+ const abort = () => {
87
+ decoder.destroy();
88
+ };
89
+ signal?.addEventListener("abort", abort, { once: true });
90
+ try {
91
+ const { data, info } = await decoder.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
92
+ signal?.throwIfAborted();
93
+ return await sharp(data, {
94
+ raw: { width: info.width, height: info.height, channels: info.channels }
95
+ }).png().toBuffer();
96
+ } finally {
97
+ signal?.removeEventListener("abort", abort);
98
+ decoder.destroy();
99
+ }
100
+ }
101
+ function detectFormat(bytes) {
102
+ if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
103
+ return "png";
104
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255)
105
+ return "jpeg";
106
+ if (["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString("ascii")))
107
+ return "gif";
108
+ if (bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP")
109
+ return "webp";
110
+ return;
111
+ }
112
+
113
+ // packages/view-image/src/description.ts
114
+ var DESCRIPTION_PROMPT = "Describe this image in detail. Output only the image description, no other commentary";
115
+ async function describeImage(image, models, caller, configured, context) {
116
+ const ref = configured ?? {
117
+ provider: caller.provider,
118
+ modelId: "gpt-6-luna"
119
+ };
120
+ const model = models.getModel(ref.provider, ref.modelId);
121
+ if (!model)
122
+ throw new Error(`view_image description model not found: ${ref.provider}/${ref.modelId}`);
123
+ if (!model.input.includes("image"))
124
+ throw new Error(`view_image description model does not support image inputs: ${ref.provider}/${ref.modelId}`);
125
+ context.abortSignal?.throwIfAborted();
126
+ const reply = await models.completeSimple(model, {
127
+ systemPrompt: DESCRIPTION_PROMPT,
128
+ messages: [
129
+ {
130
+ role: "user",
131
+ content: [{ type: "text", text: "Describe the image" }, image],
132
+ timestamp: Date.now()
133
+ }
134
+ ]
135
+ }, {
136
+ reasoning: "low",
137
+ ...context.abortSignal ? { signal: context.abortSignal } : {},
138
+ onPayload: prepareDescriptionPayload
139
+ });
140
+ context.abortSignal?.throwIfAborted();
141
+ if (reply.stopReason === "error" || reply.stopReason === "aborted") {
142
+ throw new Error(`view_image description failed: ${reply.errorMessage ?? reply.stopReason}`);
143
+ }
144
+ const description = reply.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim();
145
+ if (!description)
146
+ throw new Error("view_image description returned no text");
147
+ return { description, usage: reply.usage };
148
+ }
149
+ function prepareDescriptionPayload(payload, model) {
150
+ if (model.api !== "openai-responses" && model.api !== "openai-codex-responses")
151
+ return;
152
+ if (!payload || typeof payload !== "object")
153
+ throw new Error("view_image description expected a Responses payload");
154
+ const body = payload;
155
+ const reasoning = body["reasoning"];
156
+ const text = body["text"];
157
+ return {
158
+ ...body,
159
+ text: {
160
+ ...text && typeof text === "object" ? text : {},
161
+ verbosity: "low"
162
+ },
163
+ ...reasoning && typeof reasoning === "object" ? { reasoning: { ...reasoning, summary: "auto" } } : {}
164
+ };
165
+ }
166
+
167
+ // packages/view-image/src/index.ts
168
+ var schema = Type.Object({
169
+ path: Type.String(),
170
+ detail: Type.Optional(Type.Literal("original"))
171
+ });
172
+ function createViewImageTool(options) {
173
+ const loadImage = createImageCodec();
174
+ return defineTool({
175
+ name: "view_image",
176
+ description: "View image",
177
+ parameters: schema,
178
+ replay: options.describeForTextModels ? "unsafe" : "safe",
179
+ prepareArguments,
180
+ async execute(args, api, context) {
181
+ context.abortSignal?.throwIfAborted();
182
+ const agent = await api.agent(context);
183
+ if (!agent.model)
184
+ throw new Error("view_image requires a conversation model");
185
+ const model = options.models.getModel(agent.model.provider, agent.model.modelId);
186
+ if (!model)
187
+ throw new Error(`view_image model not found: ${agent.model.provider}/${agent.model.modelId}`);
188
+ const vision = model.input.includes("image");
189
+ if (!vision && !options.describeForTextModels) {
190
+ throw new Error("view_image is not allowed because you do not support image inputs");
191
+ }
192
+ if (!api.env)
193
+ throw new Error("view_image requires an execution environment");
194
+ const path = await locateImage(api.env, args.path, context);
195
+ let bytes;
196
+ try {
197
+ bytes = getOrThrow(await api.env.readBinaryFile(path, context));
198
+ } catch (cause) {
199
+ context.abortSignal?.throwIfAborted();
200
+ throw new Error(`unable to read image at \`${path}\`: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
201
+ }
202
+ const image = await loadImage(bytes, path, context.abortSignal);
203
+ if (vision)
204
+ return { output: [image], details: { viewImage: true } };
205
+ const { description, usage } = await describeImage(image, options.models, agent.model, options.descriptionModel, context);
206
+ return {
207
+ output: [{ type: "text", text: description }],
208
+ details: {
209
+ viewImageDescription: { image, path: args.path, description }
210
+ },
211
+ usage
212
+ };
213
+ }
214
+ });
215
+ }
216
+ function prepareArguments(args) {
217
+ if (!args || typeof args !== "object")
218
+ throw new Error("view_image requires a string 'path' parameter");
219
+ const record = args;
220
+ const path = "path" in record ? record["path"] : ("file_path" in record) ? record["file_path"] : record["image_path"];
221
+ if (typeof path !== "string")
222
+ throw new Error("view_image requires a string 'path' parameter");
223
+ const detail = record["detail"];
224
+ if (detail !== undefined && detail !== null && typeof detail !== "string")
225
+ throw new Error("view_image.detail must be a string when provided");
226
+ if (typeof detail === "string" && detail !== "original")
227
+ throw new Error(`view_image.detail only supports \`original\`, got \`${detail}\``);
228
+ return {
229
+ path: path.startsWith("@") ? path.slice(1) : path,
230
+ ...detail === "original" ? { detail } : {}
231
+ };
232
+ }
233
+ async function locateImage(env, input, context) {
234
+ const path = getOrThrow(await env.absolutePath(input, context));
235
+ let info;
236
+ try {
237
+ info = getOrThrow(await env.fileInfo(path, context));
238
+ if (info.kind === "symlink")
239
+ info = getOrThrow(await env.fileInfo(getOrThrow(await env.canonicalPath(path, context)), context));
240
+ } catch (cause) {
241
+ context.abortSignal?.throwIfAborted();
242
+ throw new Error(`unable to locate image at \`${path}\`: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
243
+ }
244
+ if (info.kind !== "file")
245
+ throw new Error(`image path \`${path}\` is not a file`);
246
+ return path;
247
+ }
248
+
249
+ // packages/view-image/src/activation.ts
250
+ var viewImageOptions = defineCapability("howaboua.view-image.options.v1", (value) => isCapabilityObject(value) && isCapabilityObject(value["models"]) && typeof value["models"]["getModel"] === "function");
251
+ var configuration = Type2.Object({
252
+ describeForTextModels: Type2.Optional(Type2.Boolean()),
253
+ descriptionModel: Type2.Optional(Type2.Object({ provider: Type2.String(), modelId: Type2.String() }, { additionalProperties: false }))
254
+ }, { additionalProperties: false });
255
+ function baseline(request) {
256
+ if (!Check(configuration, request.configuration))
257
+ throw new Error("Invalid view-image configuration");
258
+ request.capabilities.get(nodeExecutionCapability);
259
+ return {
260
+ ...request.configuration,
261
+ models: request.capabilities.get(modelsCapability)
262
+ };
263
+ }
264
+ function createComponent(request) {
265
+ const api = createViewImageTool(request.capabilities.has(viewImageOptions.id) ? request.capabilities.get(viewImageOptions) : baseline(request));
266
+ return {
267
+ extensions: [defineExtension({ name: "view-image", tools: [api] })],
268
+ api,
269
+ retention: "idle"
270
+ };
271
+ }
272
+ export {
273
+ createComponent,
274
+ viewImageOptions
275
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-durable-view-image",
3
- "version": "0.9.1",
3
+ "version": "0.11.0",
4
4
  "description": "Image inspection and description for Pi Durable",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,6 +23,10 @@
23
23
  ".": {
24
24
  "types": "./dist/index.d.ts",
25
25
  "import": "./dist/index.js"
26
+ },
27
+ "./component": {
28
+ "types": "./dist/activation.d.ts",
29
+ "import": "./dist/activation.js"
26
30
  }
27
31
  },
28
32
  "files": [
@@ -35,15 +39,32 @@
35
39
  "dependencies": {
36
40
  "@napi-rs/image": "1.15.0",
37
41
  "sharp": "0.35.5",
38
- "typebox": "1.3.27"
42
+ "typebox": "1.3.27",
43
+ "@howaboua/pi-durable-components": "0.11.0"
39
44
  },
40
45
  "peerDependencies": {
41
- "@earendil-works/chord": "1.4.0",
42
- "@earendil-works/pi-ai": "1.4.0",
43
- "@earendil-works/pi-durable": "1.4.0",
44
- "@modelcontextprotocol/sdk": "1.25.2"
46
+ "@earendil-works/chord": "1.5.0",
47
+ "@earendil-works/pi-ai": "1.5.0",
48
+ "@earendil-works/pi-durable": "1.5.0",
49
+ "@modelcontextprotocol/sdk": ">=1.25.2 <2"
45
50
  },
46
51
  "publishConfig": {
47
52
  "access": "public"
53
+ },
54
+ "durable": {
55
+ "schemaVersion": 1,
56
+ "kind": "extension",
57
+ "entry": "./component",
58
+ "runtimes": [
59
+ "node"
60
+ ],
61
+ "requires": [
62
+ "durable.models.v1",
63
+ "durable.node-execution.v1"
64
+ ],
65
+ "permissions": [
66
+ "filesystem",
67
+ "models"
68
+ ]
48
69
  }
49
70
  }