@blackbelt-technology/pi-image-fit-extension 0.7.0 → 0.9.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
@@ -93,6 +93,8 @@ extension is a no-op.
93
93
  threshold.
94
94
  - `PI_IMAGE_FIT_QUALITY=<1-100>` — JPEG output quality. Ignored for
95
95
  PNG-in → PNG-out path (always lossless).
96
+ - `PI_IMAGE_FIT_QUIET` — truthy (`1`, `true`, `yes`, `on`) drops every
97
+ telemetry and warning line while leaving resizing untouched.
96
98
 
97
99
  Invalid values fall back to the documented default and log a single
98
100
  warning line naming the variable.
@@ -108,6 +110,19 @@ Cache file extension matches the chosen output format.
108
110
 
109
111
  ## Telemetry
110
112
 
113
+ Diagnostics go through pi's own UI when the session has one
114
+ (`ctx.hasUI`): the per-resize line replaces the `pi-image-fit` footer status
115
+ (`ctx.ui.setStatus`), so it never adds a notification or dashboard transcript
116
+ row; warnings use `ctx.ui.notify(…, "warning")`. Hosts without a UI — print
117
+ mode, JSON mode, unit tests — keep `console.log` / `console.warn`. Writing to
118
+ stdio in a TUI session would land the line in the user's prompt, where it has
119
+ to be cleared before typing.
120
+
121
+ Messages raised while the extension loads (invalid env values, the
122
+ `PI_IMAGE_FIT_DISABLE` notice) are held until `session_start` and then
123
+ delivered the same way. The most recent session context always wins, so after
124
+ `/reload`, a new session or a fork the output follows the live session.
125
+
111
126
  On a successful resize the extension emits exactly one line:
112
127
 
113
128
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-image-fit-extension",
3
- "version": "0.7.0",
3
+ "version": "0.9.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": {
@@ -26,24 +26,22 @@
26
26
  "files": [
27
27
  "src/",
28
28
  "!src/__tests__",
29
- "README.md"
29
+ "README.md",
30
+ "!**/AGENTS.md",
31
+ "!**/*.AGENTS.md"
30
32
  ],
31
33
  "dependencies": {
32
34
  "jimp": "^1.6.1"
33
35
  },
34
36
  "peerDependencies": {
35
- "@earendil-works/pi-coding-agent": "*",
36
- "@mariozechner/pi-coding-agent": "*"
37
+ "@earendil-works/pi-coding-agent": ">=1.0.0"
37
38
  },
38
39
  "peerDependenciesMeta": {
39
40
  "@earendil-works/pi-coding-agent": {
40
41
  "optional": true
41
- },
42
- "@mariozechner/pi-coding-agent": {
43
- "optional": true
44
42
  }
45
43
  },
46
44
  "devDependencies": {
47
- "@earendil-works/pi-coding-agent": "*"
45
+ "@earendil-works/pi-coding-agent": "^1.0.0"
48
46
  }
49
47
  }
package/src/cache.ts CHANGED
@@ -21,6 +21,7 @@ import { createHash } from "node:crypto";
21
21
  import * as fs from "node:fs/promises";
22
22
  import * as os from "node:os";
23
23
  import * as path from "node:path";
24
+ import * as log from "./log.js";
24
25
 
25
26
  export const ROOT_DIR = path.join(os.tmpdir(), "pi-image-fit");
26
27
 
@@ -99,7 +100,7 @@ export async function hasCached(scope: CacheScope, hash: string, ext: string): P
99
100
  */
100
101
  export async function cleanupSession(
101
102
  scope: CacheScope,
102
- warn: (msg: string) => void = (msg) => console.warn(msg),
103
+ warn: (msg: string) => void = log.warn,
103
104
  ): Promise<void> {
104
105
  try {
105
106
  await fs.rm(scope.dir, { recursive: true, force: true });
@@ -118,7 +119,7 @@ export async function cleanupSession(
118
119
  export async function cleanupOrphans(
119
120
  maxAgeMs: number = 24 * 60 * 60 * 1000,
120
121
  now: () => number = Date.now,
121
- warn: (msg: string) => void = (msg) => console.warn(msg),
122
+ warn: (msg: string) => void = log.warn,
122
123
  ): Promise<void> {
123
124
  let entries: string[];
124
125
  try {
package/src/env.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Shared environment-variable parsing. Lives apart from `policy.ts` so the
3
+ * diagnostics sink (`log.ts`) can use it without an import cycle
4
+ * (`policy.ts` itself logs through `log.ts`).
5
+ */
6
+
7
+ const TRUTHY = new Set(["1", "true", "yes", "on"]);
8
+
9
+ /** Boolean env var: `1` / `true` / `yes` / `on`, any case, surrounding space ignored. */
10
+ export function parseBool(raw: string | undefined): boolean {
11
+ if (!raw) return false;
12
+ return TRUTHY.has(raw.trim().toLowerCase());
13
+ }
package/src/extension.ts CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  hasCached,
27
27
  scopeFor,
28
28
  } from "./cache.js";
29
+ import * as log from "./log.js";
29
30
  import { type ImageFitConfig, readConfigFromEnv } from "./policy.js";
30
31
  // Namespace import so tests can `vi.spyOn(resize, "resizeBuffer")` on the
31
32
  // `context`-seam path (ESM named imports are read-only live bindings).
@@ -39,10 +40,18 @@ import {
39
40
  } from "./resize.js";
40
41
 
41
42
  export default function imageFitExtension(pi: ExtensionAPI): void {
43
+ // No ctx exists yet: hold load-time diagnostics (config warnings, the
44
+ // disabled notice) until session_start, so they reach pi's UI instead of
45
+ // the TUI prompt line.
46
+ log.deferUntilContext();
47
+ pi.on("session_start", async (_event, ctx) => {
48
+ log.useUiSink(ctx);
49
+ });
50
+
42
51
  const config: ImageFitConfig = readConfigFromEnv();
43
52
 
44
53
  if (config.disabled) {
45
- console.log("[pi-image-fit] disabled via PI_IMAGE_FIT_DISABLE");
54
+ log.info("[pi-image-fit] disabled via PI_IMAGE_FIT_DISABLE");
46
55
  return;
47
56
  }
48
57
 
@@ -58,7 +67,8 @@ export default function imageFitExtension(pi: ExtensionAPI): void {
58
67
  // sessions) but must stay cheap — the cheap-probe gate + content-hash
59
68
  // cache keep the steady state to a header parse / hash + map lookup.
60
69
  const contentCache = new ContentCache();
61
- pi.on("context", async (event) => {
70
+ pi.on("context", async (event, ctx) => {
71
+ log.useUiSink(ctx);
62
72
  try {
63
73
  // event.messages is pi's deep copy (safe to mutate in place); the same
64
74
  // reference is returned when any block changed. The cast bridges pi's
@@ -70,7 +80,7 @@ export default function imageFitExtension(pi: ExtensionAPI): void {
70
80
  // logged inside fitContextMessages; reaching here means something
71
81
  // above the block loop threw. Fail open: leave messages unmodified.
72
82
  const msg = err instanceof Error ? err.message : String(err);
73
- console.warn(`[pi-image-fit] WARN context handler error: ${msg}`);
83
+ log.warn(`[pi-image-fit] WARN context handler error: ${msg}`);
74
84
  return undefined;
75
85
  }
76
86
  });
@@ -91,6 +101,7 @@ export default function imageFitExtension(pi: ExtensionAPI): void {
91
101
  }
92
102
 
93
103
  pi.on("tool_call", async (event, ctx) => {
104
+ log.useUiSink(ctx);
94
105
  // Fast-path gates. None of these touch the filesystem.
95
106
  if (event.toolName !== "read") return;
96
107
  const srcPath = event.input?.path;
@@ -105,7 +116,7 @@ export default function imageFitExtension(pi: ExtensionAPI): void {
105
116
  // fall through; event.input.path is whatever the deepest mutation
106
117
  // left it (callee responsibility to restore on partial failure).
107
118
  const msg = err instanceof Error ? err.message : String(err);
108
- console.warn(`[pi-image-fit] WARN unexpected error for ${srcPath}: ${msg}`);
119
+ log.warn(`[pi-image-fit] WARN unexpected error for ${srcPath}: ${msg}`);
109
120
  }
110
121
  });
111
122
 
@@ -151,7 +162,7 @@ async function maybeResize(
151
162
  if (!dims) {
152
163
  // Jimp couldn't decode — likely corrupted or unsupported variant.
153
164
  // Fall through to built-in Read which will surface the file as-is.
154
- console.warn(`[pi-image-fit] WARN could not decode ${srcPath}; passing through original`);
165
+ log.warn(`[pi-image-fit] WARN could not decode ${srcPath}; passing through original`);
155
166
  return;
156
167
  }
157
168
 
@@ -184,7 +195,7 @@ async function maybeResize(
184
195
  await ensureDir(scope.dir);
185
196
  } catch (err) {
186
197
  const msg = err instanceof Error ? err.message : String(err);
187
- console.warn(`[pi-image-fit] WARN could not create cache dir ${scope.dir}: ${msg}; passing through original`);
198
+ log.warn(`[pi-image-fit] WARN could not create cache dir ${scope.dir}: ${msg}; passing through original`);
188
199
  return;
189
200
  }
190
201
 
@@ -194,7 +205,7 @@ async function maybeResize(
194
205
  quality: config.quality,
195
206
  });
196
207
  event.input.path = dstPath;
197
- console.log(
208
+ log.info(
198
209
  `[pi-image-fit] ${srcPath} ${result.srcDims.width}\u00d7${result.srcDims.height} ${formatBytes(bytes)} \u2192 ${result.dstDims.width}\u00d7${result.dstDims.height} ${formatBytes(result.dstBytes)}`,
199
210
  );
200
211
  } catch (err) {
@@ -206,7 +217,7 @@ async function maybeResize(
206
217
  } catch {
207
218
  /* ignore */
208
219
  }
209
- console.warn(`[pi-image-fit] WARN resize failed for ${srcPath}: ${msg}; passing through original`);
220
+ log.warn(`[pi-image-fit] WARN resize failed for ${srcPath}: ${msg}; passing through original`);
210
221
  // event.input.path was not mutated yet — original path stands.
211
222
  }
212
223
  }
@@ -270,7 +281,7 @@ async function fitContentBlocks(
270
281
  }
271
282
  } catch (err) {
272
283
  const msg = err instanceof Error ? err.message : String(err);
273
- console.warn(`[pi-image-fit] WARN could not fit image block (${block.mimeType}): ${msg}`);
284
+ log.warn(`[pi-image-fit] WARN could not fit image block (${block.mimeType}): ${msg}`);
274
285
  }
275
286
  }
276
287
  return changed;
package/src/log.ts ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The extension's single diagnostics sink.
3
+ *
4
+ * Why this module exists: pi renders an extension's stdio inside the TUI, so a
5
+ * bare `console.log` lands in the user's prompt line — they have to clear it
6
+ * before typing. pi's documented channels for extension output are
7
+ * `ctx.ui.setStatus` (footer line) and `ctx.ui.notify` (transient message).
8
+ *
9
+ * Routing, in order:
10
+ * 1. `PI_IMAGE_FIT_QUIET` truthy → drop the message.
11
+ * 2. Held (load time, see `deferUntilContext`) → buffer until the first ctx.
12
+ * 3. Latest ctx has a real UI (`hasUI === true`):
13
+ * info → `ui.setStatus("pi-image-fit", msg)` (no dashboard transcript row),
14
+ * or `ui.notify(msg, "info")` when the host has no setStatus;
15
+ * warn → `ui.notify(msg, "warning")`.
16
+ * 4. Otherwise → console (print/JSON hosts, unit tests).
17
+ *
18
+ * Keeping the decision here means `extension.ts`, `policy.ts` and `cache.ts`
19
+ * never name an output channel, and their injectable `warn` seams stay intact.
20
+ * See openspec change: image-fit-quiet-tui.
21
+ */
22
+
23
+ import { parseBool } from "./env.js";
24
+
25
+ export type Sink = (msg: string) => void;
26
+
27
+ type Level = "info" | "warning";
28
+
29
+ /** Footer slot the info telemetry occupies in pi's status line. */
30
+ export const STATUS_KEY = "pi-image-fit";
31
+
32
+ /** Upper bound on load-time messages held before the first ctx. */
33
+ export const MAX_HELD = 50;
34
+
35
+ interface UiChannel {
36
+ ui: object;
37
+ notify: (msg: string, level?: Level) => void;
38
+ setStatus?: (key: string, text: string | undefined) => void;
39
+ }
40
+
41
+ let channel: UiChannel | null = null;
42
+ let held: Array<{ msg: string; level: Level }> | null = null;
43
+
44
+ function quiet(): boolean {
45
+ return parseBool(process.env.PI_IMAGE_FIT_QUIET);
46
+ }
47
+
48
+ /**
49
+ * Read the host UI off an event ctx. `null` when the host has no real UI
50
+ * (pi's print/JSON `noOpUIContext` still has a no-op `notify`, so `hasUI` is
51
+ * the only reliable signal); `undefined` when the ctx is stale (pi >=0.84
52
+ * throws from its getters after `invalidate()`), meaning "keep what we have".
53
+ */
54
+ function readChannel(ctx: unknown): UiChannel | null | undefined {
55
+ try {
56
+ const c = ctx as { hasUI?: unknown; ui?: Record<string, unknown> } | undefined;
57
+ if (c?.hasUI !== true) return null;
58
+ const ui = c.ui;
59
+ if (!ui || typeof ui.notify !== "function") return null;
60
+ return {
61
+ ui,
62
+ notify: ui.notify as UiChannel["notify"],
63
+ setStatus: typeof ui.setStatus === "function" ? (ui.setStatus as UiChannel["setStatus"]) : undefined,
64
+ };
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Point the sink at the latest event ctx. Called from every handler because
72
+ * the factory runs before any ctx exists and pi replaces ctx on reload /
73
+ * newSession / fork / switch (latest wins). The first call also delivers any
74
+ * messages held since `deferUntilContext()`, through this ctx's channel.
75
+ */
76
+ export function useUiSink(ctx: unknown): void {
77
+ const next = readChannel(ctx);
78
+ if (next !== undefined) channel = next;
79
+ if (held) {
80
+ const pending = held;
81
+ held = null;
82
+ for (const { msg, level } of pending) emit(msg, level);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Hold messages until the first `useUiSink` call. The extension factory calls
88
+ * this first so load-time warnings reach pi's UI instead of the TUI prompt.
89
+ * Bounded: beyond `MAX_HELD` the oldest message is dropped.
90
+ */
91
+ export function deferUntilContext(): void {
92
+ held = [];
93
+ }
94
+
95
+ /** Test seam: forget the UI channel and any held messages. */
96
+ export function resetUiSink(): void {
97
+ channel = null;
98
+ held = null;
99
+ }
100
+
101
+ function toUi(c: UiChannel, msg: string, level: Level): void {
102
+ if (level === "info" && c.setStatus) c.setStatus.call(c.ui, STATUS_KEY, msg);
103
+ else c.notify.call(c.ui, msg, level);
104
+ }
105
+
106
+ function emit(msg: string, level: Level): void {
107
+ if (quiet()) return;
108
+ if (held) {
109
+ if (held.length >= MAX_HELD) held.shift();
110
+ held.push({ msg, level });
111
+ return;
112
+ }
113
+ if (channel) {
114
+ try {
115
+ toUi(channel, msg, level);
116
+ return;
117
+ } catch {
118
+ // A failing UI channel must never break a resize: fall through to console.
119
+ }
120
+ }
121
+ if (level === "warning") console.warn(msg);
122
+ else console.log(msg);
123
+ }
124
+
125
+ /** Telemetry: one line per successful resize. */
126
+ export const info: Sink = (msg) => emit(msg, "info");
127
+
128
+ /** Recoverable failure: the extension always falls through to the original image. */
129
+ export const warn: Sink = (msg) => emit(msg, "warning");
package/src/policy.ts CHANGED
@@ -14,6 +14,9 @@
14
14
  * diminishing returns >90.
15
15
  */
16
16
 
17
+ import { parseBool } from "./env.js";
18
+ import * as log from "./log.js";
19
+
17
20
  export interface ImageFitConfig {
18
21
  /** When true, extension registers no hooks. */
19
22
  disabled: boolean;
@@ -32,13 +35,6 @@ export const DEFAULTS: Readonly<ImageFitConfig> = Object.freeze({
32
35
  quality: 85,
33
36
  });
34
37
 
35
- const TRUTHY = new Set(["1", "true", "yes", "on"]);
36
-
37
- function parseBool(raw: string | undefined): boolean {
38
- if (!raw) return false;
39
- return TRUTHY.has(raw.trim().toLowerCase());
40
- }
41
-
42
38
  interface ParseRules {
43
39
  min: number;
44
40
  max: number;
@@ -78,7 +74,7 @@ export interface ReadConfigOptions {
78
74
  */
79
75
  export function readConfigFromEnv(opts: ReadConfigOptions = {}): ImageFitConfig {
80
76
  const env = opts.env ?? process.env;
81
- const warn = opts.warn ?? ((msg: string) => console.warn(msg));
77
+ const warn = opts.warn ?? log.warn;
82
78
 
83
79
  const disabled = parseBool(env.PI_IMAGE_FIT_DISABLE);
84
80
  const maxEdge = parsePositiveInt(
package/src/AGENTS.md DELETED
@@ -1,10 +0,0 @@
1
- # DOX — packages/image-fit-extension/src
2
-
3
- Files in this directory. One row per source file.
4
-
5
- | File | Purpose |
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). 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
- | `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` | 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. |