@blackbelt-technology/pi-image-fit-extension 0.6.0 → 0.7.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
@@ -21,6 +21,44 @@ No native binary deps — `jimp` only. No `electron-rebuild` step, no
21
21
  platform-specific prebuilt downloads. Pure JS install on every supported
22
22
  pi target.
23
23
 
24
+ ## Second seam: the `context` event (any-origin images)
25
+
26
+ The `read`-tool seam above only covers images the agent opens through the
27
+ built-in `read` tool. Images that enter a session as **message content** —
28
+ `tool_result` screenshots (browser / MCP), user-pasted / attached images, and
29
+ images already persisted in a transcript — never pass through `read`, so a
30
+ second seam catches them.
31
+
32
+ The extension also hooks `pi.on("context", ...)`, fired before every LLM call
33
+ on a deep copy of the message list. For every message (regardless of role) it
34
+ walks the content blocks and, for each oversize `ImageContent`
35
+ (`{ type: "image", data, mimeType }`), resizes the bytes in-memory with jimp
36
+ and replaces `data` + `mimeType`. Because it runs on the in-flight copy every
37
+ turn, it also **rescues already-persisted oversize sessions on reload** — a
38
+ case no creation-time hook can cover (e.g. a session poisoned by an 8956×5080
39
+ browser screenshot that is under the byte limit but over the pixel limit).
40
+
41
+ How it stays cheap on the per-turn hot path:
42
+
43
+ - A **cheap header-probe gate** reads dimensions from the image header bytes
44
+ (PNG / JPEG / WEBP / GIF) and estimates size from the base64 length — no
45
+ full pixel decode. An image already within limits costs only this probe.
46
+ - An oversize image is hashed (SHA-256 of
47
+ `base64|mimeType|maxEdge|maxBytes|quality`) and its resized bytes cached in
48
+ a **bounded in-memory LRU** (~64 MiB, evicted by byte budget). The same
49
+ historical image reappearing every turn is served from the cache — no
50
+ re-encode.
51
+
52
+ The on-disk transcript is **never rewritten** — only pi's per-turn deep copy
53
+ is mutated, so the request sent to the model is always within limits while the
54
+ original bytes stay on disk. This seam reuses the same `PI_IMAGE_FIT_*`
55
+ thresholds and honors `PI_IMAGE_FIT_DISABLE` (which disables both seams). Any
56
+ per-block failure falls open (one `WARN`, block passed through unchanged) so a
57
+ single bad image never blocks a turn.
58
+
59
+ > **GIF animation:** an oversize `image/gif` is re-encoded to a static JPEG
60
+ > (first frame only) — same trade-off as the `read`-path seam.
61
+
24
62
  ## Install
25
63
 
26
64
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-image-fit-extension",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Pi extension that resizes oversize images at Read-time so they fit model byte and pixel ceilings.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/AGENTS.md CHANGED
@@ -4,7 +4,7 @@ Files in this directory. One row per source file.
4
4
 
5
5
  | File | Purpose |
6
6
  |------|---------|
7
- | `cache.ts` | SHA-256 temp-file cache under `os.tmpdir()/pi-image-fit/<session>/`. Exports `ROOT_DIR`, `cacheKey({absPath,mtimeMs,maxEdge,maxBytes,quality})`, `scopeFor(sessionScope)` (sanitizes `[^A-Za-z0-9_-]` → `_`, collapses runs, trims, falls back to `default`), `ensureDir`, `hasCached`, `cleanupSession`, `cleanupOrphans` (24 h sweep, injectable clock). See change: pi-image-fit-extension. |
8
- | `extension.ts` | Pi extension entry. Registers `pi.on("tool_call", ...)` gated on `toolName === "read"` + `isImagePath(input.path)`. Body wrapped in try/catch with fall-through (`event.input.path` reverts to original on any error; warns once via `console.warn`). `PI_IMAGE_FIT_DISABLE=1` skips registration entirely + logs one disabled-message line. Wires `session_shutdown` → `cleanupSession`. Fires `cleanupOrphans()` once on load. Emits one telemetry `console.log` per successful resize. See change: pi-image-fit-extension. |
7
+ | `cache.ts` | SHA-256 temp-file cache under `os.tmpdir()/pi-image-fit/<session>/`. Exports `ROOT_DIR`, `cacheKey({absPath,mtimeMs,maxEdge,maxBytes,quality})`, `scopeFor(sessionScope)` (sanitizes `[^A-Za-z0-9_-]` → `_`, collapses runs, trims, falls back to `default`), `ensureDir`, `hasCached`, `cleanupSession`, `cleanupOrphans` (24 h sweep, injectable clock). Also exports the context-seam in-memory content cache: `ContentCache` (bounded LRU, `keyFor(base64,mimeType,{maxEdge,maxBytes,quality})` SHA-256, `get`/`set`/`has`, byte-budget eviction, `bytes`/`size` observability) + `DEFAULT_CONTENT_CACHE_BUDGET` (64 MiB); never touches disk. See change: image-fit-tool-result-images. |
8
+ | `extension.ts` | Pi extension entry. Seam 1 `pi.on("tool_call")` gated on `toolName === "read"` + `isImagePath(input.path)`; try/catch fall-through, `session_shutdown` → `cleanupSession`, `cleanupOrphans()` once on load, one telemetry `console.log` per resize. Seam 2 `pi.on("context")` (guarded by `!config.disabled`) → `fitContextMessages(messages, config, ContentCache)` (exported): role-agnostic block walk, `Array.isArray(content)` guard, cheap header-probe gate → hash → cache → `resizeBuffer` on miss, mutates block `data`/`mimeType` in place, returns `{messages}` only on change else `undefined`; per-block try/catch fail-open (one WARN per bad block). `PI_IMAGE_FIT_DISABLE=1` skips BOTH seams. See change: image-fit-tool-result-images. |
9
9
  | `policy.ts` | Exports `readConfigFromEnv(): { disabled, maxEdge, maxBytes, quality }`. Env vars `PI_IMAGE_FIT_DISABLE` / `PI_IMAGE_FIT_MAX_EDGE` / `PI_IMAGE_FIT_MAX_BYTES` / `PI_IMAGE_FIT_QUALITY`. Defaults 1568 / 4194304 / 85. Invalid values fall back to default + emit one `[pi-image-fit] WARN ` line naming the variable. See change: pi-image-fit-extension. |
10
- | `resize.ts` | Exports `needsResize({bytes,maxBytes,dims,maxEdge})` predicate (long edge OR bytes), `outputFormatFor(srcPath)` (PNG-in → PNG-out, else JPEG), `isImagePath` regex `.png/.jpe?g/.webp/.gif`, `probeDims` (jimp lazy load), `resizeToFile` (long-edge `scaleToFit({w:maxEdge,h:maxEdge})` preserving aspect ratio, `getBuffer(JimpMime.png|jpeg, {quality})`). No `sharp` / `@napi-rs/image` / native deps. See change: pi-image-fit-extension. |
10
+ | `resize.ts` | File-path helpers: `needsResize({bytes,maxBytes,dims,maxEdge})` predicate (long edge OR bytes), `outputFormatFor(srcPath)` (PNG-in → PNG-out, else JPEG), `isImagePath` regex `.png/.jpe?g/.webp/.gif`, `probeDims` (jimp lazy load), `resizeToFile` (long-edge `scaleToFit({w:maxEdge,h:maxEdge})`, `getBuffer(JimpMime.png|jpeg,{quality})`). Buffer helpers (context seam): `estimateBytesFromBase64` (no decode), `probeDimsFromHeader(buf)` (PNG IHDR / JPEG SOF / WEBP VP8X·VP8·VP8L / GIF logical-screen, null on unparseable), `probeDimsFromBuffer(buf)` (jimp fallback), `outputFormatForMime(mime)` (`image/png`→png else jpeg), `resizeBuffer(buf,opts,"png"|"jpeg")` → `{data:Buffer,dims}` (no temp file). jimp only, no native deps. See change: image-fit-tool-result-images. |
package/src/cache.ts CHANGED
@@ -147,3 +147,105 @@ function stringifyErr(err: unknown): string {
147
147
  if (err instanceof Error) return err.message;
148
148
  return String(err);
149
149
  }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // Content-hash cache (context-seam path)
153
+ //
154
+ // A bounded in-memory LRU keyed by SHA-256 of the source bytes + policy, used
155
+ // by the `context` handler so a repeated oversize historical image is fitted
156
+ // once and served from memory on every later turn. Distinct from the temp-file
157
+ // cache above (which stays dedicated to the `read`-path seam and writes files);
158
+ // this one never touches the filesystem. Spec/Design: D3.
159
+ // ---------------------------------------------------------------------------
160
+
161
+ /** Default cache byte budget: ~64 MiB of resized image bytes. */
162
+ export const DEFAULT_CONTENT_CACHE_BUDGET = 64 * 1024 * 1024;
163
+
164
+ export interface ContentEntry {
165
+ /** base64-encoded resized image bytes. */
166
+ data: string;
167
+ /** mime type of the resized bytes (mime-derived output format). */
168
+ mimeType: string;
169
+ }
170
+
171
+ interface ContentPolicy {
172
+ maxEdge: number;
173
+ maxBytes: number;
174
+ quality: number;
175
+ }
176
+
177
+ /**
178
+ * Bounded, LRU content-hash cache. Keyed by SHA-256 of
179
+ * `${base64}|${mimeType}|${maxEdge}|${maxBytes}|${quality}` — `mimeType` is
180
+ * part of the key because the output format is mime-derived, so two blocks
181
+ * with identical bytes but different declared mime must not collide.
182
+ * Evicts least-recently-used entries once the summed resized-byte cost
183
+ * exceeds `byteBudget`.
184
+ */
185
+ export class ContentCache {
186
+ private readonly map = new Map<string, { entry: ContentEntry; cost: number }>();
187
+ private currentBytes = 0;
188
+
189
+ constructor(private readonly byteBudget: number = DEFAULT_CONTENT_CACHE_BUDGET) {}
190
+
191
+ /** Content hash for a block under the given policy. */
192
+ keyFor(base64: string, mimeType: string, p: ContentPolicy): string {
193
+ const material = [base64, mimeType, String(p.maxEdge), String(p.maxBytes), String(p.quality)].join("|");
194
+ return createHash("sha256").update(material).digest("hex");
195
+ }
196
+
197
+ has(key: string): boolean {
198
+ return this.map.has(key);
199
+ }
200
+
201
+ /** Look up, refreshing LRU recency on a hit. */
202
+ get(key: string): ContentEntry | undefined {
203
+ const hit = this.map.get(key);
204
+ if (!hit) return undefined;
205
+ // Refresh recency: delete + re-insert moves the key to the newest slot.
206
+ this.map.delete(key);
207
+ this.map.set(key, hit);
208
+ return hit.entry;
209
+ }
210
+
211
+ /** Insert (or replace), then evict LRU entries until within budget. */
212
+ set(key: string, entry: ContentEntry): void {
213
+ const cost = estimateBase64Bytes(entry.data);
214
+ const existing = this.map.get(key);
215
+ if (existing) {
216
+ this.currentBytes -= existing.cost;
217
+ this.map.delete(key);
218
+ }
219
+ this.map.set(key, { entry, cost });
220
+ this.currentBytes += cost;
221
+ // Evict least-recently-used (Map iteration order = oldest first) until
222
+ // within budget. Keep at least the just-inserted entry.
223
+ for (const oldest of this.map.keys()) {
224
+ if (this.currentBytes <= this.byteBudget || this.map.size <= 1) break;
225
+ const victim = this.map.get(oldest);
226
+ if (!victim) break;
227
+ this.currentBytes -= victim.cost;
228
+ this.map.delete(oldest);
229
+ }
230
+ }
231
+
232
+ /** Number of cached entries (test observability). */
233
+ get size(): number {
234
+ return this.map.size;
235
+ }
236
+
237
+ /** Summed resized-byte cost of cached entries (test observability). */
238
+ get bytes(): number {
239
+ return this.currentBytes;
240
+ }
241
+ }
242
+
243
+ /** Decoded byte size of a base64 string (LRU cost accounting). */
244
+ function estimateBase64Bytes(b64: string): number {
245
+ const len = b64.length;
246
+ if (len === 0) return 0;
247
+ let padding = 0;
248
+ if (b64.charCodeAt(len - 1) === 0x3d) padding++;
249
+ if (len > 1 && b64.charCodeAt(len - 2) === 0x3d) padding++;
250
+ return Math.floor((len * 3) / 4) - padding;
251
+ }
package/src/extension.ts CHANGED
@@ -13,19 +13,23 @@
13
13
  * Design: design.md.
14
14
  */
15
15
 
16
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
17
16
  import * as fs from "node:fs/promises";
18
17
  import * as path from "node:path";
19
- import { readConfigFromEnv, type ImageFitConfig } from "./policy.js";
18
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
20
19
  import {
21
- scopeFor,
20
+ type CacheScope,
21
+ ContentCache,
22
22
  cacheKey,
23
+ cleanupOrphans,
24
+ cleanupSession,
23
25
  ensureDir,
24
26
  hasCached,
25
- cleanupSession,
26
- cleanupOrphans,
27
- type CacheScope,
27
+ scopeFor,
28
28
  } from "./cache.js";
29
+ import { type ImageFitConfig, readConfigFromEnv } from "./policy.js";
30
+ // Namespace import so tests can `vi.spyOn(resize, "resizeBuffer")` on the
31
+ // `context`-seam path (ESM named imports are read-only live bindings).
32
+ import * as resize from "./resize.js";
29
33
  import {
30
34
  isImagePath,
31
35
  needsResize,
@@ -48,6 +52,29 @@ export default function imageFitExtension(pi: ExtensionAPI): void {
48
52
  /* already logged by cleanupOrphans */
49
53
  });
50
54
 
55
+ // Second interception seam: fit oversize ImageContent of any origin
56
+ // (tool_result / user-pasted / historical) before each LLM call. Runs
57
+ // every turn, so it is reload-safe (rescues already-persisted oversize
58
+ // sessions) but must stay cheap — the cheap-probe gate + content-hash
59
+ // cache keep the steady state to a header parse / hash + map lookup.
60
+ const contentCache = new ContentCache();
61
+ pi.on("context", async (event) => {
62
+ try {
63
+ // event.messages is pi's deep copy (safe to mutate in place); the same
64
+ // reference is returned when any block changed. The cast bridges pi's
65
+ // AgentMessage[] and our structural MessageLike[] view.
66
+ const patched = await fitContextMessages(event.messages as MessageLike[], config, contentCache);
67
+ return patched ? { messages: patched as unknown as typeof event.messages } : undefined;
68
+ } catch (err) {
69
+ // Last-resort catch — per-block failures are already isolated and
70
+ // logged inside fitContextMessages; reaching here means something
71
+ // above the block loop threw. Fail open: leave messages unmodified.
72
+ const msg = err instanceof Error ? err.message : String(err);
73
+ console.warn(`[pi-image-fit] WARN context handler error: ${msg}`);
74
+ return undefined;
75
+ }
76
+ });
77
+
51
78
  // Session scope is established lazily: the first tool_call we see
52
79
  // pulls sessionId from ctx.sessionManager (if available) or falls
53
80
  // back to `pid-<process.pid>`. We cache the scope per session id so
@@ -184,6 +211,127 @@ async function maybeResize(
184
211
  }
185
212
  }
186
213
 
214
+ /** Minimal structural view of a message block we care about. */
215
+ interface ImageBlockLike {
216
+ type: string;
217
+ data: string;
218
+ mimeType: string;
219
+ }
220
+
221
+ /** Minimal structural view of a message carrying content blocks. */
222
+ interface MessageLike {
223
+ content?: unknown;
224
+ }
225
+
226
+ /**
227
+ * Role-agnostic `context`-seam core: walk every message's content blocks,
228
+ * fit each oversize `image` block in place, and return the (mutated) message
229
+ * list only when at least one block changed — otherwise `undefined` so pi keeps
230
+ * the original list. Each block is isolated in its own try/catch (fail-open,
231
+ * single WARN per failed block) so one bad image never blocks its siblings.
232
+ *
233
+ * Exported for unit tests (spy on `resize.*` / `ContentCache.prototype.*`).
234
+ * Design: D4 (cheap-probe gate), D5 (role-agnostic traversal), D6 (fail-open).
235
+ */
236
+ export async function fitContextMessages(
237
+ messages: readonly MessageLike[],
238
+ config: ImageFitConfig,
239
+ cache: ContentCache,
240
+ ): Promise<MessageLike[] | undefined> {
241
+ let changed = false;
242
+ for (const message of messages) {
243
+ const content = message?.content;
244
+ // A UserMessage.content may be a plain string (no image) — skip it.
245
+ if (!Array.isArray(content)) continue;
246
+ if (await fitContentBlocks(content, config, cache)) changed = true;
247
+ }
248
+ return changed ? (messages as MessageLike[]) : undefined;
249
+ }
250
+
251
+ /**
252
+ * Fit every oversize image block in one message's content array (in place).
253
+ * Returns true if any block changed. Each block is isolated in its own
254
+ * try/catch so one bad image never blocks its siblings (fail-open, D6).
255
+ */
256
+ async function fitContentBlocks(
257
+ content: unknown[],
258
+ config: ImageFitConfig,
259
+ cache: ContentCache,
260
+ ): Promise<boolean> {
261
+ let changed = false;
262
+ for (const block of content) {
263
+ if (!isImageBlock(block)) continue;
264
+ try {
265
+ const fitted = await fitImageBlock(block, config, cache);
266
+ if (fitted) {
267
+ block.data = fitted.data;
268
+ block.mimeType = fitted.mimeType;
269
+ changed = true;
270
+ }
271
+ } catch (err) {
272
+ const msg = err instanceof Error ? err.message : String(err);
273
+ console.warn(`[pi-image-fit] WARN could not fit image block (${block.mimeType}): ${msg}`);
274
+ }
275
+ }
276
+ return changed;
277
+ }
278
+
279
+ function isImageBlock(block: unknown): block is ImageBlockLike {
280
+ return (
281
+ typeof block === "object" &&
282
+ block !== null &&
283
+ (block as { type?: unknown }).type === "image" &&
284
+ typeof (block as { data?: unknown }).data === "string" &&
285
+ typeof (block as { mimeType?: unknown }).mimeType === "string"
286
+ );
287
+ }
288
+
289
+ /**
290
+ * Fit a single oversize image block. Returns the replacement
291
+ * `{ data, mimeType }` on resize (or cache hit), or `null` when the block is
292
+ * already within limits (the steady-state path — no hash, no jimp decode).
293
+ * Throws only on an undecodable oversize block (caller logs one WARN).
294
+ */
295
+ async function fitImageBlock(
296
+ block: ImageBlockLike,
297
+ config: ImageFitConfig,
298
+ cache: ContentCache,
299
+ ): Promise<{ data: string; mimeType: string } | null> {
300
+ const buf = Buffer.from(block.data, "base64");
301
+ const bytes = resize.estimateBytesFromBase64(block.data);
302
+
303
+ // Cheap header dims; jimp fallback only if the header can't be parsed.
304
+ let dims = resize.probeDimsFromHeader(buf);
305
+ if (!dims) {
306
+ dims = await resize.probeDimsFromBuffer(buf);
307
+ if (!dims) {
308
+ // Undecodable. Only a candidate (oversize by bytes) is worth a WARN;
309
+ // a within-byte-limit block we cannot size is left as-is, silently.
310
+ if (bytes > config.maxBytes) throw new Error("undecodable image bytes");
311
+ return null;
312
+ }
313
+ }
314
+
315
+ if (!needsResize({ bytes, maxBytes: config.maxBytes, dims, maxEdge: config.maxEdge })) {
316
+ return null; // within limits — no hash, no cache, no decode
317
+ }
318
+
319
+ // Oversize candidate: hash → cache lookup → resize on miss.
320
+ const key = cache.keyFor(block.data, block.mimeType, config);
321
+ const hit = cache.get(key);
322
+ if (hit) return hit;
323
+
324
+ const { format, mime } = resize.outputFormatForMime(block.mimeType);
325
+ const { data } = await resize.resizeBuffer(
326
+ buf,
327
+ { maxEdge: config.maxEdge, quality: config.quality },
328
+ format,
329
+ );
330
+ const entry = { data: data.toString("base64"), mimeType: mime };
331
+ cache.set(key, entry);
332
+ return entry;
333
+ }
334
+
187
335
  function readSessionIdFromCtx(ctx: unknown): string {
188
336
  try {
189
337
  const sm = (ctx as { sessionManager?: { getSessionId?: () => string } } | undefined)?.sessionManager;
package/src/resize.ts CHANGED
@@ -9,9 +9,9 @@
9
9
  * ~50 ms jimp load cost.
10
10
  */
11
11
 
12
- import { JimpMime, Jimp } from "jimp";
13
12
  import * as fs from "node:fs/promises";
14
13
  import * as path from "node:path";
14
+ import { Jimp, JimpMime } from "jimp";
15
15
 
16
16
  export interface ImageDims {
17
17
  width: number;
@@ -49,6 +49,152 @@ export function outputFormatFor(srcPath: string): { ext: string; mime: string }
49
49
  return { ext: ".jpg", mime: JimpMime.jpeg };
50
50
  }
51
51
 
52
+ /**
53
+ * Mime-derived output format for the buffer (`context`-seam) path.
54
+ * - `image/png` → PNG output (lossless)
55
+ * - everything else (`image/jpeg`, `image/webp`, `image/gif`) → JPEG@quality
56
+ *
57
+ * Mirrors `outputFormatFor` but keyed on the declared mime type, since a
58
+ * `context`-seam `ImageContent` block carries a mimeType, not a file path.
59
+ * Spec/Design: D2.
60
+ */
61
+ export function outputFormatForMime(mime: string): { format: "png" | "jpeg"; mime: string } {
62
+ if (mime.trim().toLowerCase() === "image/png") {
63
+ return { format: "png", mime: JimpMime.png };
64
+ }
65
+ return { format: "jpeg", mime: JimpMime.jpeg };
66
+ }
67
+
68
+ /**
69
+ * Estimate decoded byte size from a base64 string length without decoding.
70
+ * Each 4 base64 chars encode 3 bytes; trailing `=` padding shrinks the last
71
+ * group. Cheap (no allocation, no decode) — the steady-state byte gate.
72
+ * Design: D4.
73
+ */
74
+ export function estimateBytesFromBase64(b64: string): number {
75
+ const len = b64.length;
76
+ if (len === 0) return 0;
77
+ let padding = 0;
78
+ if (b64.charCodeAt(len - 1) === 0x3d /* = */) padding++;
79
+ if (len > 1 && b64.charCodeAt(len - 2) === 0x3d) padding++;
80
+ return Math.floor((len * 3) / 4) - padding;
81
+ }
82
+
83
+ /**
84
+ * Cheap image-header dimension probe — parses PNG IHDR / JPEG SOF /
85
+ * WEBP VP8X|VP8|VP8L / GIF logical-screen from the leading bytes without a
86
+ * full pixel decode. Returns null when the header cannot be parsed (caller
87
+ * falls back to a bounded jimp decode). Design: D4.
88
+ */
89
+ export function probeDimsFromHeader(buf: Buffer): ImageDims | null {
90
+ try {
91
+ if (isPng(buf)) return pngDims(buf);
92
+ if (isGif(buf)) return gifDims(buf);
93
+ if (isWebp(buf)) return webpDims(buf);
94
+ if (buf.length >= 4 && buf[0] === 0xff && buf[1] === 0xd8) return jpegDims(buf);
95
+ return null;
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ function positiveDims(width: number, height: number): ImageDims | null {
102
+ return width > 0 && height > 0 ? { width, height } : null;
103
+ }
104
+
105
+ // PNG: 8-byte signature, then IHDR chunk (width/height at 16/20 BE).
106
+ function isPng(buf: Buffer): boolean {
107
+ return (
108
+ buf.length >= 24 &&
109
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
110
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a
111
+ );
112
+ }
113
+ function pngDims(buf: Buffer): ImageDims | null {
114
+ return positiveDims(buf.readUInt32BE(16), buf.readUInt32BE(20));
115
+ }
116
+
117
+ // GIF: "GIF87a"/"GIF89a", logical-screen width/height at 6/8 LE.
118
+ function isGif(buf: Buffer): boolean {
119
+ return buf.length >= 10 && buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46;
120
+ }
121
+ function gifDims(buf: Buffer): ImageDims | null {
122
+ return positiveDims(buf.readUInt16LE(6), buf.readUInt16LE(8));
123
+ }
124
+
125
+ // WEBP: "RIFF"...."WEBP", then a VP8X / VP8 / VP8L chunk.
126
+ function isWebp(buf: Buffer): boolean {
127
+ return (
128
+ buf.length >= 30 &&
129
+ buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
130
+ buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50
131
+ );
132
+ }
133
+ function webpDims(buf: Buffer): ImageDims | null {
134
+ const fourcc = buf.toString("ascii", 12, 16);
135
+ if (fourcc === "VP8X") {
136
+ return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 };
137
+ }
138
+ if (fourcc === "VP8 " && buf[23] === 0x9d && buf[24] === 0x01 && buf[25] === 0x2a) {
139
+ // Lossy: dims at offsets 26/28, masked to 14 bits.
140
+ return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
141
+ }
142
+ if (fourcc === "VP8L" && buf[20] === 0x2f) {
143
+ // Lossless: 14-bit (width-1) then 14-bit (height-1), little-endian bits.
144
+ const b1 = buf[21];
145
+ const b2 = buf[22];
146
+ const b3 = buf[23];
147
+ const b4 = buf[24];
148
+ return {
149
+ width: 1 + (((b2 & 0x3f) << 8) | b1),
150
+ height: 1 + (((b4 & 0x0f) << 10) | (b3 << 2) | ((b2 & 0xc0) >> 6)),
151
+ };
152
+ }
153
+ return null;
154
+ }
155
+
156
+ // JPEG: 0xFFD8, then scan segments for a Start-Of-Frame marker.
157
+ function jpegDims(buf: Buffer): ImageDims | null {
158
+ let i = 2;
159
+ while (i + 9 < buf.length) {
160
+ if (buf[i] !== 0xff) {
161
+ i++;
162
+ continue;
163
+ }
164
+ const marker = buf[i + 1];
165
+ // Padding fill byte / standalone markers with no length payload.
166
+ if (marker === 0xff) {
167
+ i++;
168
+ continue;
169
+ }
170
+ if (marker === 0xd8 || marker === 0xd9 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
171
+ i += 2;
172
+ continue;
173
+ }
174
+ // SOF0..SOF15 (baseline/progressive/etc.), excluding DHT/JPG/DAC.
175
+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
176
+ if (isSof) {
177
+ return positiveDims(buf.readUInt16BE(i + 7), buf.readUInt16BE(i + 5));
178
+ }
179
+ i += 2 + buf.readUInt16BE(i + 2);
180
+ }
181
+ return null;
182
+ }
183
+
184
+ /**
185
+ * Probe image dimensions from raw bytes via a full jimp decode.
186
+ * Buffer-path twin of `probeDims`. Returns null on undecodable input.
187
+ * Used only on the resize path / header-probe fallback (Design D4).
188
+ */
189
+ export async function probeDimsFromBuffer(buf: Buffer): Promise<ImageDims | null> {
190
+ try {
191
+ const img = await Jimp.fromBuffer(buf);
192
+ return { width: img.width, height: img.height };
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+
52
198
  /**
53
199
  * Image-extension allowlist used by the tool_call hook gate.
54
200
  * Spec: Tool-call mutation seam.
@@ -127,3 +273,25 @@ export async function resizeToFile(
127
273
  outExt,
128
274
  };
129
275
  }
276
+
277
+ /**
278
+ * Buffer-path twin of `resizeToFile`: decode `buf`, long-edge scale to
279
+ * `opts.maxEdge` (aspect-ratio preserving, never upscaling), and re-encode
280
+ * to `outFormat`. No temp file. Throws on any jimp failure; the caller
281
+ * catches and falls open per the fail-open contract. Design: D2.
282
+ */
283
+ export async function resizeBuffer(
284
+ buf: Buffer,
285
+ opts: ResizeOptions,
286
+ outFormat: "png" | "jpeg",
287
+ ): Promise<{ data: Buffer; dims: ImageDims }> {
288
+ const img = await Jimp.fromBuffer(buf);
289
+ if (Math.max(img.width, img.height) > opts.maxEdge) {
290
+ img.scaleToFit({ w: opts.maxEdge, h: opts.maxEdge });
291
+ }
292
+ const data =
293
+ outFormat === "png"
294
+ ? ((await img.getBuffer(JimpMime.png)) as unknown as Buffer)
295
+ : ((await img.getBuffer(JimpMime.jpeg, { quality: opts.quality })) as unknown as Buffer);
296
+ return { data, dims: { width: img.width, height: img.height } };
297
+ }