@eduardo191labs/opencode-free-pi 0.3.20 → 0.3.21

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
@@ -129,9 +129,10 @@ herramienta `look_at_image` con una ruta y una pregunta concreta. El plugin:
129
129
  - Solo lee archivos dentro de la carpeta del proyecto (incluidos enlaces
130
130
  simbólicos resueltos).
131
131
  - Acepta PNG, JPEG y WebP.
132
- - Detecta el tamaño y reduce automáticamente las imágenes que superan los
133
- 2000 px o los 5 MB, probando PNG y varias calidades JPEG con Photon, para no
134
- enviar base64 enorme ni gastar cuota de más.
132
+ - Lee las dimensiones de la cabecera y envía el archivo intacto mientras no
133
+ supere los 5 MB, conservando la resolución y la calidad originales. Solo las
134
+ imágenes mayores se recodifican con Photon, manteniendo el mayor tamaño y la
135
+ mejor calidad JPEG que quepan en el límite.
135
136
  - Envía la imagen a `/tools/vision` y devuelve la respuesta del modelo de
136
137
  visión como texto.
137
138
 
@@ -41,8 +41,18 @@ export declare function detectMime(bytes: Uint8Array): VisionMime | undefined;
41
41
  * so a symlink cannot escape the project folder.
42
42
  */
43
43
  export declare function loadImage(cwd: string, path: string): LoadedImage;
44
+ export type ImageSize = {
45
+ readonly width: number;
46
+ readonly height: number;
47
+ };
48
+ /**
49
+ * Reads dimensions from the file header. This avoids decoding typical images
50
+ * with WASM just to decide whether they need to be resized.
51
+ */
52
+ export declare function imageSize(bytes: Buffer, mime: VisionMime): ImageSize | undefined;
44
53
  /**
45
- * Decodes the image and downscales it when it exceeds 2000 px or 5 MB.
54
+ * Sends the file untouched while it fits the provider's 5 MB limit. Only larger
55
+ * files are decoded, and then kept at the highest resolution/quality that fits.
46
56
  *
47
57
  * Photon is optional: if its WASM module cannot load, images that already fit
48
58
  * are still sent unchanged, while oversized ones fail with a clear message.
@@ -12,9 +12,14 @@ import { isAbsolute, relative, resolve, sep } from "node:path";
12
12
  export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
13
13
  /** Refuse to read absurd files before decoding them in memory. */
14
14
  const MAX_SOURCE_BYTES = 80 * 1024 * 1024;
15
- /** pi's attachment limit: 2000 x 2000 is enough for screenshots and UI QA. */
16
- const MAX_DIMENSION = 2_000;
17
- const JPEG_QUALITIES = [80, 70, 55, 40];
15
+ /**
16
+ * Only images above the provider's 5 MB limit are re-encoded. The CLI sends
17
+ * full-resolution files, and more pixels help OCR; the first JPEG quality that
18
+ * fits is kept instead of forcing an aggressive downscale.
19
+ */
20
+ const JPEG_QUALITIES = [92, 85, 75, 62, 50];
21
+ /** Refuse to decode absurd canvases that could exhaust memory. */
22
+ const MAX_DECODE_DIMENSION = 8_000;
18
23
  const OUTSIDE = "look_at_image only reads images inside the project folder.";
19
24
  let photonPromise;
20
25
  /** Loads Photon lazily so the plugin startup does not pay for the WASM module. */
@@ -104,6 +109,92 @@ export function loadImage(cwd, path) {
104
109
  closeSync(fd);
105
110
  }
106
111
  }
112
+ function pngSize(bytes) {
113
+ if (bytes.length < 24 || bytes.toString("latin1", 12, 16) !== "IHDR") {
114
+ return undefined;
115
+ }
116
+ const width = bytes.readUInt32BE(16);
117
+ const height = bytes.readUInt32BE(20);
118
+ return width > 0 && height > 0 ? { width, height } : undefined;
119
+ }
120
+ /** Walks the JPEG markers up to the first Start Of Frame segment. */
121
+ function jpegSize(bytes) {
122
+ let offset = 2;
123
+ while (offset + 9 < bytes.length) {
124
+ if (bytes[offset] !== 0xff) {
125
+ offset += 1;
126
+ continue;
127
+ }
128
+ const marker = bytes[offset + 1];
129
+ if (marker === 0xff) {
130
+ offset += 1;
131
+ continue;
132
+ }
133
+ if (marker === 0xd8 ||
134
+ marker === 0xd9 ||
135
+ (marker >= 0xd0 && marker <= 0xd7)) {
136
+ offset += 2;
137
+ continue;
138
+ }
139
+ const length = bytes.readUInt16BE(offset + 2);
140
+ if (length < 2)
141
+ return undefined;
142
+ const sof = (marker >= 0xc0 && marker <= 0xc3) ||
143
+ (marker >= 0xc5 && marker <= 0xc7) ||
144
+ (marker >= 0xc9 && marker <= 0xcb) ||
145
+ (marker >= 0xcd && marker <= 0xcf);
146
+ if (sof) {
147
+ if (offset + 9 > bytes.length)
148
+ return undefined;
149
+ const height = bytes.readUInt16BE(offset + 5);
150
+ const width = bytes.readUInt16BE(offset + 7);
151
+ return width > 0 && height > 0 ? { width, height } : undefined;
152
+ }
153
+ offset += 2 + length;
154
+ }
155
+ return undefined;
156
+ }
157
+ function webpSize(bytes) {
158
+ if (bytes.length < 30)
159
+ return undefined;
160
+ const chunk = bytes.toString("latin1", 12, 16);
161
+ if (chunk === "VP8X") {
162
+ const width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16));
163
+ const height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16));
164
+ return { width, height };
165
+ }
166
+ if (chunk === "VP8 ") {
167
+ if (bytes[23] !== 0x9d ||
168
+ bytes[24] !== 0x01 ||
169
+ bytes[25] !== 0x2a) {
170
+ return undefined;
171
+ }
172
+ const width = bytes.readUInt16LE(26) & 0x3fff;
173
+ const height = bytes.readUInt16LE(28) & 0x3fff;
174
+ return width > 0 && height > 0 ? { width, height } : undefined;
175
+ }
176
+ if (chunk === "VP8L") {
177
+ if (bytes[20] !== 0x2f)
178
+ return undefined;
179
+ const bits = bytes.readUInt32LE(21);
180
+ return {
181
+ width: (bits & 0x3fff) + 1,
182
+ height: ((bits >>> 14) & 0x3fff) + 1,
183
+ };
184
+ }
185
+ return undefined;
186
+ }
187
+ /**
188
+ * Reads dimensions from the file header. This avoids decoding typical images
189
+ * with WASM just to decide whether they need to be resized.
190
+ */
191
+ export function imageSize(bytes, mime) {
192
+ if (mime === "image/png")
193
+ return pngSize(bytes);
194
+ if (mime === "image/jpeg")
195
+ return jpegSize(bytes);
196
+ return webpSize(bytes);
197
+ }
107
198
  function unchanged(bytes, mime, width, height) {
108
199
  return {
109
200
  ok: true,
@@ -118,52 +209,61 @@ function unchanged(bytes, mime, width, height) {
118
209
  resized: false,
119
210
  };
120
211
  }
212
+ function candidate(bytes, mime) {
213
+ return { data: bytes.toString("base64"), mime, bytes: bytes.length };
214
+ }
121
215
  /**
122
- * Re-encodes the image at `width` x `height`, trying PNG and several JPEG
123
- * qualities, and returns the smallest candidate under the size limit.
216
+ * Re-encodes the image at `width` x `height`. It keeps the source format when
217
+ * possible and stops at the first JPEG quality that fits, so one call usually
218
+ * costs a single encode instead of five.
124
219
  */
125
220
  function encodeCandidate(photon, image, width, height, preferred) {
126
221
  const resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3);
127
222
  try {
128
- const png = Buffer.from(resized.get_bytes());
129
- const candidates = [
130
- { data: png.toString("base64"), mime: "image/png", bytes: png.length },
131
- ];
223
+ // Keep PNG screenshots crisp: JPEG artifacts blur UI text and transparency,
224
+ // and the vision model charges by pixels, not by encoded bytes.
225
+ if (preferred === "image/png") {
226
+ const png = Buffer.from(resized.get_bytes());
227
+ if (png.length <= MAX_IMAGE_BYTES)
228
+ return candidate(png, "image/png");
229
+ }
230
+ if (preferred === "image/webp") {
231
+ try {
232
+ const webp = Buffer.from(resized.get_bytes_webp());
233
+ if (webp.length <= MAX_IMAGE_BYTES)
234
+ return candidate(webp, "image/webp");
235
+ }
236
+ catch {
237
+ // Older Photon builds may not expose WebP encoding.
238
+ }
239
+ }
132
240
  for (const quality of JPEG_QUALITIES) {
133
241
  const jpeg = Buffer.from(resized.get_bytes_jpeg(quality));
134
- candidates.push({
135
- data: jpeg.toString("base64"),
136
- mime: "image/jpeg",
137
- bytes: jpeg.length,
138
- });
242
+ if (jpeg.length <= MAX_IMAGE_BYTES)
243
+ return candidate(jpeg, "image/jpeg");
139
244
  }
140
- const usable = candidates.filter((candidate) => candidate.bytes <= MAX_IMAGE_BYTES);
141
- if (usable.length === 0)
142
- return undefined;
143
- // Keep PNG for PNG screenshots as long as it fits: JPEG artifacts blur UI
144
- // text and transparency, and the vision model charges by pixels, not bytes.
145
- if (preferred === "image/png") {
146
- const pngCandidate = usable.find((candidate) => candidate.mime === "image/png");
147
- if (pngCandidate)
148
- return pngCandidate;
149
- }
150
- return usable.sort((a, b) => a.bytes - b.bytes)[0];
245
+ return undefined;
151
246
  }
152
247
  finally {
153
248
  resized.free();
154
249
  }
155
250
  }
156
251
  /**
157
- * Decodes the image and downscales it when it exceeds 2000 px or 5 MB.
252
+ * Sends the file untouched while it fits the provider's 5 MB limit. Only larger
253
+ * files are decoded, and then kept at the highest resolution/quality that fits.
158
254
  *
159
255
  * Photon is optional: if its WASM module cannot load, images that already fit
160
256
  * are still sent unchanged, while oversized ones fail with a clear message.
161
257
  */
162
258
  export async function prepareImage(bytes, mime, name) {
259
+ // The normal path never touches WASM, so screenshots and phone photos under
260
+ // 5 MB keep their original resolution and add no local processing latency.
261
+ const size = imageSize(bytes, mime);
262
+ if (bytes.length <= MAX_IMAGE_BYTES) {
263
+ return unchanged(bytes, mime, size?.width ?? 0, size?.height ?? 0);
264
+ }
163
265
  const photo = await loadPhoton();
164
266
  if (!photo) {
165
- if (bytes.length <= MAX_IMAGE_BYTES)
166
- return unchanged(bytes, mime, 0, 0);
167
267
  return {
168
268
  ok: false,
169
269
  text: `${name} is larger than 5 MB and image resizing is unavailable in this OpenCode runtime. Resize it first.`,
@@ -174,8 +274,6 @@ export async function prepareImage(bytes, mime, name) {
174
274
  image = photo.PhotonImage.new_from_byteslice(new Uint8Array(bytes));
175
275
  }
176
276
  catch {
177
- if (bytes.length <= MAX_IMAGE_BYTES)
178
- return unchanged(bytes, mime, 0, 0);
179
277
  return {
180
278
  ok: false,
181
279
  text: `${name} could not be decoded, so it cannot be reduced below 5 MB.`,
@@ -184,22 +282,13 @@ export async function prepareImage(bytes, mime, name) {
184
282
  try {
185
283
  const originalWidth = image.get_width();
186
284
  const originalHeight = image.get_height();
187
- if (originalWidth <= MAX_DIMENSION &&
188
- originalHeight <= MAX_DIMENSION &&
189
- bytes.length <= MAX_IMAGE_BYTES) {
190
- return unchanged(bytes, mime, originalWidth, originalHeight);
191
- }
192
- let width = originalWidth;
193
- let height = originalHeight;
194
- if (width > MAX_DIMENSION) {
195
- height = Math.max(1, Math.round((height * MAX_DIMENSION) / width));
196
- width = MAX_DIMENSION;
197
- }
198
- if (height > MAX_DIMENSION) {
199
- width = Math.max(1, Math.round((width * MAX_DIMENSION) / height));
200
- height = MAX_DIMENSION;
201
- }
285
+ const longest = Math.max(originalWidth, originalHeight);
286
+ let scale = longest > MAX_DECODE_DIMENSION
287
+ ? MAX_DECODE_DIMENSION / longest
288
+ : 1;
202
289
  while (true) {
290
+ const width = Math.max(1, Math.round(originalWidth * scale));
291
+ const height = Math.max(1, Math.round(originalHeight * scale));
203
292
  const best = encodeCandidate(photo, image, width, height, mime);
204
293
  if (best) {
205
294
  return {
@@ -217,12 +306,7 @@ export async function prepareImage(bytes, mime, name) {
217
306
  }
218
307
  if (width === 1 && height === 1)
219
308
  break;
220
- const nextWidth = width === 1 ? 1 : Math.max(1, Math.floor(width * 0.75));
221
- const nextHeight = height === 1 ? 1 : Math.max(1, Math.floor(height * 0.75));
222
- if (nextWidth === width && nextHeight === height)
223
- break;
224
- width = nextWidth;
225
- height = nextHeight;
309
+ scale *= 0.85;
226
310
  }
227
311
  return {
228
312
  ok: false,
@@ -65,6 +65,7 @@ async function executeVision(ctx, deps, raw, context) {
65
65
  if (!isFreePiSession(deps, context.sessionID)) {
66
66
  return fail("look_at_image is only available in free-pi sessions.");
67
67
  }
68
+ const startedAt = Date.now();
68
69
  const image = loadImage(ctx.location.directory, path);
69
70
  if (!image.ok)
70
71
  return fail(image.text);
@@ -113,10 +114,21 @@ async function executeVision(ctx, deps, raw, context) {
113
114
  if (typeof data?.text !== "string" || data.text === "") {
114
115
  return fail("The vision model returned no answer.");
115
116
  }
117
+ const elapsed = Date.now() - startedAt;
118
+ deps.log.info("look_at_image answered", {
119
+ path,
120
+ ms: elapsed,
121
+ resized: prepared.resized,
122
+ bytes: prepared.bytes,
123
+ size: `${prepared.width}x${prepared.height}`,
124
+ mime: prepared.mime,
125
+ model: data.model,
126
+ });
116
127
  return done(questionText(path, data.text), {
117
128
  ok: true,
118
129
  ...(typeof data.cost_usd === "number" ? { cost_usd: data.cost_usd } : {}),
119
130
  ...(typeof data.model === "string" ? { model: data.model } : {}),
131
+ elapsed_ms: elapsed,
120
132
  });
121
133
  }
122
134
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -41,9 +41,14 @@ export type PreparedImage =
41
41
  export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
42
42
  /** Refuse to read absurd files before decoding them in memory. */
43
43
  const MAX_SOURCE_BYTES = 80 * 1024 * 1024;
44
- /** pi's attachment limit: 2000 x 2000 is enough for screenshots and UI QA. */
45
- const MAX_DIMENSION = 2_000;
46
- const JPEG_QUALITIES = [80, 70, 55, 40] as const;
44
+ /**
45
+ * Only images above the provider's 5 MB limit are re-encoded. The CLI sends
46
+ * full-resolution files, and more pixels help OCR; the first JPEG quality that
47
+ * fits is kept instead of forcing an aggressive downscale.
48
+ */
49
+ const JPEG_QUALITIES = [92, 85, 75, 62, 50] as const;
50
+ /** Refuse to decode absurd canvases that could exhaust memory. */
51
+ const MAX_DECODE_DIMENSION = 8_000;
47
52
 
48
53
  const OUTSIDE = "look_at_image only reads images inside the project folder.";
49
54
 
@@ -143,6 +148,100 @@ export function loadImage(cwd: string, path: string): LoadedImage {
143
148
  }
144
149
  }
145
150
 
151
+ export type ImageSize = { readonly width: number; readonly height: number };
152
+
153
+ function pngSize(bytes: Buffer): ImageSize | undefined {
154
+ if (bytes.length < 24 || bytes.toString("latin1", 12, 16) !== "IHDR") {
155
+ return undefined;
156
+ }
157
+ const width = bytes.readUInt32BE(16);
158
+ const height = bytes.readUInt32BE(20);
159
+ return width > 0 && height > 0 ? { width, height } : undefined;
160
+ }
161
+
162
+ /** Walks the JPEG markers up to the first Start Of Frame segment. */
163
+ function jpegSize(bytes: Buffer): ImageSize | undefined {
164
+ let offset = 2;
165
+ while (offset + 9 < bytes.length) {
166
+ if (bytes[offset] !== 0xff) {
167
+ offset += 1;
168
+ continue;
169
+ }
170
+ const marker = bytes[offset + 1]!;
171
+ if (marker === 0xff) {
172
+ offset += 1;
173
+ continue;
174
+ }
175
+ if (
176
+ marker === 0xd8 ||
177
+ marker === 0xd9 ||
178
+ (marker >= 0xd0 && marker <= 0xd7)
179
+ ) {
180
+ offset += 2;
181
+ continue;
182
+ }
183
+ const length = bytes.readUInt16BE(offset + 2);
184
+ if (length < 2) return undefined;
185
+ const sof =
186
+ (marker >= 0xc0 && marker <= 0xc3) ||
187
+ (marker >= 0xc5 && marker <= 0xc7) ||
188
+ (marker >= 0xc9 && marker <= 0xcb) ||
189
+ (marker >= 0xcd && marker <= 0xcf);
190
+ if (sof) {
191
+ if (offset + 9 > bytes.length) return undefined;
192
+ const height = bytes.readUInt16BE(offset + 5);
193
+ const width = bytes.readUInt16BE(offset + 7);
194
+ return width > 0 && height > 0 ? { width, height } : undefined;
195
+ }
196
+ offset += 2 + length;
197
+ }
198
+ return undefined;
199
+ }
200
+
201
+ function webpSize(bytes: Buffer): ImageSize | undefined {
202
+ if (bytes.length < 30) return undefined;
203
+ const chunk = bytes.toString("latin1", 12, 16);
204
+ if (chunk === "VP8X") {
205
+ const width = 1 + (bytes[24]! | (bytes[25]! << 8) | (bytes[26]! << 16));
206
+ const height = 1 + (bytes[27]! | (bytes[28]! << 8) | (bytes[29]! << 16));
207
+ return { width, height };
208
+ }
209
+ if (chunk === "VP8 ") {
210
+ if (
211
+ bytes[23] !== 0x9d ||
212
+ bytes[24] !== 0x01 ||
213
+ bytes[25] !== 0x2a
214
+ ) {
215
+ return undefined;
216
+ }
217
+ const width = bytes.readUInt16LE(26) & 0x3fff;
218
+ const height = bytes.readUInt16LE(28) & 0x3fff;
219
+ return width > 0 && height > 0 ? { width, height } : undefined;
220
+ }
221
+ if (chunk === "VP8L") {
222
+ if (bytes[20] !== 0x2f) return undefined;
223
+ const bits = bytes.readUInt32LE(21);
224
+ return {
225
+ width: (bits & 0x3fff) + 1,
226
+ height: ((bits >>> 14) & 0x3fff) + 1,
227
+ };
228
+ }
229
+ return undefined;
230
+ }
231
+
232
+ /**
233
+ * Reads dimensions from the file header. This avoids decoding typical images
234
+ * with WASM just to decide whether they need to be resized.
235
+ */
236
+ export function imageSize(
237
+ bytes: Buffer,
238
+ mime: VisionMime,
239
+ ): ImageSize | undefined {
240
+ if (mime === "image/png") return pngSize(bytes);
241
+ if (mime === "image/jpeg") return jpegSize(bytes);
242
+ return webpSize(bytes);
243
+ }
244
+
146
245
  function unchanged(
147
246
  bytes: Buffer,
148
247
  mime: VisionMime,
@@ -169,9 +268,14 @@ type Candidate = {
169
268
  readonly bytes: number;
170
269
  };
171
270
 
271
+ function candidate(bytes: Buffer, mime: VisionMime): Candidate {
272
+ return { data: bytes.toString("base64"), mime, bytes: bytes.length };
273
+ }
274
+
172
275
  /**
173
- * Re-encodes the image at `width` x `height`, trying PNG and several JPEG
174
- * qualities, and returns the smallest candidate under the size limit.
276
+ * Re-encodes the image at `width` x `height`. It keeps the source format when
277
+ * possible and stops at the first JPEG quality that fits, so one call usually
278
+ * costs a single encode instead of five.
175
279
  */
176
280
  function encodeCandidate(
177
281
  photon: PhotonModule,
@@ -182,38 +286,33 @@ function encodeCandidate(
182
286
  ): Candidate | undefined {
183
287
  const resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3);
184
288
  try {
185
- const png = Buffer.from(resized.get_bytes());
186
- const candidates: Candidate[] = [
187
- { data: png.toString("base64"), mime: "image/png", bytes: png.length },
188
- ];
289
+ // Keep PNG screenshots crisp: JPEG artifacts blur UI text and transparency,
290
+ // and the vision model charges by pixels, not by encoded bytes.
291
+ if (preferred === "image/png") {
292
+ const png = Buffer.from(resized.get_bytes());
293
+ if (png.length <= MAX_IMAGE_BYTES) return candidate(png, "image/png");
294
+ }
295
+ if (preferred === "image/webp") {
296
+ try {
297
+ const webp = Buffer.from(resized.get_bytes_webp());
298
+ if (webp.length <= MAX_IMAGE_BYTES) return candidate(webp, "image/webp");
299
+ } catch {
300
+ // Older Photon builds may not expose WebP encoding.
301
+ }
302
+ }
189
303
  for (const quality of JPEG_QUALITIES) {
190
304
  const jpeg = Buffer.from(resized.get_bytes_jpeg(quality));
191
- candidates.push({
192
- data: jpeg.toString("base64"),
193
- mime: "image/jpeg",
194
- bytes: jpeg.length,
195
- });
196
- }
197
- const usable = candidates.filter(
198
- (candidate) => candidate.bytes <= MAX_IMAGE_BYTES,
199
- );
200
- if (usable.length === 0) return undefined;
201
- // Keep PNG for PNG screenshots as long as it fits: JPEG artifacts blur UI
202
- // text and transparency, and the vision model charges by pixels, not bytes.
203
- if (preferred === "image/png") {
204
- const pngCandidate = usable.find(
205
- (candidate) => candidate.mime === "image/png",
206
- );
207
- if (pngCandidate) return pngCandidate;
305
+ if (jpeg.length <= MAX_IMAGE_BYTES) return candidate(jpeg, "image/jpeg");
208
306
  }
209
- return usable.sort((a, b) => a.bytes - b.bytes)[0];
307
+ return undefined;
210
308
  } finally {
211
309
  resized.free();
212
310
  }
213
311
  }
214
312
 
215
313
  /**
216
- * Decodes the image and downscales it when it exceeds 2000 px or 5 MB.
314
+ * Sends the file untouched while it fits the provider's 5 MB limit. Only larger
315
+ * files are decoded, and then kept at the highest resolution/quality that fits.
217
316
  *
218
317
  * Photon is optional: if its WASM module cannot load, images that already fit
219
318
  * are still sent unchanged, while oversized ones fail with a clear message.
@@ -223,9 +322,15 @@ export async function prepareImage(
223
322
  mime: VisionMime,
224
323
  name: string,
225
324
  ): Promise<PreparedImage> {
325
+ // The normal path never touches WASM, so screenshots and phone photos under
326
+ // 5 MB keep their original resolution and add no local processing latency.
327
+ const size = imageSize(bytes, mime);
328
+ if (bytes.length <= MAX_IMAGE_BYTES) {
329
+ return unchanged(bytes, mime, size?.width ?? 0, size?.height ?? 0);
330
+ }
331
+
226
332
  const photo = await loadPhoton();
227
333
  if (!photo) {
228
- if (bytes.length <= MAX_IMAGE_BYTES) return unchanged(bytes, mime, 0, 0);
229
334
  return {
230
335
  ok: false,
231
336
  text: `${name} is larger than 5 MB and image resizing is unavailable in this OpenCode runtime. Resize it first.`,
@@ -236,7 +341,6 @@ export async function prepareImage(
236
341
  try {
237
342
  image = photo.PhotonImage.new_from_byteslice(new Uint8Array(bytes));
238
343
  } catch {
239
- if (bytes.length <= MAX_IMAGE_BYTES) return unchanged(bytes, mime, 0, 0);
240
344
  return {
241
345
  ok: false,
242
346
  text: `${name} could not be decoded, so it cannot be reduced below 5 MB.`,
@@ -246,26 +350,14 @@ export async function prepareImage(
246
350
  try {
247
351
  const originalWidth = image.get_width();
248
352
  const originalHeight = image.get_height();
249
- if (
250
- originalWidth <= MAX_DIMENSION &&
251
- originalHeight <= MAX_DIMENSION &&
252
- bytes.length <= MAX_IMAGE_BYTES
253
- ) {
254
- return unchanged(bytes, mime, originalWidth, originalHeight);
255
- }
256
-
257
- let width = originalWidth;
258
- let height = originalHeight;
259
- if (width > MAX_DIMENSION) {
260
- height = Math.max(1, Math.round((height * MAX_DIMENSION) / width));
261
- width = MAX_DIMENSION;
262
- }
263
- if (height > MAX_DIMENSION) {
264
- width = Math.max(1, Math.round((width * MAX_DIMENSION) / height));
265
- height = MAX_DIMENSION;
266
- }
353
+ const longest = Math.max(originalWidth, originalHeight);
354
+ let scale = longest > MAX_DECODE_DIMENSION
355
+ ? MAX_DECODE_DIMENSION / longest
356
+ : 1;
267
357
 
268
358
  while (true) {
359
+ const width = Math.max(1, Math.round(originalWidth * scale));
360
+ const height = Math.max(1, Math.round(originalHeight * scale));
269
361
  const best = encodeCandidate(photo, image, width, height, mime);
270
362
  if (best) {
271
363
  return {
@@ -282,11 +374,7 @@ export async function prepareImage(
282
374
  };
283
375
  }
284
376
  if (width === 1 && height === 1) break;
285
- const nextWidth = width === 1 ? 1 : Math.max(1, Math.floor(width * 0.75));
286
- const nextHeight = height === 1 ? 1 : Math.max(1, Math.floor(height * 0.75));
287
- if (nextWidth === width && nextHeight === height) break;
288
- width = nextWidth;
289
- height = nextHeight;
377
+ scale *= 0.85;
290
378
  }
291
379
 
292
380
  return {
@@ -96,6 +96,7 @@ async function executeVision(
96
96
  return fail("look_at_image is only available in free-pi sessions.");
97
97
  }
98
98
 
99
+ const startedAt = Date.now();
99
100
  const image = loadImage(ctx.location.directory, path);
100
101
  if (!image.ok) return fail(image.text);
101
102
 
@@ -150,10 +151,21 @@ async function executeVision(
150
151
  if (typeof data?.text !== "string" || data.text === "") {
151
152
  return fail("The vision model returned no answer.");
152
153
  }
154
+ const elapsed = Date.now() - startedAt;
155
+ deps.log.info("look_at_image answered", {
156
+ path,
157
+ ms: elapsed,
158
+ resized: prepared.resized,
159
+ bytes: prepared.bytes,
160
+ size: `${prepared.width}x${prepared.height}`,
161
+ mime: prepared.mime,
162
+ model: data.model,
163
+ });
153
164
  return done(questionText(path, data.text), {
154
165
  ok: true,
155
166
  ...(typeof data.cost_usd === "number" ? { cost_usd: data.cost_usd } : {}),
156
167
  ...(typeof data.model === "string" ? { model: data.model } : {}),
168
+ elapsed_ms: elapsed,
157
169
  });
158
170
  } catch (error) {
159
171
  if (error instanceof Error && error.name === "TimeoutError") {