@howaboua/pi-durable-view-image 0.0.0-stage → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Igor Warzocha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,244 @@
1
+ Source alignment inspected at Pi Stuff revision 7f3295e67a8e6146b2a6922b56a06fa4db5c3a32.
2
+ See docs/parity for carried changes and explicit native-environment exclusions.
3
+
4
+ View image for Pi Durable
5
+
6
+ Argument repair and description behavior are adapted from pi-codex-conversion,
7
+ revision b2006db9def12c373ae48e70044d30f7d6b7e34f, under the MIT License.
8
+
9
+ Original-mode codec behavior and cache policy follow OpenAI Codex's
10
+ codex-utils-image, upstream revision b545c94041017d000e2c8b2f6272705d21b85dfb,
11
+ under the Apache License 2.0. The implementation here uses TypeScript with
12
+ @napi-rs/image for Rust image decoding and sharp for GIF conversion.
13
+ No upstream native executable is shipped.
14
+
15
+ The sharp dependency is separately distributed under Apache-2.0. Its bundled
16
+ libvips and codec dependencies retain their own third-party license notices.
17
+ The @napi-rs/image dependency is separately distributed under MIT and retains
18
+ its own third-party license notices.
19
+
20
+ MIT License
21
+
22
+ Copyright (c) 2026 Igor Warzocha
23
+
24
+ Permission is hereby granted, free of charge, to any person obtaining a copy
25
+ of this software and associated documentation files (the "Software"), to deal
26
+ in the Software without restriction, including without limitation the rights
27
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
28
+ copies of the Software, and to permit persons to whom the Software is
29
+ furnished to do so, subject to the following conditions:
30
+
31
+ The above copyright notice and this permission notice shall be included in all
32
+ copies or substantial portions of the Software.
33
+
34
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
40
+ SOFTWARE.
41
+
42
+
43
+
44
+ Apache License
45
+ Version 2.0, January 2004
46
+ http://www.apache.org/licenses/
47
+
48
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
49
+
50
+ 1. Definitions.
51
+
52
+ "License" shall mean the terms and conditions for use, reproduction,
53
+ and distribution as defined by Sections 1 through 9 of this document.
54
+
55
+ "Licensor" shall mean the copyright owner or entity authorized by
56
+ the copyright owner that is granting the License.
57
+
58
+ "Legal Entity" shall mean the union of the acting entity and all
59
+ other entities that control, are controlled by, or are under common
60
+ control with that entity. For the purposes of this definition,
61
+ "control" means (i) the power, direct or indirect, to cause the
62
+ direction or management of such entity, whether by contract or
63
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
64
+ outstanding shares, or (iii) beneficial ownership of such entity.
65
+
66
+ "You" (or "Your") shall mean an individual or Legal Entity
67
+ exercising permissions granted by this License.
68
+
69
+ "Source" form shall mean the preferred form for making modifications,
70
+ including but not limited to software source code, documentation
71
+ source, and configuration files.
72
+
73
+ "Object" form shall mean any form resulting from mechanical
74
+ transformation or translation of a Source form, including but
75
+ not limited to compiled object code, generated documentation,
76
+ and conversions to other media types.
77
+
78
+ "Work" shall mean the work of authorship, whether in Source or
79
+ Object form, made available under the License, as indicated by a
80
+ copyright notice that is included in or attached to the work
81
+ (an example is provided in the Appendix below).
82
+
83
+ "Derivative Works" shall mean any work, whether in Source or Object
84
+ form, that is based on (or derived from) the Work and for which the
85
+ editorial revisions, annotations, elaborations, or other modifications
86
+ represent, as a whole, an original work of authorship. For the purposes
87
+ of this License, Derivative Works shall not include works that remain
88
+ separable from, or merely link (or bind by name) to the interfaces of,
89
+ the Work and Derivative Works thereof.
90
+
91
+ "Contribution" shall mean any work of authorship, including
92
+ the original version of the Work and any modifications or additions
93
+ to that Work or Derivative Works thereof, that is intentionally
94
+ submitted to Licensor for inclusion in the Work by the copyright owner
95
+ or by an individual or Legal Entity authorized to submit on behalf of
96
+ the copyright owner. For the purposes of this definition, "submitted"
97
+ means any form of electronic, verbal, or written communication sent
98
+ to the Licensor or its representatives, including but not limited to
99
+ communication on electronic mailing lists, source code control systems,
100
+ and issue tracking systems that are managed by, or on behalf of, the
101
+ Licensor for the purpose of discussing and improving the Work, but
102
+ excluding communication that is conspicuously marked or otherwise
103
+ designated in writing by the copyright owner as "Not a Contribution."
104
+
105
+ "Contributor" shall mean Licensor and any individual or Legal Entity
106
+ on behalf of whom a Contribution has been received by Licensor and
107
+ subsequently incorporated within the Work.
108
+
109
+ 2. Grant of Copyright License. Subject to the terms and conditions of
110
+ this License, each Contributor hereby grants to You a perpetual,
111
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
112
+ copyright license to reproduce, prepare Derivative Works of,
113
+ publicly display, publicly perform, sublicense, and distribute the
114
+ Work and such Derivative Works in Source or Object form.
115
+
116
+ 3. Grant of Patent License. Subject to the terms and conditions of
117
+ this License, each Contributor hereby grants to You a perpetual,
118
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
119
+ (except as stated in this section) patent license to make, have made,
120
+ use, offer to sell, sell, import, and otherwise transfer the Work,
121
+ where such license applies only to those patent claims licensable
122
+ by such Contributor that are necessarily infringed by their
123
+ Contribution(s) alone or by combination of their Contribution(s)
124
+ with the Work to which such Contribution(s) was submitted. If You
125
+ institute patent litigation against any entity (including a
126
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
127
+ or a Contribution incorporated within the Work constitutes direct
128
+ or contributory patent infringement, then any patent licenses
129
+ granted to You under this License for that Work shall terminate
130
+ as of the date such litigation is filed.
131
+
132
+ 4. Redistribution. You may reproduce and distribute copies of the
133
+ Work or Derivative Works thereof in any medium, with or without
134
+ modifications, and in Source or Object form, provided that You
135
+ meet the following conditions:
136
+
137
+ (a) You must give any other recipients of the Work or
138
+ Derivative Works a copy of this License; and
139
+
140
+ (b) You must cause any modified files to carry prominent notices
141
+ stating that You changed the files; and
142
+
143
+ (c) You must retain, in the Source form of any Derivative Works
144
+ that You distribute, all copyright, patent, trademark, and
145
+ attribution notices from the Source form of the Work,
146
+ excluding those notices that do not pertain to any part of
147
+ the Derivative Works; and
148
+
149
+ (d) If the Work includes a "NOTICE" text file as part of its
150
+ distribution, then any Derivative Works that You distribute must
151
+ include a readable copy of the attribution notices contained
152
+ within such NOTICE file, excluding those notices that do not
153
+ pertain to any part of the Derivative Works, in at least one
154
+ of the following places: within a NOTICE text file distributed
155
+ as part of the Derivative Works; within the Source form or
156
+ documentation, if provided along with the Derivative Works; or,
157
+ within a display generated by the Derivative Works, if and
158
+ wherever such third-party notices normally appear. The contents
159
+ of the NOTICE file are for informational purposes only and
160
+ do not modify the License. You may add Your own attribution
161
+ notices within Derivative Works that You distribute, alongside
162
+ or as an addendum to the NOTICE text from the Work, provided
163
+ that such additional attribution notices cannot be construed
164
+ as modifying the License.
165
+
166
+ You may add Your own copyright statement to Your modifications and
167
+ may provide additional or different license terms and conditions
168
+ for use, reproduction, or distribution of Your modifications, or
169
+ for any such Derivative Works as a whole, provided Your use,
170
+ reproduction, and distribution of the Work otherwise complies with
171
+ the conditions stated in this License.
172
+
173
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
174
+ any Contribution intentionally submitted for inclusion in the Work
175
+ by You to the Licensor shall be under the terms and conditions of
176
+ this License, without any additional terms or conditions.
177
+ Notwithstanding the above, nothing herein shall supersede or modify
178
+ the terms of any separate license agreement you may have executed
179
+ with Licensor regarding such Contributions.
180
+
181
+ 6. Trademarks. This License does not grant permission to use the trade
182
+ names, trademarks, service marks, or product names of the Licensor,
183
+ except as required for reasonable and customary use in describing the
184
+ origin of the Work and reproducing the content of the NOTICE file.
185
+
186
+ 7. Disclaimer of Warranty. Unless required by applicable law or
187
+ agreed to in writing, Licensor provides the Work (and each
188
+ Contributor provides its Contributions) on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
190
+ implied, including, without limitation, any warranties or conditions
191
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
192
+ PARTICULAR PURPOSE. You are solely responsible for determining the
193
+ appropriateness of using or redistributing the Work and assume any
194
+ risks associated with Your exercise of permissions under this License.
195
+
196
+ 8. Limitation of Liability. In no event and under no legal theory,
197
+ whether in tort (including negligence), contract, or otherwise,
198
+ unless required by applicable law (such as deliberate and grossly
199
+ negligent acts) or agreed to in writing, shall any Contributor be
200
+ liable to You for damages, including any direct, indirect, special,
201
+ incidental, or consequential damages of any character arising as a
202
+ result of this License or out of the use or inability to use the
203
+ Work (including but not limited to damages for loss of goodwill,
204
+ work stoppage, computer failure or malfunction, or any and all
205
+ other commercial damages or losses), even if such Contributor
206
+ has been advised of the possibility of such damages.
207
+
208
+ 9. Accepting Warranty or Additional Liability. While redistributing
209
+ the Work or Derivative Works thereof, You may choose to offer,
210
+ and charge a fee for, acceptance of support, warranty, indemnity,
211
+ or other liability obligations and/or rights consistent with this
212
+ License. However, in accepting such obligations, You may act only
213
+ on Your own behalf and on Your sole responsibility, not on behalf
214
+ of any other Contributor, and only if You agree to indemnify,
215
+ defend, and hold each Contributor harmless for any liability
216
+ incurred by, or claims asserted against, such Contributor by reason
217
+ of your accepting any such warranty or additional liability.
218
+
219
+ END OF TERMS AND CONDITIONS
220
+
221
+ APPENDIX: How to apply the Apache License to your work.
222
+
223
+ To apply the Apache License to your work, attach the following
224
+ boilerplate notice, with the fields enclosed by brackets "[]"
225
+ replaced with your own identifying information. (Don't include
226
+ the brackets!) The text should be enclosed in the appropriate
227
+ comment syntax for the file format. We also recommend that a
228
+ file or class name and description of purpose be included on the
229
+ same "printed page" as the copyright notice for easier
230
+ identification within third-party archives.
231
+
232
+ Copyright [yyyy] [name of copyright owner]
233
+
234
+ Licensed under the Apache License, Version 2.0 (the "License");
235
+ you may not use this file except in compliance with the License.
236
+ You may obtain a copy of the License at
237
+
238
+ http://www.apache.org/licenses/LICENSE-2.0
239
+
240
+ Unless required by applicable law or agreed to in writing, software
241
+ distributed under the License is distributed on an "AS IS" BASIS,
242
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
243
+ See the License for the specific language governing permissions and
244
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # View image for Pi Durable
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `createViewImageTool(options)` creates a Durable `view_image` registration. Install it in the ordinary tool registry. Code and Notebook discover the same registration.
4
+
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
7
+ ```
8
+
9
+ ```ts
10
+ import { createRegistry } from "@earendil-works/pi-durable";
11
+ import { createViewImageTool } from "@howaboua/pi-durable-view-image";
12
+
13
+ // models is the same pi-ai Models collection supplied to Harness.open().
14
+ const registry = createRegistry();
15
+ registry.install({
16
+ name: "images",
17
+ tools: [createViewImageTool({ models, describeForTextModels: true })],
18
+ });
19
+ ```
20
+
21
+ The tool accepts `{ path: string, detail?: "original" }`. Relative paths resolve through the conversation's `api.env`. `file_path` and `image_path` are repaired to `path`. A leading `@` is removed. The canonical `path` wins when aliases are also present.
22
+
23
+ PNG, JPEG and WebP return their original bytes after Rust image decoding validates the image through `@napi-rs/image@1.15.0`. GIF returns the first frame as PNG through `sharp@0.35.5`. Images are not resized or EXIF-rotated. Both native codecs receive bytes from the execution environment and do not read host paths.
24
+
25
+ Returned images carry `detail: "original"` alongside pi-ai image content. The `@howaboua/pi-durable-openai-responses` provider forwards it for both tool-result images and optional description requests. Other providers may ignore this per-image setting; pi-ai's stock Responses serializer uses `auto`. The marker does not alter the encoded image bytes.
26
+
27
+ ## Text-only models
28
+
29
+ Description is disabled by default. Enable `describeForTextModels` to return a description from a vision model, plus the image, path and description in `details.viewImageDescription`. The description call uses the injected Models collection for provider routing and authentication. No Pi extension context or provider auth shim is needed.
30
+
31
+ The default description model is `gpt-6-luna` in the caller's provider. Set `descriptionModel: { provider, modelId }` to use another configured vision model. Requests use low reasoning. Responses providers also receive low verbosity and automatic reasoning summaries through pi-ai's supported payload callback. Missing models, provider failures and empty descriptions are visible tool failures.
32
+
33
+ Cancellation follows the Durable invocation context. Description-enabled registrations are replay-unsafe because an interrupted provider request may already have incurred a charge. Registrations with description disabled are replay-safe.
34
+
35
+ ## Validation
36
+
37
+ ```sh
38
+ node --experimental-strip-types --test packages/view-image/test/*.test.ts
39
+ VIEW_IMAGE_REFERENCE_BINARY=/path/to/pinned/view_image \
40
+ node --experimental-strip-types --test packages/view-image/test/differential.ts
41
+ ```
42
+
43
+ The differential probe creates temporary fixtures and invokes the reference helper read-only. Original bytes, first-frame conversion and decoder acceptance evidence are recorded in [`docs/parity/view-image.md`](../../docs/parity/view-image.md).
44
+
45
+ ## Headless presentations
46
+
47
+ The browser-safe `@howaboua/pi-durable-view-image/presentation` entry exports `viewImageCapability`, `viewImageSummary`, `viewImageDetail` and `createViewImagePresentationState`. The constructor projects an existing tool receipt into the invoked path and returned image MIME type without retaining encoded bytes.
48
+
49
+ Start with `createViewImagePresentationState(path, image)`. Its `detail` is `null`, meaning not acquired. Bind the capability once and select either presentation. A summary request for `detail` is a host callback, not a tool call. The host may publish the already recorded body on demand. Empty acquired results remain distinct from `null`.
50
+
51
+ These readonly receipt capabilities expose no actions or streams. They do not register tools, load artifacts, authenticate, or replay operations. The host owns binding, authorization and any ordinary tool invocation. Never repeat an interrupted side effect to populate a presentation.
@@ -0,0 +1,10 @@
1
+ import type { ImageContent } from "@earendil-works/pi-ai";
2
+ export type ViewImageContent = {
3
+ type: ImageContent["type"];
4
+ data: string;
5
+ mimeType: string;
6
+ /** Preserved by the local Responses provider; other providers may ignore it. */
7
+ detail: "original";
8
+ };
9
+ /** The Original path validates every pixel but never rotates or rewrites passthrough formats. */
10
+ export declare function createImageCodec(): (bytes: Uint8Array, path: string, signal?: AbortSignal) => Promise<ViewImageContent>;
@@ -0,0 +1,8 @@
1
+ import type { Context } from "@earendil-works/chord";
2
+ import type { Models, Usage } from "@earendil-works/pi-ai";
3
+ import type { ModelRef } from "@earendil-works/pi-durable";
4
+ import type { ViewImageContent } from "./codec.ts";
5
+ export declare function describeImage(image: ViewImageContent, models: Models, caller: ModelRef, configured: ModelRef | undefined, context: Context): Promise<{
6
+ description: string;
7
+ usage: Usage;
8
+ }>;
@@ -0,0 +1,27 @@
1
+ import type { Models } from "@earendil-works/pi-ai";
2
+ import { type ModelRef, type ToolRegistration } from "@earendil-works/pi-durable";
3
+ import { Type } from "typebox";
4
+ import { type ViewImageContent } from "./codec.ts";
5
+ export type { ViewImageContent } from "./codec.ts";
6
+ export interface ViewImageOptions {
7
+ /** Supply the same collection passed to Harness.open(). */
8
+ models: Models;
9
+ describeForTextModels?: boolean;
10
+ /** Defaults to gpt-6-luna in the caller's provider. */
11
+ descriptionModel?: ModelRef;
12
+ }
13
+ export type ViewImageDetails = {
14
+ viewImage: true;
15
+ } | {
16
+ viewImageDescription: {
17
+ image: ViewImageContent;
18
+ path: string;
19
+ description: string;
20
+ };
21
+ };
22
+ declare const schema: Type.TObject<{
23
+ path: Type.TString;
24
+ detail: Type.TOptional<Type.TLiteral<"original">>;
25
+ }>;
26
+ /** Durable registration. Ordinary registry discovery also exposes this tool to Code and Notebook. */
27
+ export declare function createViewImageTool(options: ViewImageOptions): ToolRegistration<typeof schema, ViewImageDetails>;
package/dist/index.js ADDED
@@ -0,0 +1,239 @@
1
+ // packages/view-image/src/index.ts
2
+ import {
3
+ defineTool
4
+ } from "@earendil-works/pi-durable";
5
+ import {
6
+ getOrThrow
7
+ } from "@earendil-works/pi-durable/env";
8
+ import { Type } from "typebox";
9
+
10
+ // packages/view-image/src/codec.ts
11
+ import { createHash } from "node:crypto";
12
+ import { Transformer } from "@napi-rs/image";
13
+ import sharp from "sharp";
14
+ var CACHE_ENTRIES = 32;
15
+ var CACHE_BYTES = 64 * 1024 * 1024;
16
+ function createImageCodec() {
17
+ const cache = new Map;
18
+ let cacheBytes = 0;
19
+ return async (bytes, path, signal) => {
20
+ signal?.throwIfAborted();
21
+ const digest = createHash("sha1").update(bytes).digest("hex");
22
+ const cached = cache.get(digest);
23
+ if (cached) {
24
+ cache.delete(digest);
25
+ cache.set(digest, cached);
26
+ return { ...cached.image };
27
+ }
28
+ const input = Buffer.from(bytes);
29
+ const format = detectFormat(input);
30
+ if (!format)
31
+ throw new Error(`unable to process image at \`${path}\`: unsupported image format`);
32
+ let encoded;
33
+ try {
34
+ if (format === "gif") {
35
+ encoded = await decodeGif(input, signal);
36
+ } else {
37
+ await new Transformer(input).metadata(false, signal);
38
+ encoded = input;
39
+ }
40
+ signal?.throwIfAborted();
41
+ } catch (cause) {
42
+ signal?.throwIfAborted();
43
+ throw new Error(`unable to process image at \`${path}\`: failed to decode image: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
44
+ }
45
+ const image = {
46
+ type: "image",
47
+ data: encoded.toString("base64"),
48
+ mimeType: format === "gif" ? "image/png" : `image/${format}`,
49
+ detail: "original"
50
+ };
51
+ if (encoded.byteLength <= CACHE_BYTES) {
52
+ const previous = cache.get(digest);
53
+ if (previous)
54
+ cacheBytes -= previous.size;
55
+ cache.delete(digest);
56
+ cache.set(digest, { image: { ...image }, size: encoded.byteLength });
57
+ cacheBytes += encoded.byteLength;
58
+ while (cache.size > CACHE_ENTRIES || cacheBytes > CACHE_BYTES) {
59
+ const oldest = cache.entries().next().value;
60
+ if (!oldest)
61
+ break;
62
+ cache.delete(oldest[0]);
63
+ cacheBytes -= oldest[1].size;
64
+ }
65
+ }
66
+ return image;
67
+ };
68
+ }
69
+ async function decodeGif(input, signal) {
70
+ const decoder = sharp(input, {
71
+ animated: false,
72
+ failOn: "error",
73
+ limitInputPixels: false
74
+ });
75
+ const abort = () => {
76
+ decoder.destroy();
77
+ };
78
+ signal?.addEventListener("abort", abort, { once: true });
79
+ try {
80
+ const { data, info } = await decoder.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
81
+ signal?.throwIfAborted();
82
+ return await sharp(data, {
83
+ raw: { width: info.width, height: info.height, channels: info.channels }
84
+ }).png().toBuffer();
85
+ } finally {
86
+ signal?.removeEventListener("abort", abort);
87
+ decoder.destroy();
88
+ }
89
+ }
90
+ function detectFormat(bytes) {
91
+ if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
92
+ return "png";
93
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255)
94
+ return "jpeg";
95
+ if (["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString("ascii")))
96
+ return "gif";
97
+ if (bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP")
98
+ return "webp";
99
+ return;
100
+ }
101
+
102
+ // packages/view-image/src/description.ts
103
+ var DESCRIPTION_PROMPT = "Describe this image in detail. Output only the image description, no other commentary";
104
+ async function describeImage(image, models, caller, configured, context) {
105
+ const ref = configured ?? {
106
+ provider: caller.provider,
107
+ modelId: "gpt-6-luna"
108
+ };
109
+ const model = models.getModel(ref.provider, ref.modelId);
110
+ if (!model)
111
+ throw new Error(`view_image description model not found: ${ref.provider}/${ref.modelId}`);
112
+ if (!model.input.includes("image"))
113
+ throw new Error(`view_image description model does not support image inputs: ${ref.provider}/${ref.modelId}`);
114
+ context.abortSignal?.throwIfAborted();
115
+ const reply = await models.completeSimple(model, {
116
+ systemPrompt: DESCRIPTION_PROMPT,
117
+ messages: [
118
+ {
119
+ role: "user",
120
+ content: [{ type: "text", text: "Describe the image" }, image],
121
+ timestamp: Date.now()
122
+ }
123
+ ]
124
+ }, {
125
+ reasoning: "low",
126
+ ...context.abortSignal ? { signal: context.abortSignal } : {},
127
+ onPayload: prepareDescriptionPayload
128
+ });
129
+ context.abortSignal?.throwIfAborted();
130
+ if (reply.stopReason === "error" || reply.stopReason === "aborted") {
131
+ throw new Error(`view_image description failed: ${reply.errorMessage ?? reply.stopReason}`);
132
+ }
133
+ const description = reply.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("").trim();
134
+ if (!description)
135
+ throw new Error("view_image description returned no text");
136
+ return { description, usage: reply.usage };
137
+ }
138
+ function prepareDescriptionPayload(payload, model) {
139
+ if (model.api !== "openai-responses" && model.api !== "openai-codex-responses")
140
+ return;
141
+ if (!payload || typeof payload !== "object")
142
+ throw new Error("view_image description expected a Responses payload");
143
+ const body = payload;
144
+ const reasoning = body["reasoning"];
145
+ const text = body["text"];
146
+ return {
147
+ ...body,
148
+ text: {
149
+ ...text && typeof text === "object" ? text : {},
150
+ verbosity: "low"
151
+ },
152
+ ...reasoning && typeof reasoning === "object" ? { reasoning: { ...reasoning, summary: "auto" } } : {}
153
+ };
154
+ }
155
+
156
+ // packages/view-image/src/index.ts
157
+ var schema = Type.Object({
158
+ path: Type.String(),
159
+ detail: Type.Optional(Type.Literal("original"))
160
+ });
161
+ function createViewImageTool(options) {
162
+ const loadImage = createImageCodec();
163
+ return defineTool({
164
+ name: "view_image",
165
+ description: "View image",
166
+ parameters: schema,
167
+ replay: options.describeForTextModels ? "unsafe" : "safe",
168
+ prepareArguments,
169
+ async execute(args, api, context) {
170
+ context.abortSignal?.throwIfAborted();
171
+ const agent = await api.agent(context);
172
+ if (!agent.model)
173
+ throw new Error("view_image requires a conversation model");
174
+ const model = options.models.getModel(agent.model.provider, agent.model.modelId);
175
+ if (!model)
176
+ throw new Error(`view_image model not found: ${agent.model.provider}/${agent.model.modelId}`);
177
+ const vision = model.input.includes("image");
178
+ if (!vision && !options.describeForTextModels) {
179
+ throw new Error("view_image is not allowed because you do not support image inputs");
180
+ }
181
+ if (!api.env)
182
+ throw new Error("view_image requires an execution environment");
183
+ const path = await locateImage(api.env, args.path, context);
184
+ let bytes;
185
+ try {
186
+ bytes = getOrThrow(await api.env.readBinaryFile(path, context));
187
+ } catch (cause) {
188
+ context.abortSignal?.throwIfAborted();
189
+ throw new Error(`unable to read image at \`${path}\`: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
190
+ }
191
+ const image = await loadImage(bytes, path, context.abortSignal);
192
+ if (vision)
193
+ return { output: [image], details: { viewImage: true } };
194
+ const { description, usage } = await describeImage(image, options.models, agent.model, options.descriptionModel, context);
195
+ return {
196
+ output: [{ type: "text", text: description }],
197
+ details: {
198
+ viewImageDescription: { image, path: args.path, description }
199
+ },
200
+ usage
201
+ };
202
+ }
203
+ });
204
+ }
205
+ function prepareArguments(args) {
206
+ if (!args || typeof args !== "object")
207
+ throw new Error("view_image requires a string 'path' parameter");
208
+ const record = args;
209
+ const path = "path" in record ? record["path"] : ("file_path" in record) ? record["file_path"] : record["image_path"];
210
+ if (typeof path !== "string")
211
+ throw new Error("view_image requires a string 'path' parameter");
212
+ const detail = record["detail"];
213
+ if (detail !== undefined && detail !== null && typeof detail !== "string")
214
+ throw new Error("view_image.detail must be a string when provided");
215
+ if (typeof detail === "string" && detail !== "original")
216
+ throw new Error(`view_image.detail only supports \`original\`, got \`${detail}\``);
217
+ return {
218
+ path: path.startsWith("@") ? path.slice(1) : path,
219
+ ...detail === "original" ? { detail } : {}
220
+ };
221
+ }
222
+ async function locateImage(env, input, context) {
223
+ const path = getOrThrow(await env.absolutePath(input, context));
224
+ let info;
225
+ try {
226
+ info = getOrThrow(await env.fileInfo(path, context));
227
+ if (info.kind === "symlink")
228
+ info = getOrThrow(await env.fileInfo(getOrThrow(await env.canonicalPath(path, context)), context));
229
+ } catch (cause) {
230
+ context.abortSignal?.throwIfAborted();
231
+ throw new Error(`unable to locate image at \`${path}\`: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
232
+ }
233
+ if (info.kind !== "file")
234
+ throw new Error(`image path \`${path}\` is not a file`);
235
+ return path;
236
+ }
237
+ export {
238
+ createViewImageTool
239
+ };
@@ -0,0 +1,38 @@
1
+ import type { ViewImageContent } from "./codec.ts";
2
+ export interface ViewImagePresentationState {
3
+ path: string;
4
+ mimeType: string;
5
+ detail: {
6
+ image: ViewImageContent;
7
+ description: string | null;
8
+ } | null;
9
+ }
10
+ /** The host supplies the actual path and codec result from an existing invocation. */
11
+ export declare function createViewImagePresentationState(path: string, image: ViewImageContent): ViewImagePresentationState;
12
+ declare function parseState(value: unknown): ViewImagePresentationState;
13
+ /** Readonly receipts. The host owns binding, acquisition and ordinary tool invocation. */
14
+ export declare const viewImageCapability: {
15
+ id: string;
16
+ version: number;
17
+ parseState: typeof parseState;
18
+ actions: readonly string[];
19
+ streams: readonly string[];
20
+ presentations: readonly string[];
21
+ };
22
+ export declare const viewImageSummary: {
23
+ id: string;
24
+ select: (state: ViewImagePresentationState) => {
25
+ path: string;
26
+ mimeType: string;
27
+ };
28
+ requests: readonly string[];
29
+ };
30
+ export declare const viewImageDetail: {
31
+ id: string;
32
+ select: (state: ViewImagePresentationState) => {
33
+ image: ViewImageContent;
34
+ description: string | null;
35
+ } | null;
36
+ requests: readonly string[];
37
+ };
38
+ export {};
@@ -0,0 +1,63 @@
1
+ // packages/view-image/src/presentation.ts
2
+ function createViewImagePresentationState(path, image) {
3
+ return parseState({ path, mimeType: image.mimeType, detail: null });
4
+ }
5
+ function parseState(value) {
6
+ const state = record(value);
7
+ const path = string(state["path"]);
8
+ const mimeType = string(state["mimeType"]);
9
+ let detail = null;
10
+ if (state["detail"] !== null) {
11
+ const body = record(state["detail"]);
12
+ const image = record(body["image"]);
13
+ if (image["type"] !== "image" || image["mimeType"] !== mimeType)
14
+ throw new TypeError("Invalid viewed image");
15
+ detail = {
16
+ image: {
17
+ type: "image",
18
+ mimeType,
19
+ data: string(image["data"]),
20
+ detail: "original"
21
+ },
22
+ description: body["description"] === null ? null : string(body["description"])
23
+ };
24
+ }
25
+ return { path, mimeType, detail };
26
+ }
27
+ var viewImageCapability = {
28
+ id: "view-image",
29
+ version: 1,
30
+ parseState,
31
+ actions: [],
32
+ streams: [],
33
+ presentations: ["summary", "detail"]
34
+ };
35
+ var viewImageSummary = {
36
+ id: "summary",
37
+ select: (state) => ({
38
+ path: state.path,
39
+ mimeType: state.mimeType
40
+ }),
41
+ requests: ["detail"]
42
+ };
43
+ var viewImageDetail = {
44
+ id: "detail",
45
+ select: (state) => state.detail,
46
+ requests: []
47
+ };
48
+ function record(value) {
49
+ if (!value || typeof value !== "object" || Array.isArray(value))
50
+ throw new TypeError("Expected a receipt object");
51
+ return value;
52
+ }
53
+ function string(value) {
54
+ if (typeof value !== "string")
55
+ throw new TypeError("Expected a string");
56
+ return value;
57
+ }
58
+ export {
59
+ createViewImagePresentationState,
60
+ viewImageCapability,
61
+ viewImageDetail,
62
+ viewImageSummary
63
+ };
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
- "name": "@howaboua/pi-durable-view-image",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@howaboua/pi-durable-view-image",
3
+ "version": "0.9.1",
4
+ "description": "Image inspection and description for Pi Durable",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/IgorWarzocha/pi-durable-components.git",
10
+ "directory": "packages/view-image"
11
+ },
12
+ "author": "Igor Warzocha",
13
+ "engines": {
14
+ "node": ">=22.19.0"
15
+ },
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ "./presentation": {
20
+ "types": "./dist/presentation.d.ts",
21
+ "import": "./dist/presentation.js"
22
+ },
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "NOTICE",
32
+ "LICENSE"
33
+ ],
34
+ "sideEffects": false,
35
+ "dependencies": {
36
+ "@napi-rs/image": "1.15.0",
37
+ "sharp": "0.35.5",
38
+ "typebox": "1.3.27"
39
+ },
40
+ "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"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ }
49
+ }