@spellkave/world-map 0.0.0-stage → 0.1.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.
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Churn-guarded JPEG write for a caller-supplied output directory — the SAME
3
+ * sha256(svg + width) provenance-sidecar pattern
4
+ * `packages/spellkave-srd-cc/src/author/elven-mini/renders.ts` established
5
+ * for the AUTHOR-side "with-map" product renders, generalized into a small
6
+ * reusable helper so `spellkave_map`'s (and `spellkave_map_graph`'s)
7
+ * `output_type: "jpg"` mode (shared tool runtime `tools.ts`/`authoring-verbs.ts`)
8
+ * doesn't hand-roll a second copy. `resolveMapJpegOutput` below is the
9
+ * companion piece — output_dir/output_name default resolution (bead sk-due).
10
+ *
11
+ * PNG -> JPEG (operator decision, 2026-08-13): a full-resolution backdrop
12
+ * PNG runs 1.1-1.4 MB, well over the repo's `check-added-large-files
13
+ * --maxkb=1024` pre-commit gate. Mirrors `renders.ts`'s own established
14
+ * product-view path exactly: rasterize to PNG via resvg (still a PNG buffer
15
+ * at this stage — `rasterizeSvgToPng` is unchanged, resvg has no native JPEG
16
+ * output), write it to a dot-prefixed temp file, shell out to
17
+ * `ffmpeg -q:v 4` to encode the JPEG, then delete the temp PNG.
18
+ *
19
+ * ffmpeg on CI (sk-zgbj, corrects this header's earlier "never on a CI
20
+ * runner" claim): srd-integration.yml's story job DOES re-record the
21
+ * elven-mini playthrough on a runner, and #2442's first execution died on
22
+ * `spawnSync ffmpeg ENOENT` there. The churn guard below hides that whenever
23
+ * the committed art is current — an unchanged source skips rasterize+encode
24
+ * entirely — so the ENOENT only appears once the source actually drifts,
25
+ * which is the worst possible moment for a confusing error. `textOnly` (see
26
+ * `writeJpegWithChurnGuard`) is the CI answer, mirroring the author-side
27
+ * `SRD_CC_AUTHOR_CHECK_TEXT_ONLY` idiom in
28
+ * `packages/spellkave-srd-cc/src/author/elven-mini/renders.ts` — it produces
29
+ * nothing AND compares nothing.
30
+ *
31
+ * Why a hash sidecar and not a byte-diff: encoded bytes are host-dependent
32
+ * (fonts + native resvg build + ffmpeg version), so two machines rendering
33
+ * the SAME logical map can produce different bytes — comparing raw bytes
34
+ * would rewrite the file on every re-record.
35
+ *
36
+ * The hash therefore uses a HOST-INDEPENDENT source: the raster width, the
37
+ * SVG with host-resolved backdrop `href=` payloads normalised away, and a
38
+ * stable fingerprint of the authored `map_layers` rows that identify those
39
+ * backdrops. That keeps real graph/SVG changes visible (style, labels,
40
+ * topology, layout) while excluding the machine-local terms that made the old
41
+ * `sha256(width + "\n" + svg)` claim false in practice (absolute `file://`
42
+ * URLs and embedded `data:` payloads reaching the SVG). Proof target: two
43
+ * consecutive recordings leave `git status` clean, and the same logical input
44
+ * hashed from two checkout-path contexts produces the same digest.
45
+ */
46
+
47
+ import { execFileSync } from "node:child_process";
48
+ import { createHash } from "node:crypto";
49
+ import {
50
+ existsSync,
51
+ mkdirSync,
52
+ mkdtempSync,
53
+ readFileSync,
54
+ unlinkSync,
55
+ writeFileSync,
56
+ } from "node:fs";
57
+ import { tmpdir } from "node:os";
58
+ import { isAbsolute, join } from "node:path";
59
+
60
+ import { rasterizeSvgToPng } from "./rasterize.ts";
61
+
62
+ const PROVENANCE_FILE = "provenance.json";
63
+
64
+ /**
65
+ * Skip PRODUCING the binary (keep recording its provenance) — the same
66
+ * portability escape hatch `renders.ts` exposes as
67
+ * `SRD_CC_AUTHOR_CHECK_TEXT_ONLY`, under its own name because this writer
68
+ * serves `spellkave_map`'s tool path rather than the author check. Read per
69
+ * call, never cached, so a test can flip it around a single write.
70
+ */
71
+ function textOnlyMode(): boolean {
72
+ return process.env.SPELLKAVE_MAP_JPEG_TEXT_ONLY === "1";
73
+ }
74
+
75
+ const HOST_DEPENDENT_BACKDROP_HREF = /href="(?:data:[^"]*|file:[^"]*)"/g;
76
+
77
+ function stableRowFingerprint(rows: readonly Record<string, unknown>[]): string {
78
+ return JSON.stringify(
79
+ rows
80
+ .map((row) =>
81
+ Object.keys(row)
82
+ .sort()
83
+ .map((key) => [key, row[key]] as const),
84
+ )
85
+ .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
86
+ );
87
+ }
88
+
89
+ export function mapLayerFingerprint(layerRows: readonly Record<string, unknown>[]): string {
90
+ return stableRowFingerprint(layerRows);
91
+ }
92
+
93
+ export function provenanceHash(svg: string, width: number, layerFingerprint = ""): string {
94
+ const assetIndependentSvg = svg.replace(HOST_DEPENDENT_BACKDROP_HREF, 'href="[backdrop]"');
95
+ return createHash("sha256")
96
+ .update(`${width}\n${layerFingerprint}\n${assetIndependentSvg}`)
97
+ .digest("hex");
98
+ }
99
+
100
+ /** `null` = no sidecar on disk yet (first write into this directory). */
101
+ function loadProvenance(dir: string): Record<string, string> | null {
102
+ try {
103
+ const parsed = JSON.parse(readFileSync(join(dir, PROVENANCE_FILE), "utf8"));
104
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, string>) : {};
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ function writeProvenance(dir: string, provenance: Record<string, string>): void {
111
+ const sorted: Record<string, string> = {};
112
+ for (const [key, hash] of Object.entries(provenance).sort(([a], [b]) =>
113
+ a < b ? -1 : a > b ? 1 : 0,
114
+ )) {
115
+ sorted[key] = hash;
116
+ }
117
+ writeFileSync(join(dir, PROVENANCE_FILE), `${JSON.stringify(sorted, null, "\t")}\n`, "utf8");
118
+ }
119
+
120
+ /**
121
+ * True when the existing binary at `path` can be trusted as-is: its recorded
122
+ * provenance hash still matches (source unchanged), or the sidecar is
123
+ * missing entirely — the ONE-TIME bootstrap (first write after this feature
124
+ * landed, or a caller-managed directory that predates the sidecar) trusts
125
+ * whatever is already on disk rather than forcing a rewrite of every file.
126
+ */
127
+ function canSkipRewrite(
128
+ path: string,
129
+ filename: string,
130
+ hash: string,
131
+ oldProvenance: Record<string, string> | null,
132
+ ): boolean {
133
+ if (!existsSync(path)) return false;
134
+ if (oldProvenance === null) return true;
135
+ return oldProvenance[filename] === hash;
136
+ }
137
+
138
+ export interface WriteJpegResult {
139
+ /** Absolute path the JPEG was (or already was) written to. */
140
+ path: string;
141
+ /** True when this call actually rasterized + encoded + wrote new bytes. */
142
+ written: boolean;
143
+ }
144
+
145
+ /**
146
+ * Write `<dir>/<baseName>.jpg`, rasterized from `svg` at `width` via resvg
147
+ * then encoded via `ffmpeg -q:v 4` (same quality renders.ts's own
148
+ * `*-with-map.jpg` product views use) — but only when the deterministic
149
+ * source changed since the last write into `dir` (see module header). `dir`
150
+ * and `baseName` are ALWAYS caller-supplied (no ambient/hardcoded location)
151
+ * — see `spellkave_map`'s own `output_dir`/`output_name` params
152
+ * (`resolveMapJpegOutput` below fills in a temp dir / derived name when a
153
+ * caller omits either).
154
+ */
155
+ export async function writeJpegWithChurnGuard(
156
+ dir: string,
157
+ baseName: string,
158
+ svg: string,
159
+ width: number,
160
+ layerFingerprint = "",
161
+ ): Promise<WriteJpegResult> {
162
+ mkdirSync(dir, { recursive: true });
163
+ const filename = `${baseName}.jpg`;
164
+ const path = join(dir, filename);
165
+ const hash = provenanceHash(svg, width, layerFingerprint);
166
+ const oldProvenance = loadProvenance(dir);
167
+ let written = false;
168
+ if (!canSkipRewrite(path, filename, hash, oldProvenance)) {
169
+ if (textOnlyMode()) {
170
+ // sk-zgbj (corrected): touch NOTHING on disk — not the JPEG, and
171
+ // deliberately not the sidecar either.
172
+ //
173
+ // The first cut wrote the new hash here, on the theory that the
174
+ // sidecar is a reproducible text stand-in for the binary. It is
175
+ // not. The old `sha256(width + "\\n" + svg)` hash included host-
176
+ // resolved backdrop `href=` payloads, so a foreign host could miss
177
+ // even when the logical map matched. That is also the real trigger
178
+ // behind this bead's original ENOENT — the guard never matched on
179
+ // a foreign host, so it always reached for ffmpeg; stale content
180
+ // merely made it look content-shaped. Writing the hash therefore
181
+ // did not report drift, it MANUFACTURED a diff on every runner and
182
+ // would have made the story gate permanently red (caught in #2459
183
+ // before that gate went live).
184
+ //
185
+ // So this mirrors the author side exactly: renders.ts's `textOnly`
186
+ // skips producing the binaries and its callers skip them on the
187
+ // COMPARE side too. Map-art drift is consequently not a CI-visible
188
+ // signal — it cannot be, on a host that can neither encode the
189
+ // binary nor reproduce its hash. It is caught where the art is
190
+ // actually regenerated: the local re-record.
191
+ // eslint-disable-next-line no-console
192
+ console.error(
193
+ `[map-jpeg] ${filename}: SPELLKAVE_MAP_JPEG_TEXT_ONLY=1 — skipping ` +
194
+ "rasterize+ffmpeg and leaving provenance.json untouched. If the SOURCE " +
195
+ "genuinely changed, a local re-record refreshes both the JPEG and its hash.",
196
+ );
197
+ return { path, written: false };
198
+ }
199
+ const { png } = await rasterizeSvgToPng(svg, { width });
200
+ // resvg has no native JPEG output — rasterize to a temp PNG, then shell
201
+ // out to ffmpeg for the JPEG encode (same two-step renders.ts's own
202
+ // `*-with-map.jpg` product views use), and delete the temp file.
203
+ const tmpPng = join(dir, `.${baseName}.tmp.png`);
204
+ writeFileSync(tmpPng, png);
205
+ execFileSync("ffmpeg", ["-y", "-i", tmpPng, "-q:v", "4", path], { stdio: "pipe" });
206
+ unlinkSync(tmpPng);
207
+ written = true;
208
+ }
209
+ // Always persist (even on skip): a fresh bootstrap sidecar still needs this
210
+ // entry recorded so the NEXT call in a different directory state compares
211
+ // correctly, and re-sorting/re-writing an unchanged sidecar is idempotent.
212
+ writeProvenance(dir, { ...(oldProvenance ?? {}), [filename]: hash });
213
+ return { path, written };
214
+ }
215
+
216
+ /** `graph` (a place_graph_id) -> a filesystem-safe stem, e.g. "elven_mini/inn"
217
+ * -> "elven-mini-inn". Falls back to "map" for a world-compose call (no graph
218
+ * filter) or a graph id with no alphanumerics at all. */
219
+ function defaultMapName(graph: string | undefined): string {
220
+ const trimmed = graph?.trim();
221
+ if (!trimmed) return "map";
222
+ const slug = trimmed
223
+ .toLowerCase()
224
+ .replace(/[^a-z0-9]+/g, "-")
225
+ .replace(/^-+|-+$/g, "");
226
+ return slug.length > 0 ? slug : "map";
227
+ }
228
+
229
+ export interface MapJpegOutputTarget {
230
+ /** Absolute directory to actually write into. */
231
+ dir: string;
232
+ /** Base filename (no extension). */
233
+ name: string;
234
+ /** What the tool's response should echo as the `output_dir` half of
235
+ * `jpg_path` — the caller's OWN string verbatim when supplied (never
236
+ * resolved, so a relative input stays relative — see this module's own
237
+ * header on why that matters for a recorded artifact), or the same
238
+ * absolute temp dir actually used when defaulted (there is no
239
+ * caller-original to echo in that case). */
240
+ echoDir: string;
241
+ }
242
+
243
+ /**
244
+ * Resolve `output_dir`/`output_name` for `output_type: "jpg"` — BOTH stay
245
+ * optional (bead sk-due): an omitted `output_dir` gets a fresh temp
246
+ * directory (`mkdtempSync`), an omitted `output_name` gets one derived from
247
+ * `graph` (or "map" for a world-compose call with no graph filter). Explicit
248
+ * values are untouched — same relative-stays-relative contract
249
+ * `writeJpegWithChurnGuard`'s own callers already prove (the srd-cc adventure
250
+ * story recording needs stable repo-relative paths).
251
+ */
252
+ export function resolveMapJpegOutput(
253
+ outputDir: string | undefined,
254
+ outputName: string | undefined,
255
+ graph: string | undefined,
256
+ ): MapJpegOutputTarget {
257
+ const trimmedDir = outputDir?.trim();
258
+ const trimmedName = outputName?.trim();
259
+ const name = trimmedName && trimmedName.length > 0 ? trimmedName : defaultMapName(graph);
260
+ if (trimmedDir !== undefined && trimmedDir.length > 0) {
261
+ const dir = isAbsolute(trimmedDir) ? trimmedDir : join(process.cwd(), trimmedDir);
262
+ return { dir, name, echoDir: trimmedDir };
263
+ }
264
+ const dir = mkdtempSync(join(tmpdir(), "spellkave-map-"));
265
+ return { dir, name, echoDir: dir };
266
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Host-boundary SVG → PNG. Uses @resvg/resvg-js when available.
3
+ * Pure SVG remains the canonical product; this is only for pi-tui Image.
4
+ */
5
+
6
+ export interface RasterizeSvgResult {
7
+ png: Buffer;
8
+ mimeType: "image/png";
9
+ }
10
+
11
+ export async function rasterizeSvgToPng(
12
+ svg: string,
13
+ options: { width?: number } = {},
14
+ ): Promise<RasterizeSvgResult> {
15
+ const { Resvg } = await import("@resvg/resvg-js");
16
+ const resvg = new Resvg(svg, {
17
+ fitTo:
18
+ options.width === undefined
19
+ ? undefined
20
+ : {
21
+ mode: "width",
22
+ value: options.width,
23
+ },
24
+ });
25
+ const rendered = resvg.render();
26
+ return { png: Buffer.from(rendered.asPng()), mimeType: "image/png" };
27
+ }
@@ -0,0 +1,89 @@
1
+ import { isatty } from "node:tty";
2
+ import {
3
+ detectCapabilities,
4
+ setCapabilities,
5
+ type TerminalCapabilities,
6
+ } from "@earendil-works/pi-tui";
7
+
8
+ export type TerminalImagesMode = "auto" | "kitty" | "iterm2" | "off";
9
+
10
+ /**
11
+ * Resolve terminal image protocol for sk + Pi hosts.
12
+ *
13
+ * Nested hosts (Herdr panes) often leave TERM=xterm-256color with empty
14
+ * TERM_PROGRAM even when the outer Ghostty window supports Kitty graphics.
15
+ */
16
+ export function resolveTerminalImageCapabilities(
17
+ imagesMode: TerminalImagesMode = "auto",
18
+ explicit?: TerminalCapabilities,
19
+ ): TerminalCapabilities {
20
+ if (explicit !== undefined) return explicit;
21
+
22
+ const mode =
23
+ normalizeImagesMode(imagesMode) ??
24
+ normalizeImagesMode(process.env.SPELLKAVE_TERMINAL_IMAGES) ??
25
+ "auto";
26
+ if (mode === "off") {
27
+ return { images: null, trueColor: true, hyperlinks: false };
28
+ }
29
+ if (mode === "kitty" || mode === "iterm2") {
30
+ return { images: mode, trueColor: true, hyperlinks: true };
31
+ }
32
+
33
+ const detected = detectCapabilities();
34
+ if (detected.images !== null) return detected;
35
+
36
+ if (stdoutIsTerminal() && !isMultiplexerTerm() && !isKnownNonGraphicsTerminal()) {
37
+ return { images: "kitty", trueColor: true, hyperlinks: detected.hyperlinks };
38
+ }
39
+ return detected;
40
+ }
41
+
42
+ /**
43
+ * Install resolved capabilities into pi-tui's process-global cache so Pi's
44
+ * ToolExecution Image renderer (which calls getCapabilities()) enables Kitty.
45
+ * Safe to call at extension load / session_start.
46
+ */
47
+ export function ensureSpellkaveTerminalImageCapabilities(
48
+ imagesMode: TerminalImagesMode = "auto",
49
+ ): TerminalCapabilities {
50
+ const caps = resolveTerminalImageCapabilities(imagesMode);
51
+ setCapabilities(caps);
52
+ return caps;
53
+ }
54
+
55
+ export function stdoutIsTerminal(): boolean {
56
+ try {
57
+ return isatty(1);
58
+ } catch {
59
+ return process.stdout.isTTY === true;
60
+ }
61
+ }
62
+
63
+ export function parseImagesModeFlag(raw: string | undefined): TerminalImagesMode | undefined {
64
+ return normalizeImagesMode(raw);
65
+ }
66
+
67
+ function normalizeImagesMode(raw: string | undefined | null): TerminalImagesMode | undefined {
68
+ if (raw === undefined || raw === null) return undefined;
69
+ const value = raw.trim().toLowerCase();
70
+ if (value === "auto" || value === "kitty" || value === "iterm2" || value === "off") return value;
71
+ return undefined;
72
+ }
73
+
74
+ function isMultiplexerTerm(): boolean {
75
+ const term = process.env.TERM?.toLowerCase() ?? "";
76
+ return Boolean(process.env.TMUX) || term.startsWith("tmux") || term.startsWith("screen");
77
+ }
78
+
79
+ function isKnownNonGraphicsTerminal(): boolean {
80
+ const termProgram = process.env.TERM_PROGRAM?.toLowerCase() ?? "";
81
+ const term = process.env.TERM?.toLowerCase() ?? "";
82
+ const emulator = process.env.TERMINAL_EMULATOR?.toLowerCase() ?? "";
83
+ if (term === "dumb" || term === "") return true;
84
+ if (termProgram === "apple_terminal" || termProgram === "vscode") return true;
85
+ if (termProgram === "alacritty") return true;
86
+ if (emulator === "jetbrains-jediterm") return true;
87
+ if (process.env.WT_SESSION) return true;
88
+ return false;
89
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Terminal-only entry: pi-tui image-protocol capability resolution.
3
+ * Split from `./index.ts` because pi-tui is an OPTIONAL peer dependency —
4
+ * server hosts (PLAYER MCP gateway) never install it (#2468).
5
+ */
6
+ export {
7
+ ensureSpellkaveTerminalImageCapabilities,
8
+ parseImagesModeFlag,
9
+ resolveTerminalImageCapabilities,
10
+ stdoutIsTerminal,
11
+ type TerminalImagesMode,
12
+ } from "./terminal-capabilities.ts";
@@ -0,0 +1,136 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ /**
7
+ * Pixelation modes that always go through the timg binary.
8
+ * Native kitty/iterm2 stay on pi-tui; half/quarter/sixel are remote-friendly.
9
+ */
10
+ export type TimgPixelation = "half" | "quarter" | "sixel";
11
+
12
+ const PIXEL_FLAG: Record<TimgPixelation, string> = {
13
+ half: "h",
14
+ quarter: "q",
15
+ sixel: "s",
16
+ };
17
+
18
+ export function isTimgPixelation(mode: string): mode is TimgPixelation {
19
+ return mode in PIXEL_FLAG;
20
+ }
21
+
22
+ export function findTimgBinary(env: NodeJS.ProcessEnv = process.env): string | null {
23
+ const override = env.SPELLKAVE_TIMG?.trim();
24
+ if (override) return override;
25
+ const which = spawnSync("which", ["timg"], { encoding: "utf8" });
26
+ if (which.status === 0) {
27
+ const path = which.stdout.trim().split("\n")[0]?.trim();
28
+ if (path) {
29
+ const probe = spawnSync(path, ["--version"], { encoding: "utf8" });
30
+ if (probe.status === 0) return path;
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+
36
+ /**
37
+ * Render a PNG buffer through timg into terminal escape/unicode bytes.
38
+ * Uses -g when stdout is not a size-queryable TTY (required by timg).
39
+ */
40
+ export function renderPngWithTimg(
41
+ png: Buffer,
42
+ options: {
43
+ pixelation: TimgPixelation;
44
+ /** Terminal cells; used for -g WxH. */
45
+ cols?: number;
46
+ rows?: number;
47
+ timgPath?: string;
48
+ },
49
+ ): { ok: true; bytes: Buffer } | { ok: false; error: string } {
50
+ const timg = options.timgPath ?? findTimgBinary();
51
+ if (timg === null) {
52
+ return {
53
+ ok: false,
54
+ error: "timg not found on PATH (install: brew install timg; or set SPELLKAVE_TIMG)",
55
+ };
56
+ }
57
+ const cols = Math.max(20, options.cols ?? process.stdout.columns ?? 80);
58
+ // Image aspect ~1200x760 → rows ≈ cols * 0.45 for half/quarter cell pixels
59
+ const rows = Math.max(8, options.rows ?? Math.ceil(cols * 0.45));
60
+ const dir = mkdtempSync(join(tmpdir(), "sk-timg-"));
61
+ const pngPath = join(dir, "map.png");
62
+ try {
63
+ writeFileSync(pngPath, png);
64
+ const args = [
65
+ `-p${PIXEL_FLAG[options.pixelation]}`,
66
+ `-g${cols}x${rows}`,
67
+ "--frames=1",
68
+ pngPath,
69
+ ];
70
+ const result = spawnSync(timg, args, {
71
+ encoding: "buffer",
72
+ maxBuffer: 32 * 1024 * 1024,
73
+ });
74
+ if (result.error) {
75
+ return { ok: false, error: `timg spawn failed: ${result.error.message}` };
76
+ }
77
+ if (result.status !== 0) {
78
+ const err = (result.stderr ?? Buffer.alloc(0)).toString("utf8").trim();
79
+ return {
80
+ ok: false,
81
+ error: `timg exited ${result.status}${err ? `: ${err.split("\n")[0]}` : ""}`,
82
+ };
83
+ }
84
+ const out = result.stdout ?? Buffer.alloc(0);
85
+ if (out.length === 0) {
86
+ return { ok: false, error: "timg produced empty output" };
87
+ }
88
+ return { ok: true, bytes: out };
89
+ } finally {
90
+ try {
91
+ rmSync(dir, { recursive: true, force: true });
92
+ } catch {
93
+ // ignore cleanup errors
94
+ }
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Convert timg stdout into line-oriented strings safe for pi-tui Components.
100
+ * Strips cursor hide/show; keeps truecolor SGR + half/quarter block glyphs.
101
+ */
102
+ export function timgBytesToLines(bytes: Buffer): string[] {
103
+ let text = bytes.toString("utf8");
104
+ // Cursor visibility / alternate-screen noise — not line content.
105
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ESC-byte match for ANSI stripping
106
+ text = text.replace(/\x1b\[\?25[lh]/g, "");
107
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ESC-byte match for ANSI stripping
108
+ text = text.replace(/\x1b\[\?1049[lh]/g, "");
109
+ text = text.replace(/\r/g, "");
110
+ const raw = text.split("\n");
111
+ // Drop trailing empties; keep interior blank rows for aspect.
112
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ESC-byte match for ANSI stripping
113
+ while (raw.length > 0 && raw[raw.length - 1]?.replace(/\x1b\[[0-9;]*m/g, "").trim() === "") {
114
+ raw.pop();
115
+ }
116
+ return raw;
117
+ }
118
+
119
+ /** Prefer unicode blocks when forced, or when native graphics are unavailable. */
120
+ export function preferTimgUnicodeBlocks(
121
+ imagesMode: string | undefined,
122
+ hasNativeGraphics: boolean,
123
+ env: NodeJS.ProcessEnv = process.env,
124
+ ): TimgPixelation | null {
125
+ const mode =
126
+ (imagesMode ?? env.SPELLKAVE_TERMINAL_IMAGES ?? "auto").trim().toLowerCase() || "auto";
127
+ if (mode === "half" || mode === "h") return "half";
128
+ if (mode === "quarter" || mode === "q" || mode === "timg") return "quarter";
129
+ if (mode === "sixel" || mode === "s") return "sixel";
130
+ if (mode === "kitty" || mode === "iterm2" || mode === "off") return null;
131
+ // auto: unicode when no Kitty/iTerm2
132
+ if (mode === "auto" && !hasNativeGraphics && findTimgBinary(env) !== null) {
133
+ return "quarter";
134
+ }
135
+ return null;
136
+ }
@@ -0,0 +1,53 @@
1
+ import { rasterizeSvgToPng } from "./rasterize.ts";
2
+
3
+ /** Minimal tool-result shape (pi-agent-core AgentToolResult-compatible). */
4
+ export interface SpatialToolResultLike {
5
+ content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;
6
+ details?: unknown;
7
+ }
8
+
9
+ /**
10
+ * If `details.svg` is present, rasterize to PNG and append an ImageContent
11
+ * block so Pi's TUI (and any host that renders tool-result images) shows the
12
+ * map inline — same product as `sk map-render` without --out.
13
+ *
14
+ * Large `svg` is stripped from details after rasterize to keep LLM context small;
15
+ * `inventory` and counts remain.
16
+ */
17
+ export async function attachSpatialGraphImageToToolResult<T extends SpatialToolResultLike>(
18
+ result: T,
19
+ ): Promise<T> {
20
+ const details = result.details;
21
+ if (typeof details !== "object" || details === null || Array.isArray(details)) {
22
+ return result;
23
+ }
24
+ const record = details as Record<string, unknown>;
25
+ const svg = typeof record.svg === "string" ? record.svg : null;
26
+ if (svg === null || svg.length === 0) return result;
27
+ // Idempotent: tool run + host wrapper may both call this; keep a single PNG.
28
+ if (result.content.some((block) => block.type === "image")) return result;
29
+
30
+ try {
31
+ const { png, mimeType } = await rasterizeSvgToPng(svg);
32
+ const data = png.toString("base64");
33
+ const inventory =
34
+ typeof record.inventory === "string" ? record.inventory : "Spatial graph rendered as image.";
35
+ const textBlocks = result.content.filter((block) => block.type === "text");
36
+ const hasText = textBlocks.some(
37
+ (block) => typeof block.text === "string" && block.text.length > 0,
38
+ );
39
+ // Keep details.svg for hosts (sk) that paint from the vector; add ImageContent
40
+ // for Pi TUI tool-result rendering (Ghostty/Kitty).
41
+ return {
42
+ ...result,
43
+ content: [
44
+ ...(hasText ? textBlocks : [{ type: "text" as const, text: inventory }]),
45
+ { type: "image" as const, data, mimeType },
46
+ ],
47
+ details: record,
48
+ };
49
+ } catch {
50
+ // Rasterize failure must not break the tool — keep original SVG details.
51
+ return result;
52
+ }
53
+ }
package/src/poi.ts ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Schema definition and helpers for POI metadata attachments (ADR-0073 / ADR-0130).
3
+ *
4
+ * Namespace: 'maps.poi' (or ending with '.maps.poi')
5
+ * Target kind: 'place_node' or 'place_graph'
6
+ *
7
+ * Payload shape:
8
+ * {
9
+ * "icon": "inn" | "portal" | "dungeon" | "cave" | "temple" | "shop" | "well" | ...,
10
+ * "category"?: string,
11
+ * "label"?: string,
12
+ * "badge"?: string,
13
+ * "color"?: string,
14
+ * "image"?: string
15
+ * }
16
+ */
17
+
18
+ export interface PoiMetadataPayload {
19
+ icon?: string;
20
+ category?: string;
21
+ label?: string;
22
+ badge?: string;
23
+ color?: string;
24
+ image?: string;
25
+ }
26
+
27
+ export const POI_NAMESPACE = "maps.poi";
28
+
29
+ export function isPoiNamespace(namespace: string): boolean {
30
+ return namespace === POI_NAMESPACE || namespace.endsWith(`.${POI_NAMESPACE}`);
31
+ }
32
+
33
+ export function parsePoiMetadata(payloadJson: string): PoiMetadataPayload | null {
34
+ if (!payloadJson || typeof payloadJson !== "string") return null;
35
+ try {
36
+ const parsed = JSON.parse(payloadJson);
37
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
38
+ const res: PoiMetadataPayload = {};
39
+ if (typeof parsed.icon === "string" && parsed.icon.trim() !== "") {
40
+ res.icon = parsed.icon.trim();
41
+ }
42
+ if (typeof parsed.category === "string" && parsed.category.trim() !== "") {
43
+ res.category = parsed.category.trim();
44
+ }
45
+ if (typeof parsed.badge === "string" && parsed.badge.trim() !== "") {
46
+ res.badge = parsed.badge.trim();
47
+ }
48
+ if (typeof parsed.color === "string" && parsed.color.trim() !== "") {
49
+ res.color = parsed.color.trim();
50
+ }
51
+ if (typeof parsed.label === "string" && parsed.label.trim() !== "") {
52
+ res.label = parsed.label.trim();
53
+ }
54
+ if (typeof parsed.image === "string" && parsed.image.trim() !== "") {
55
+ res.image = parsed.image.trim();
56
+ }
57
+ return Object.keys(res).length > 0 ? res : null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }