@blackbelt-technology/pi-image-fit-extension 0.5.4
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 +94 -0
- package/package.json +49 -0
- package/src/cache.ts +149 -0
- package/src/extension.ts +204 -0
- package/src/policy.ts +107 -0
- package/src/resize.ts +129 -0
package/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# @blackbelt-technology/pi-image-fit-extension
|
|
2
|
+
|
|
3
|
+
Pi extension that resizes oversize images at Read-time so they fit model
|
|
4
|
+
byte and pixel ceilings.
|
|
5
|
+
|
|
6
|
+
The extension hooks `pi.on("tool_call", ...)`. When the agent runs the
|
|
7
|
+
built-in `read` tool with an image path (`.png`, `.jpg`, `.jpeg`, `.webp`,
|
|
8
|
+
`.gif`), the extension:
|
|
9
|
+
|
|
10
|
+
1. Stats the file and (lazily) probes dimensions via [jimp](https://github.com/jimp-dev/jimp).
|
|
11
|
+
2. If the image already fits both thresholds, leaves `event.input.path`
|
|
12
|
+
untouched — built-in Read sees the original bytes, no temp file, no
|
|
13
|
+
telemetry.
|
|
14
|
+
3. Otherwise, re-encodes the image (long-edge scaled, aspect-ratio
|
|
15
|
+
preserved) into a session-scoped temp file under
|
|
16
|
+
`os.tmpdir()/pi-image-fit/<session>/<sha256>.<ext>` and mutates
|
|
17
|
+
`event.input.path` to point at it. Built-in Read attaches the smaller
|
|
18
|
+
image to the agent's context window.
|
|
19
|
+
|
|
20
|
+
No native binary deps — `jimp` only. No `electron-rebuild` step, no
|
|
21
|
+
platform-specific prebuilt downloads. Pure JS install on every supported
|
|
22
|
+
pi target.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pi install @blackbelt-technology/pi-image-fit-extension
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The next pi session loads the extension. No dashboard or other workspace
|
|
31
|
+
package required.
|
|
32
|
+
|
|
33
|
+
## Default thresholds
|
|
34
|
+
|
|
35
|
+
| Setting | Default | Env var |
|
|
36
|
+
| --- | --- | --- |
|
|
37
|
+
| Long-edge pixels | 1568 | `PI_IMAGE_FIT_MAX_EDGE` |
|
|
38
|
+
| Byte size | 4,194,304 (4 MiB) | `PI_IMAGE_FIT_MAX_BYTES` |
|
|
39
|
+
| JPEG quality | 85 | `PI_IMAGE_FIT_QUALITY` |
|
|
40
|
+
| Kill switch | off | `PI_IMAGE_FIT_DISABLE` |
|
|
41
|
+
|
|
42
|
+
Resize triggers when **either** the byte size **or** the long edge
|
|
43
|
+
exceeds its threshold. When both are at or below their thresholds, the
|
|
44
|
+
extension is a no-op.
|
|
45
|
+
|
|
46
|
+
## Environment variables
|
|
47
|
+
|
|
48
|
+
- `PI_IMAGE_FIT_DISABLE` — truthy (`1`, `true`, `yes`, case-insensitive)
|
|
49
|
+
skips the `pi.on("tool_call", ...)` registration entirely; the
|
|
50
|
+
extension logs a single disabled-message line on load and does nothing
|
|
51
|
+
else.
|
|
52
|
+
- `PI_IMAGE_FIT_MAX_EDGE=<px>` — positive integer; override the
|
|
53
|
+
long-edge threshold.
|
|
54
|
+
- `PI_IMAGE_FIT_MAX_BYTES=<bytes>` — positive integer; override the byte
|
|
55
|
+
threshold.
|
|
56
|
+
- `PI_IMAGE_FIT_QUALITY=<1-100>` — JPEG output quality. Ignored for
|
|
57
|
+
PNG-in → PNG-out path (always lossless).
|
|
58
|
+
|
|
59
|
+
Invalid values fall back to the documented default and log a single
|
|
60
|
+
warning line naming the variable.
|
|
61
|
+
|
|
62
|
+
## Output format
|
|
63
|
+
|
|
64
|
+
Format-adaptive:
|
|
65
|
+
|
|
66
|
+
- `.png` source → PNG output (lossless re-encode preserves transparency).
|
|
67
|
+
- everything else → JPEG at the configured quality.
|
|
68
|
+
|
|
69
|
+
Cache file extension matches the chosen output format.
|
|
70
|
+
|
|
71
|
+
## Telemetry
|
|
72
|
+
|
|
73
|
+
On a successful resize the extension emits exactly one line:
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
[pi-image-fit] <path> <srcW>×<srcH> <srcBytes>B → <dstW>×<dstH> <dstBytes>B
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
No log on already-small pass-throughs, on non-image reads, or on
|
|
80
|
+
non-`read` tool calls. Failures log a single `[pi-image-fit] WARN ...`
|
|
81
|
+
line and fall through to the original path (the agent's Read behaves
|
|
82
|
+
exactly as if the extension were not installed).
|
|
83
|
+
|
|
84
|
+
## Caveat: silent quality loss
|
|
85
|
+
|
|
86
|
+
A 4K screenshot squashed to 1568 px may lose fine text. The agent has no
|
|
87
|
+
way to tell that resize fired beyond the console log line. If pixel
|
|
88
|
+
perfect Read matters for a workflow, set `PI_IMAGE_FIT_DISABLE=1` in
|
|
89
|
+
that environment.
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
MIT. Part of the [pi-agent-dashboard](https://github.com/BlackBeltTechnology/pi-agent-dashboard)
|
|
94
|
+
monorepo; versions move in lockstep with the rest of the workspace.
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@blackbelt-technology/pi-image-fit-extension",
|
|
3
|
+
"version": "0.5.4",
|
|
4
|
+
"description": "Pi extension that resizes oversize images at Read-time so they fit model byte and pixel ceilings.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
|
|
9
|
+
"directory": "packages/image-fit-extension"
|
|
10
|
+
},
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"pi-package",
|
|
17
|
+
"pi-extension",
|
|
18
|
+
"image",
|
|
19
|
+
"resize"
|
|
20
|
+
],
|
|
21
|
+
"pi": {
|
|
22
|
+
"extensions": [
|
|
23
|
+
"src/extension.ts"
|
|
24
|
+
]
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src/",
|
|
28
|
+
"!src/__tests__",
|
|
29
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"jimp": "^1.6.1"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
36
|
+
"@mariozechner/pi-coding-agent": "*"
|
|
37
|
+
},
|
|
38
|
+
"peerDependenciesMeta": {
|
|
39
|
+
"@earendil-works/pi-coding-agent": {
|
|
40
|
+
"optional": true
|
|
41
|
+
},
|
|
42
|
+
"@mariozechner/pi-coding-agent": {
|
|
43
|
+
"optional": true
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/cache.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Temp-file cache for pi-image-fit.
|
|
3
|
+
*
|
|
4
|
+
* Spec: Temp-file cache.
|
|
5
|
+
*
|
|
6
|
+
* Layout:
|
|
7
|
+
* <os.tmpdir()>/pi-image-fit/<sessionScope>/<hash><ext>
|
|
8
|
+
*
|
|
9
|
+
* <ext> is chosen by the resize step per the format-adaptive policy
|
|
10
|
+
* (`.png` for PNG inputs, `.jpg` for other inputs). The cache helpers
|
|
11
|
+
* are extension-agnostic — callers pass the extension explicitly.
|
|
12
|
+
*
|
|
13
|
+
* Cache key = SHA-256 of `${absPath}|${mtimeMs}|${maxEdge}|${maxBytes}|${quality}`.
|
|
14
|
+
* Session scope = sessionId when available, else `pid-<process.pid>`.
|
|
15
|
+
* Cleanup: full session-scope directory removed on session_shutdown;
|
|
16
|
+
* orphan sweep on extension load removes any dir under pi-image-fit/
|
|
17
|
+
* whose mtime is older than 24 h.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import * as fs from "node:fs/promises";
|
|
22
|
+
import * as os from "node:os";
|
|
23
|
+
import * as path from "node:path";
|
|
24
|
+
|
|
25
|
+
export const ROOT_DIR = path.join(os.tmpdir(), "pi-image-fit");
|
|
26
|
+
|
|
27
|
+
export interface CacheKeyInput {
|
|
28
|
+
absPath: string;
|
|
29
|
+
/** Source file's mtime in ms (Date.getTime() or stat.mtimeMs). */
|
|
30
|
+
mtimeMs: number;
|
|
31
|
+
maxEdge: number;
|
|
32
|
+
maxBytes: number;
|
|
33
|
+
quality: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Pure deterministic hash of the inputs that affect output bytes.
|
|
38
|
+
* Identical inputs → identical hash.
|
|
39
|
+
*/
|
|
40
|
+
export function cacheKey(input: CacheKeyInput): string {
|
|
41
|
+
const material = [
|
|
42
|
+
input.absPath,
|
|
43
|
+
String(input.mtimeMs),
|
|
44
|
+
String(input.maxEdge),
|
|
45
|
+
String(input.maxBytes),
|
|
46
|
+
String(input.quality),
|
|
47
|
+
].join("|");
|
|
48
|
+
return createHash("sha256").update(material).digest("hex");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface CacheScope {
|
|
52
|
+
/** Absolute path of this session's cache directory. */
|
|
53
|
+
dir: string;
|
|
54
|
+
/**
|
|
55
|
+
* Absolute path of the cache file for the given key.
|
|
56
|
+
* `ext` MUST include the leading dot (e.g. `.png`, `.jpg`).
|
|
57
|
+
*/
|
|
58
|
+
filePath(hash: string, ext: string): string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function scopeFor(sessionScope: string): CacheScope {
|
|
62
|
+
const dir = path.join(ROOT_DIR, sanitize(sessionScope));
|
|
63
|
+
return {
|
|
64
|
+
dir,
|
|
65
|
+
filePath: (hash, ext) => path.join(dir, `${hash}${ext}`),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function sanitize(s: string): string {
|
|
70
|
+
// Drop anything not [A-Za-z0-9_-] (notably `.` and `/`, which would
|
|
71
|
+
// allow path traversal); collapse runs of `_`; trim leading/trailing
|
|
72
|
+
// `_`; fall back to "default" when nothing usable remains.
|
|
73
|
+
let out = s.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
74
|
+
out = out.replace(/_+/g, "_").replace(/^_+|_+$/g, "");
|
|
75
|
+
return out.slice(0, 96) || "default";
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Best-effort: ensure the directory exists. */
|
|
79
|
+
export async function ensureDir(dir: string): Promise<void> {
|
|
80
|
+
await fs.mkdir(dir, { recursive: true });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Returns true if a cache file exists for `hash` with the given extension.
|
|
85
|
+
* Any fs error is treated as "no cache hit" — the caller will rebuild.
|
|
86
|
+
*/
|
|
87
|
+
export async function hasCached(scope: CacheScope, hash: string, ext: string): Promise<boolean> {
|
|
88
|
+
try {
|
|
89
|
+
const st = await fs.stat(scope.filePath(hash, ext));
|
|
90
|
+
return st.isFile();
|
|
91
|
+
} catch {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Remove this session's cache directory.
|
|
98
|
+
* Best-effort; errors are reported via `warn` and swallowed.
|
|
99
|
+
*/
|
|
100
|
+
export async function cleanupSession(
|
|
101
|
+
scope: CacheScope,
|
|
102
|
+
warn: (msg: string) => void = (msg) => console.warn(msg),
|
|
103
|
+
): Promise<void> {
|
|
104
|
+
try {
|
|
105
|
+
await fs.rm(scope.dir, { recursive: true, force: true });
|
|
106
|
+
} catch (err) {
|
|
107
|
+
warn(`[pi-image-fit] WARN cleanupSession failed for ${scope.dir}: ${stringifyErr(err)}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Sweep the cache root for stale session directories.
|
|
113
|
+
* Best-effort; errors swallowed-and-logged.
|
|
114
|
+
*
|
|
115
|
+
* @param maxAgeMs entries with mtime older than this are removed
|
|
116
|
+
* @param now injectable clock for tests
|
|
117
|
+
*/
|
|
118
|
+
export async function cleanupOrphans(
|
|
119
|
+
maxAgeMs: number = 24 * 60 * 60 * 1000,
|
|
120
|
+
now: () => number = Date.now,
|
|
121
|
+
warn: (msg: string) => void = (msg) => console.warn(msg),
|
|
122
|
+
): Promise<void> {
|
|
123
|
+
let entries: string[];
|
|
124
|
+
try {
|
|
125
|
+
entries = await fs.readdir(ROOT_DIR);
|
|
126
|
+
} catch {
|
|
127
|
+
// Root doesn't exist yet — nothing to clean.
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const threshold = now() - maxAgeMs;
|
|
131
|
+
await Promise.all(
|
|
132
|
+
entries.map(async (name) => {
|
|
133
|
+
const full = path.join(ROOT_DIR, name);
|
|
134
|
+
try {
|
|
135
|
+
const st = await fs.stat(full);
|
|
136
|
+
if (st.mtimeMs < threshold) {
|
|
137
|
+
await fs.rm(full, { recursive: true, force: true });
|
|
138
|
+
}
|
|
139
|
+
} catch (err) {
|
|
140
|
+
warn(`[pi-image-fit] WARN cleanupOrphans failed for ${full}: ${stringifyErr(err)}`);
|
|
141
|
+
}
|
|
142
|
+
}),
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function stringifyErr(err: unknown): string {
|
|
147
|
+
if (err instanceof Error) return err.message;
|
|
148
|
+
return String(err);
|
|
149
|
+
}
|
package/src/extension.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-image-fit extension entry point.
|
|
3
|
+
*
|
|
4
|
+
* Registers a single `tool_call` hook that, when the agent reads an
|
|
5
|
+
* image whose byte size or long edge exceeds the configured limits,
|
|
6
|
+
* re-encodes the image to a smaller temp file and rewrites
|
|
7
|
+
* `event.input.path` so the built-in Read attaches the resized bytes.
|
|
8
|
+
*
|
|
9
|
+
* All work is wrapped in try/catch with fall-through: any failure
|
|
10
|
+
* leaves `event.input.path` unmodified and logs a single warning.
|
|
11
|
+
*
|
|
12
|
+
* Spec: pi-image-fit/spec.md (all requirements).
|
|
13
|
+
* Design: design.md.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
17
|
+
import * as fs from "node:fs/promises";
|
|
18
|
+
import * as path from "node:path";
|
|
19
|
+
import { readConfigFromEnv, type ImageFitConfig } from "./policy.js";
|
|
20
|
+
import {
|
|
21
|
+
scopeFor,
|
|
22
|
+
cacheKey,
|
|
23
|
+
ensureDir,
|
|
24
|
+
hasCached,
|
|
25
|
+
cleanupSession,
|
|
26
|
+
cleanupOrphans,
|
|
27
|
+
type CacheScope,
|
|
28
|
+
} from "./cache.js";
|
|
29
|
+
import {
|
|
30
|
+
isImagePath,
|
|
31
|
+
needsResize,
|
|
32
|
+
outputFormatFor,
|
|
33
|
+
probeDims,
|
|
34
|
+
resizeToFile,
|
|
35
|
+
} from "./resize.js";
|
|
36
|
+
|
|
37
|
+
export default function imageFitExtension(pi: ExtensionAPI): void {
|
|
38
|
+
const config: ImageFitConfig = readConfigFromEnv();
|
|
39
|
+
|
|
40
|
+
if (config.disabled) {
|
|
41
|
+
console.log("[pi-image-fit] disabled via PI_IMAGE_FIT_DISABLE");
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Best-effort orphan sweep on load. Errors swallowed-and-logged
|
|
46
|
+
// internally. Fire-and-forget — we do not block extension load on it.
|
|
47
|
+
cleanupOrphans().catch(() => {
|
|
48
|
+
/* already logged by cleanupOrphans */
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// Session scope is established lazily: the first tool_call we see
|
|
52
|
+
// pulls sessionId from ctx.sessionManager (if available) or falls
|
|
53
|
+
// back to `pid-<process.pid>`. We cache the scope per session id so
|
|
54
|
+
// that mid-session changes (resume into a different session) get a
|
|
55
|
+
// fresh dir.
|
|
56
|
+
let cachedScope: { sessionId: string; scope: CacheScope } | null = null;
|
|
57
|
+
|
|
58
|
+
function getScopeFor(ctx: unknown): CacheScope {
|
|
59
|
+
const sessionId = readSessionIdFromCtx(ctx);
|
|
60
|
+
if (!cachedScope || cachedScope.sessionId !== sessionId) {
|
|
61
|
+
cachedScope = { sessionId, scope: scopeFor(sessionId) };
|
|
62
|
+
}
|
|
63
|
+
return cachedScope.scope;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
67
|
+
// Fast-path gates. None of these touch the filesystem.
|
|
68
|
+
if (event.toolName !== "read") return;
|
|
69
|
+
const srcPath = event.input?.path;
|
|
70
|
+
if (typeof srcPath !== "string" || srcPath.length === 0) return;
|
|
71
|
+
if (!isImagePath(srcPath)) return;
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
await maybeResize(srcPath, event, ctx, config, getScopeFor);
|
|
75
|
+
} catch (err) {
|
|
76
|
+
// Last-resort catch — every internal step already logs its own
|
|
77
|
+
// warning, but a thrown error here means we missed one. Log and
|
|
78
|
+
// fall through; event.input.path is whatever the deepest mutation
|
|
79
|
+
// left it (callee responsibility to restore on partial failure).
|
|
80
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
81
|
+
console.warn(`[pi-image-fit] WARN unexpected error for ${srcPath}: ${msg}`);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
pi.on("session_shutdown", async () => {
|
|
86
|
+
if (cachedScope) {
|
|
87
|
+
await cleanupSession(cachedScope.scope);
|
|
88
|
+
cachedScope = null;
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Core resize pipeline. Mutates `event.input.path` on success;
|
|
95
|
+
* leaves it untouched on any failure (logs once and returns).
|
|
96
|
+
*/
|
|
97
|
+
async function maybeResize(
|
|
98
|
+
srcPath: string,
|
|
99
|
+
event: { input: { path: string } },
|
|
100
|
+
ctx: unknown,
|
|
101
|
+
config: ImageFitConfig,
|
|
102
|
+
getScopeFor: (ctx: unknown) => CacheScope,
|
|
103
|
+
): Promise<void> {
|
|
104
|
+
// Stat: get bytes + mtime. ENOENT and friends → fall through to
|
|
105
|
+
// built-in Read which produces the appropriate user-facing error.
|
|
106
|
+
let bytes: number;
|
|
107
|
+
let mtimeMs: number;
|
|
108
|
+
try {
|
|
109
|
+
const st = await fs.stat(srcPath);
|
|
110
|
+
if (!st.isFile()) return;
|
|
111
|
+
bytes = st.size;
|
|
112
|
+
mtimeMs = st.mtimeMs;
|
|
113
|
+
} catch (err) {
|
|
114
|
+
// Source file missing or unreadable — let built-in Read handle the error.
|
|
115
|
+
// No warning: this is pi's normal Read-error path, not an extension fault.
|
|
116
|
+
void err;
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Byte-size short-circuit: if the source is already under the byte
|
|
121
|
+
// ceiling AND the (presumed) long edge cannot exceed maxEdge without
|
|
122
|
+
// a dimension probe, we'd still need to probe. Probe once and decide.
|
|
123
|
+
const dims = await probeDims(srcPath);
|
|
124
|
+
if (!dims) {
|
|
125
|
+
// Jimp couldn't decode — likely corrupted or unsupported variant.
|
|
126
|
+
// Fall through to built-in Read which will surface the file as-is.
|
|
127
|
+
console.warn(`[pi-image-fit] WARN could not decode ${srcPath}; passing through original`);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (!needsResize({ bytes, maxBytes: config.maxBytes, dims, maxEdge: config.maxEdge })) {
|
|
132
|
+
// Already-small image — pass through untouched. No log line.
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Resize is needed. Compute cache key + output path.
|
|
137
|
+
const { ext: outExt } = outputFormatFor(srcPath);
|
|
138
|
+
const absPath = path.resolve(srcPath);
|
|
139
|
+
const key = cacheKey({
|
|
140
|
+
absPath,
|
|
141
|
+
mtimeMs,
|
|
142
|
+
maxEdge: config.maxEdge,
|
|
143
|
+
maxBytes: config.maxBytes,
|
|
144
|
+
quality: config.quality,
|
|
145
|
+
});
|
|
146
|
+
const scope = getScopeFor(ctx);
|
|
147
|
+
const dstPath = scope.filePath(key, outExt);
|
|
148
|
+
|
|
149
|
+
// Cache hit: rewrite path, no work.
|
|
150
|
+
if (await hasCached(scope, key, outExt)) {
|
|
151
|
+
event.input.path = dstPath;
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Cache miss: ensure dir, resize, rewrite path, log once.
|
|
156
|
+
try {
|
|
157
|
+
await ensureDir(scope.dir);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
160
|
+
console.warn(`[pi-image-fit] WARN could not create cache dir ${scope.dir}: ${msg}; passing through original`);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
const result = await resizeToFile(srcPath, dstPath, {
|
|
166
|
+
maxEdge: config.maxEdge,
|
|
167
|
+
quality: config.quality,
|
|
168
|
+
});
|
|
169
|
+
event.input.path = dstPath;
|
|
170
|
+
console.log(
|
|
171
|
+
`[pi-image-fit] ${srcPath} ${result.srcDims.width}\u00d7${result.srcDims.height} ${formatBytes(bytes)} \u2192 ${result.dstDims.width}\u00d7${result.dstDims.height} ${formatBytes(result.dstBytes)}`,
|
|
172
|
+
);
|
|
173
|
+
} catch (err) {
|
|
174
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
175
|
+
// Defensive cleanup: a partial write would leave a corrupt file
|
|
176
|
+
// matching the cache key, poisoning later reads. Best-effort unlink.
|
|
177
|
+
try {
|
|
178
|
+
await fs.unlink(dstPath);
|
|
179
|
+
} catch {
|
|
180
|
+
/* ignore */
|
|
181
|
+
}
|
|
182
|
+
console.warn(`[pi-image-fit] WARN resize failed for ${srcPath}: ${msg}; passing through original`);
|
|
183
|
+
// event.input.path was not mutated yet — original path stands.
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function readSessionIdFromCtx(ctx: unknown): string {
|
|
188
|
+
try {
|
|
189
|
+
const sm = (ctx as { sessionManager?: { getSessionId?: () => string } } | undefined)?.sessionManager;
|
|
190
|
+
if (sm && typeof sm.getSessionId === "function") {
|
|
191
|
+
const id = sm.getSessionId();
|
|
192
|
+
if (typeof id === "string" && id.length > 0) return id;
|
|
193
|
+
}
|
|
194
|
+
} catch {
|
|
195
|
+
/* ignore */
|
|
196
|
+
}
|
|
197
|
+
return `pid-${process.pid}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function formatBytes(n: number): string {
|
|
201
|
+
if (n < 1024) return `${n}B`;
|
|
202
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;
|
|
203
|
+
return `${(n / (1024 * 1024)).toFixed(1)}MB`;
|
|
204
|
+
}
|
package/src/policy.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Environment-variable configuration for pi-image-fit.
|
|
3
|
+
*
|
|
4
|
+
* Read once on extension load. Invalid values fall back to documented
|
|
5
|
+
* defaults and emit a single warning line naming the offending variable
|
|
6
|
+
* per spec: Environment-variable configuration.
|
|
7
|
+
*
|
|
8
|
+
* Defaults rationale (see design.md D4):
|
|
9
|
+
* - maxEdge 1568 px — Anthropic's server-side downscale target;
|
|
10
|
+
* landing under this avoids double-downscale.
|
|
11
|
+
* - maxBytes 4 MiB — comfortable headroom under Anthropic's ~5 MB
|
|
12
|
+
* per-image ceiling and the 30 MB per-request total.
|
|
13
|
+
* - quality 85 — webp sweet spot; visible quality cliff <80,
|
|
14
|
+
* diminishing returns >90.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export interface ImageFitConfig {
|
|
18
|
+
/** When true, extension registers no hooks. */
|
|
19
|
+
disabled: boolean;
|
|
20
|
+
/** Long-edge pixel threshold; resize fires if exceeded. */
|
|
21
|
+
maxEdge: number;
|
|
22
|
+
/** Byte-size threshold; resize fires if exceeded. */
|
|
23
|
+
maxBytes: number;
|
|
24
|
+
/** webp output quality, 1–100. */
|
|
25
|
+
quality: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const DEFAULTS: Readonly<ImageFitConfig> = Object.freeze({
|
|
29
|
+
disabled: false,
|
|
30
|
+
maxEdge: 1568,
|
|
31
|
+
maxBytes: 4 * 1024 * 1024, // 4 MiB
|
|
32
|
+
quality: 85,
|
|
33
|
+
});
|
|
34
|
+
|
|
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
|
+
interface ParseRules {
|
|
43
|
+
min: number;
|
|
44
|
+
max: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parsePositiveInt(
|
|
48
|
+
name: string,
|
|
49
|
+
raw: string | undefined,
|
|
50
|
+
fallback: number,
|
|
51
|
+
rules: ParseRules,
|
|
52
|
+
warn: (msg: string) => void,
|
|
53
|
+
): number {
|
|
54
|
+
if (raw === undefined || raw === "") return fallback;
|
|
55
|
+
const trimmed = raw.trim();
|
|
56
|
+
// Integer-only parse: reject floats, NaN, hex, scientific notation,
|
|
57
|
+
// anything that isn't a positive integer literal.
|
|
58
|
+
if (!/^\d+$/.test(trimmed)) {
|
|
59
|
+
warn(`[pi-image-fit] WARN invalid ${name}="${raw}", falling back to ${fallback}`);
|
|
60
|
+
return fallback;
|
|
61
|
+
}
|
|
62
|
+
const n = Number.parseInt(trimmed, 10);
|
|
63
|
+
if (!Number.isFinite(n) || n < rules.min || n > rules.max) {
|
|
64
|
+
warn(`[pi-image-fit] WARN out-of-range ${name}="${raw}", falling back to ${fallback}`);
|
|
65
|
+
return fallback;
|
|
66
|
+
}
|
|
67
|
+
return n;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ReadConfigOptions {
|
|
71
|
+
env?: NodeJS.ProcessEnv;
|
|
72
|
+
warn?: (msg: string) => void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Read configuration from environment variables.
|
|
77
|
+
* Pure function: no side effects beyond the provided `warn` callback.
|
|
78
|
+
*/
|
|
79
|
+
export function readConfigFromEnv(opts: ReadConfigOptions = {}): ImageFitConfig {
|
|
80
|
+
const env = opts.env ?? process.env;
|
|
81
|
+
const warn = opts.warn ?? ((msg: string) => console.warn(msg));
|
|
82
|
+
|
|
83
|
+
const disabled = parseBool(env.PI_IMAGE_FIT_DISABLE);
|
|
84
|
+
const maxEdge = parsePositiveInt(
|
|
85
|
+
"PI_IMAGE_FIT_MAX_EDGE",
|
|
86
|
+
env.PI_IMAGE_FIT_MAX_EDGE,
|
|
87
|
+
DEFAULTS.maxEdge,
|
|
88
|
+
{ min: 1, max: 100_000 },
|
|
89
|
+
warn,
|
|
90
|
+
);
|
|
91
|
+
const maxBytes = parsePositiveInt(
|
|
92
|
+
"PI_IMAGE_FIT_MAX_BYTES",
|
|
93
|
+
env.PI_IMAGE_FIT_MAX_BYTES,
|
|
94
|
+
DEFAULTS.maxBytes,
|
|
95
|
+
{ min: 1, max: Number.MAX_SAFE_INTEGER },
|
|
96
|
+
warn,
|
|
97
|
+
);
|
|
98
|
+
const quality = parsePositiveInt(
|
|
99
|
+
"PI_IMAGE_FIT_QUALITY",
|
|
100
|
+
env.PI_IMAGE_FIT_QUALITY,
|
|
101
|
+
DEFAULTS.quality,
|
|
102
|
+
{ min: 1, max: 100 },
|
|
103
|
+
warn,
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
return { disabled, maxEdge, maxBytes, quality };
|
|
107
|
+
}
|
package/src/resize.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Image probing and resizing for pi-image-fit.
|
|
3
|
+
*
|
|
4
|
+
* Spec: Resize threshold policy, Resize implementation.
|
|
5
|
+
* Design: D2 (jimp), D3 (format-adaptive PNG-in→PNG-out, else JPEG@85).
|
|
6
|
+
*
|
|
7
|
+
* The `jimp` library is loaded lazily so that the disabled path
|
|
8
|
+
* (PI_IMAGE_FIT_DISABLE=1) and non-image read paths never pay the
|
|
9
|
+
* ~50 ms jimp load cost.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { JimpMime, Jimp } from "jimp";
|
|
13
|
+
import * as fs from "node:fs/promises";
|
|
14
|
+
import * as path from "node:path";
|
|
15
|
+
|
|
16
|
+
export interface ImageDims {
|
|
17
|
+
width: number;
|
|
18
|
+
height: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface NeedsResizeInput {
|
|
22
|
+
bytes: number;
|
|
23
|
+
maxBytes: number;
|
|
24
|
+
dims: ImageDims;
|
|
25
|
+
maxEdge: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resize policy predicate.
|
|
30
|
+
* Spec: Resize threshold policy.
|
|
31
|
+
*/
|
|
32
|
+
export function needsResize(input: NeedsResizeInput): boolean {
|
|
33
|
+
const longEdge = Math.max(input.dims.width, input.dims.height);
|
|
34
|
+
return input.bytes > input.maxBytes || longEdge > input.maxEdge;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Output extension and mime type for the format-adaptive policy.
|
|
39
|
+
* - `.png` source → PNG output (lossless)
|
|
40
|
+
* - everything else → JPEG output (lossy)
|
|
41
|
+
*
|
|
42
|
+
* Returns `{ ext, mime }` where `ext` includes the leading dot.
|
|
43
|
+
*/
|
|
44
|
+
export function outputFormatFor(srcPath: string): { ext: string; mime: string } {
|
|
45
|
+
const lower = srcPath.toLowerCase();
|
|
46
|
+
if (lower.endsWith(".png")) {
|
|
47
|
+
return { ext: ".png", mime: JimpMime.png };
|
|
48
|
+
}
|
|
49
|
+
return { ext: ".jpg", mime: JimpMime.jpeg };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Image-extension allowlist used by the tool_call hook gate.
|
|
54
|
+
* Spec: Tool-call mutation seam.
|
|
55
|
+
*/
|
|
56
|
+
const IMAGE_EXT_RE = /\.(png|jpe?g|webp|gif)$/i;
|
|
57
|
+
|
|
58
|
+
export function isImagePath(p: string): boolean {
|
|
59
|
+
return IMAGE_EXT_RE.test(p);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Probe source image dimensions by loading via jimp.
|
|
64
|
+
* Returns null if the file cannot be decoded (caller falls through).
|
|
65
|
+
*/
|
|
66
|
+
export async function probeDims(srcPath: string): Promise<ImageDims | null> {
|
|
67
|
+
try {
|
|
68
|
+
const img = await Jimp.read(srcPath);
|
|
69
|
+
return { width: img.width, height: img.height };
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ResizeOptions {
|
|
76
|
+
maxEdge: number;
|
|
77
|
+
/** JPEG quality 1–100. Ignored for PNG output. */
|
|
78
|
+
quality: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface ResizeResult {
|
|
82
|
+
srcDims: ImageDims;
|
|
83
|
+
dstDims: ImageDims;
|
|
84
|
+
dstBytes: number;
|
|
85
|
+
outExt: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Re-encode the source image to `dstPath` at `outExt`, scaled so the
|
|
90
|
+
* long edge is at most `maxEdge` (preserving aspect ratio).
|
|
91
|
+
*
|
|
92
|
+
* Caller is responsible for ensuring `path.dirname(dstPath)` exists.
|
|
93
|
+
* Throws on any failure; the extension hook catches at the top level
|
|
94
|
+
* and falls through to the original path.
|
|
95
|
+
*/
|
|
96
|
+
export async function resizeToFile(
|
|
97
|
+
srcPath: string,
|
|
98
|
+
dstPath: string,
|
|
99
|
+
opts: ResizeOptions,
|
|
100
|
+
): Promise<ResizeResult> {
|
|
101
|
+
const img = await Jimp.read(srcPath);
|
|
102
|
+
const srcDims: ImageDims = { width: img.width, height: img.height };
|
|
103
|
+
|
|
104
|
+
// Long-edge scaling, aspect-ratio preserving. Jimp 1.x exposes
|
|
105
|
+
// `.scaleToFit({ w, h })` which fits the image inside a w×h box.
|
|
106
|
+
// Using the same value for both edges yields long-edge ≤ maxEdge.
|
|
107
|
+
if (Math.max(srcDims.width, srcDims.height) > opts.maxEdge) {
|
|
108
|
+
img.scaleToFit({ w: opts.maxEdge, h: opts.maxEdge });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const outExt = path.extname(dstPath).toLowerCase();
|
|
112
|
+
let buffer: Buffer;
|
|
113
|
+
if (outExt === ".png") {
|
|
114
|
+
buffer = (await img.getBuffer(JimpMime.png)) as unknown as Buffer;
|
|
115
|
+
} else {
|
|
116
|
+
buffer = (await img.getBuffer(JimpMime.jpeg, {
|
|
117
|
+
quality: opts.quality,
|
|
118
|
+
})) as unknown as Buffer;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
await fs.writeFile(dstPath, buffer);
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
srcDims,
|
|
125
|
+
dstDims: { width: img.width, height: img.height },
|
|
126
|
+
dstBytes: buffer.length,
|
|
127
|
+
outExt,
|
|
128
|
+
};
|
|
129
|
+
}
|