fix(ctx): collapse oversized bash output
4d8c5b46002bffc467389a2b028cfb03766a3b92
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 2aa00d019726
bugabingas dorkfiles
4d8c5b46002bffc467389a2b028cfb03766a3b92
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+287 / −565 text lines
+82 / −8 text lines
Off-context execution and large-output search for Pi.Pi context blowup fuse for oversized `bash` output.Runs JS, Python, and shell analysis outside the main conversation and searches stored outputs.`ctx` does one thing:## Tools- `ctx`It does **not** run shell/JS/Python jobs. It does **not** inspect files. Use normal Pi tools for normal work.<!-- demo:tools_suite:start --><!-- demo:tools_suite:end -->### `ctx`Search output previously stored by ctx.```json{ "query": "TARGET_EVENT", "source": "bash:178810b1", "limit": 3}````source` is optional, but use the exact label from `ctx:stored` when available.## ThresholdsDefaults:```textPI_CTX_LARGE_OUTPUT_THRESHOLD=20000PI_CTX_ERROR_OUTPUT_THRESHOLD=5000```Meaning:- successful `bash` output > 20KB → stored- failed `bash` output > 5KB → stored + error-oriented preview- smaller output → unchanged## StorageDefault DB path:```text${XDG_STATE_HOME:-~/.local/state}/pi/ctx/<session-file-basename>-<sha256(abs-cwd)[0..16]>.db```Platform fallbacks:```textLinux: ${XDG_STATE_HOME:-~/.local/state}/pi/ctx/macOS: ~/Library/Application Support/pi/ctx/Windows:%LOCALAPPDATA%\\pi\\ctx\\````ctx` still requires the active Pi session file, but only to derive the session id. It does not store under `sessionManager.getSessionDir()`, because that can mix unrelated session runtime data.Override for tests/debug:```bashPI_CTX_DB_PATH=/tmp/ctx.db```In benchmark runs this is inside sandbox HOME:```text/home/bench/.local/state/pi/ctx/<session-id>-<cwd-hash>.db```The DB contains:- `sources` table: labels, byte counts, metadata- `chunks_fts` FTS5 table: chunked searchable output## Example flow```textbash ./dump.sh→ ctx:stored bash:178810b1 (2085.9KB, 135 chunks). Stored output is not in the workspace. Call the ctx tool with {"query":"...","source":"bash:178810b1"}.ctx {"query":"TARGET_EVENT","source":"bash:178810b1"}→ matching snippets only```+0 / −2 text lines
+38 / −67 text lines
import { CtxStore, defaultDbPath, executeCtxOperation, handleBashToolResult, registerCtxExtension, type CtxToolParams } from "../index.js";import { CtxStore, defaultDbPath, executeCtxSearch, handleBashToolResult, registerCtxExtension, stateRoot } from "../index.ts"; process.env.XDG_STATE_HOME = join(dir, "state"); delete process.env.XDG_STATE_HOME; test("defaults under current Pi session dir", () => { test("defaults under current Pi session file", () => { expect(path).toStartWith(join(dir, "sessions", "ctx")); expect(path).toStartWith(join(dir, "state", "pi", "ctx", "session-")); test("uses SessionManager sessionDir when no session file exists", () => { test("uses XDG/native state root", () => { expect(stateRoot({ XDG_STATE_HOME: "/state" } as NodeJS.ProcessEnv, "linux", "/home/me")).toBe("/state/pi"); expect(stateRoot({} as NodeJS.ProcessEnv, "linux", "/home/me")).toBe("/home/me/.local/state/pi"); expect(stateRoot({} as NodeJS.ProcessEnv, "darwin", "/Users/me")).toBe("/Users/me/Library/Application Support/pi"); expect(stateRoot({ LOCALAPPDATA: "C:\\Users\\me\\AppData\\Local" } as NodeJS.ProcessEnv, "win32", "C:\\Users\\me")).toBe("C:\\Users\\me\\AppData\\Local/pi"); }); test("rejects sessionDir-only contexts because storage must be session-scoped", () => { }); expect(path).toStartWith(join(dir, "session-dir", "ctx")); expect(path).toEndWith(".db"); })).toThrow("session file"); const indexed = store.indexText({ kind: "test", label: "sample", text: "alpha beta\npanic stack trace\nomega" }); const hits = store.search(["panic trace"], { limit: 3 }); expect(hits).toContain("panic stack trace"); store.close(); }); test("purges project DB content", () => { const store = new CtxStore(dbPath); store.indexText({ kind: "test", label: "sample", text: "alpha beta" }); expect(store.stats().sources).toBe(1); store.purge(); expect(store.stats().sources).toBe(0); store.close(); });});describe("ctx operations", () => { test("run-js returns printed findings", async () => { const store = new CtxStore(dbPath); const result = await executeCtxOperation(store, { op: "run-js", code: "console.log('answer', 41 + 1)", } satisfies CtxToolParams, dir); expect(result.isError).toBeFalsy(); expect(result.content[0].text).toContain("answer 42"); store.close(); }); test("file-py reads file as text", async () => { const file = join(dir, "data.txt"); writeFileSync(file, "one\ntwo\nthree\n", "utf8"); const store = new CtxStore(dbPath); const result = await executeCtxOperation(store, { op: "file-py", path: file, code: "print(len(text.splitlines()))", } satisfies CtxToolParams, dir); expect(result.content[0].text.trim()).toBe("3"); store.close(); }); test("large run output is indexed and returns pointer", async () => { const store = new CtxStore(dbPath); const result = await executeCtxOperation(store, { op: "run-js", code: "console.log('x'.repeat(110_000))", } satisfies CtxToolParams, dir); expect(result.content[0].text).toContain("ctx:stored"); expect(result.content[0].text).toContain("Use ctx search"); expect(store.stats().sources).toBe(1); expect(store.search(["panic trace"], { limit: 3 })).toContain("panic stack trace"); test("uses fullOutputPath, stores raw, returns bounded replacement", () => { test("leaves small bash output unchanged", () => { const store = new CtxStore(dbPath); expect(handleBashToolResult(store, { toolName: "bash", input: { command: "echo small" }, content: [{ type: "text", text: "small" }], details: {}, isError: false, })).toBeUndefined(); store.close(); }); test("uses fullOutputPath, stores raw, returns bounded replacement without leaking fullOutputPath", () => { expect(text).toContain("Call the ctx tool"); expect(store.search(["CTX_RAW_SENTINEL"], { limit: 1 })).toContain("CTX_RAW_SENTINEL"); test("large error output is searched for failures", () => { test("large error output is stored and searchable", () => { test("registers one tool and one command", () => { test("registers one search tool and a tool_result hook", () => { const commands: Record<string, any> = {}; registerCommand: (name: string, command: any) => { commands[name] = command; },+55 / −135 text lines
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";async function emitBash(params: { command?: string; text: string; fullPath?: boolean; isError?: boolean }) { const details: Record<string, unknown> = {}; let contentText = params.text; if (params.fullPath) { const full = join(root, `bash-${crypto.randomUUID()}.log`); writeFileSync(full, params.text, "utf8"); details.fullOutputPath = full; details.truncation = { truncated: true }; contentText = "[pi truncated visible output]"; } return await t!.session.extensionRunner.emitToolResult({ type: "tool_result", toolName: "bash", input: { command: params.command ?? "generate massive report" }, content: [{ type: "text", text: contentText }], details, isError: params.isError ?? false, });} delete process.env.PI_CTX_DB_PATH; process.env.PI_CTX_DB_PATH = join(sessionDir, "ctx", "harness.db"); it("registers exactly one ctx tool and one ctx command", () => { it("registers exactly one ctx search tool and no command", () => { expect([...extension.commands.keys()]).toEqual(["ctx"]); }); it("runs JS off-context, stores oversized output, and retrieves exact needles later", async () => { const result = await ctxExec({ op: "run-js", query: "ctxneedle12345", code: ` for (let i = 0; i < 9000; i++) console.log('noise line ' + i + ' ' + 'x'.repeat(20)); console.log('ctxneedle12345 fatal failure in generated report'); for (let i = 0; i < 9000; i++) console.log('tail noise ' + i + ' ' + 'y'.repeat(20)); `, }); const text = textOf(result); expect(text).toContain("ctx:stored"); expect(text).toContain("matched"); expect(text.length).toBeLessThan(2_000); expect(text).not.toContain("tail noise 8999"); expect(dbFiles()).toHaveLength(1); const search = await ctxExec({ op: "search", query: "ctxneedle12345", limit: 1 }); const searchText = textOf(search); expect(searchText).toContain("ctxneedle12345 fatal failure"); }); it("analyzes a huge file without returning the file body or indexing small findings", async () => { const file = join(root, "huge.log"); const lines = Array.from({ length: 25_000 }, (_, i) => `row ${i} boring payload ${"z".repeat(40)}`); lines[19_876] = "ctxfilemarker67890 ERROR customer=42 shard=west"; writeFileSync(file, `${lines.join("\n")}\n`, "utf8"); const result = await ctxExec({ op: "file-js", path: file, code: ` const hit = text.split(/\\n/).find(line => line.includes('ctxfilemarker67890')); console.log(hit); `, }); const out = textOf(result); expect(out.trim()).toBe("ctxfilemarker67890 ERROR customer=42 shard=west"); expect(out).not.toContain("row 0 boring payload"); const [extension] = t!.session.extensionRunner.extensions; const stats = await extension.commands.get("ctx").handler("", t!.session.extensionRunner.createContext()); expect(stats.text).toContain("ctx: 0 sources"); expect([...extension.commands.keys()]).toEqual([]); it("collapses huge bash tool_result using fullOutputPath before it reaches the transcript", async () => { const full = join(root, "bash-full.log"); writeFileSync(full, raw, "utf8"); const patched = await t!.session.extensionRunner.emitToolResult({ type: "tool_result", toolName: "bash", input: { command: "generate massive report" }, content: [{ type: "text", text: "[pi truncated visible output]" }], details: { fullOutputPath: full, truncation: { truncated: true } }, isError: false, }); const patched = await emitBash({ text: raw, fullPath: true }); expect(JSON.stringify(patched)).not.toContain("fullOutputPath"); expect(statSync(join(sessionDir, "ctx", dbFiles()[0])).size).toBeGreaterThan(0); expect(dbFiles()).toHaveLength(1); const search = await ctxExec({ op: "search", query: "bashneedle24680", limit: 1 }); const search = await ctxExec({ query: "bashneedle24680", limit: 1 }); it("extracts searchable failure context for huge failing bash output and keeps isError", async () => { const full = join(root, "bash-error.log"); writeFileSync(full, `${"boring\n".repeat(5_000)}panic ctxboom999 exploded\nstack trace line\n`, "utf8"); const patched = await t!.session.extensionRunner.emitToolResult({ type: "tool_result", toolName: "bash", input: { command: "run failing suite" }, content: [{ type: "text", text: "[truncated]" }], details: { fullOutputPath: full }, command: "run failing suite", expect(textOf(patched)).toContain("matched"); const search = await ctxExec({ op: "search", query: "ctxboom999", limit: 1 }); const search = await ctxExec({ query: "ctxboom999", limit: 1 }); it("search returns the matching region when a hit is buried deep inside a chunk", async () => { const filler = Array.from({ length: 180 }, (_, i) => `preface ${i} ${"p".repeat(80)}`).join("\n"); const search = await ctxExec({ op: "search", query: "buriedneedle424242", limit: 1 }); const search = await ctxExec({ query: "buriedneedle424242", limit: 1 }); const search = await ctxExec({ op: "search", query: "realbashneedle777", limit: 1 }); const patched = await t!.session.extensionRunner.emitToolResult({ type: "tool_result", toolCallId: "bash-visible-1", toolName: "bash", input: { command: "already truncated elsewhere" }, content: [{ type: "text", text: visible }], details: { truncation: { truncated: true } }, isError: false, }); const patched = await emitBash({ text: visible }); const search = await ctxExec({ op: "search", query: "visibleonly333", limit: 1 }); const search = await ctxExec({ query: "visibleonly333", limit: 1 }); it("handles concurrent ctx writes without lock errors or lost sources", async () => { it("handles concurrent bash collapses without lock errors or lost sources", async () => { const search = await ctxExec({ op: "search", query: `concurrentneedle${i}`, limit: 1 }); const search = await ctxExec({ query: `concurrentneedle${i}`, limit: 1 }); it("keeps unicode output valid while using byte thresholds conservatively", async () => { it("keeps unicode output searchable", async () => { const result = await ctxExec({ op: "run-js", code: `console.log('${"😀".repeat(40_000)} ${marker}')`, }); await emitBash({ text: `${"😀".repeat(40_000)} ${marker}` }); expect(textOf(result)).toContain("ctx:stored"); const search = await ctxExec({ op: "search", query: "unicodeNeedle555", limit: 1 }); const search = await ctxExec({ query: "unicodeNeedle555", limit: 1 }); await ctxExec({ op: "run-js", code: "console.log('cleanupneedle ' + 'x'.repeat(120_000))" }); await emitBash({ text: `cleanupneedle ${"x".repeat(120_000)}` }); it("does not touch small bash output, then /ctx reports, searches, and purges stored data", async () => { const unchanged = await t!.session.extensionRunner.emitToolResult({ type: "tool_result", toolName: "bash", input: { command: "echo small" }, content: [{ type: "text", text: "small output" }], details: {}, isError: false, }); await ctxExec({ op: "run-js", code: "console.log('cmdneedle13579 ' + 'q'.repeat(120_000))" }); const [extension] = t!.session.extensionRunner.extensions; const command = extension.commands.get("ctx"); const stats = await command.handler("", t!.session.extensionRunner.createContext()); expect(stats.text).toContain("ctx: 1 sources"); expect(stats.text).toContain("recent:"); const found = await command.handler("cmdneedle13579", t!.session.extensionRunner.createContext()); expect(found.text).toContain("cmdneedle13579"); const purged = await command.handler("--purge", t!.session.extensionRunner.createContext()); expect(purged.text).toBe("ctx purged"); const empty = await command.handler("", t!.session.extensionRunner.createContext()); expect(empty.text).toContain("ctx: 0 sources");+111 / −352 text lines
import { spawn } from "node:child_process";const ERROR_QUERY = "errors failures exceptions panic traceback assertion failed error";type ToolPatch = { content: TextContent[]; details?: Record<string, unknown>; isError?: boolean };export type CtxToolParams = | { op: "run-sh"; script: string; query?: string | string[]; timeoutMs?: number } | { op: "run-js"; code: string; query?: string | string[]; timeoutMs?: number } | { op: "run-py"; code: string; query?: string | string[]; timeoutMs?: number } | { op: "file-sh"; path: string; script: string; query?: string | string[]; timeoutMs?: number } | { op: "file-js"; path: string; code: string; query?: string | string[]; timeoutMs?: number } | { op: "file-py"; path: string; code: string; query?: string | string[]; timeoutMs?: number } | { op: "search"; query: string | string[]; source?: string; limit?: number };interface SourceRow { id: number; kind: string; label: string; bytes: number; created_at: string;}export type CtxSearchParams = { query: string | string[]; source?: string; limit?: number };interface RunResult { stdout: string; stderr: string; exitCode: number | null; timedOut: boolean;function envThreshold(name: string, fallback: number): number { const raw = process.env[name]; if (raw === undefined) return fallback; const n = Number(raw); return Number.isFinite(n) && n >= 0 ? n : fallback;}function largeOutputThreshold(): number { return envThreshold("PI_CTX_LARGE_OUTPUT_THRESHOLD", LARGE_OUTPUT_THRESHOLD);}function errorOutputThreshold(): number { return envThreshold("PI_CTX_ERROR_OUTPUT_THRESHOLD", ERROR_OUTPUT_THRESHOLD);function truncateBytes(text: string, max = MAX_RETURN_BYTES): string {function truncateBytes(text: string, max = MAX_SNIPPET_BYTES): string { return content.map((c: any) => c?.type === "text" && typeof c.text === "string" ? c.text : "").join("\n");function snippetForQuery(text: string, query: string, max = 2500): string { if (byteLen(text) <= max) return text.trim();function ftsQuery(query: string): string { const terms = queryTerms(query).slice(0, 24); if (terms.length === 0) return `"${query.replaceAll('"', '""')}"`; return terms.map(term => `"${term.replaceAll('"', '""')}"`).join(" OR ");}function snippetForQuery(text: string, query: string): string { if (byteLen(text) <= MAX_SNIPPET_BYTES) return text.trim(); return truncateBytes(snippet.trim(), max);}function shortHash(text: string): string { return createHash("sha256").update(text).digest("hex").slice(0, 8);}export function defaultDbPath(cwd = process.cwd(), ctx?: any): string { if (process.env.PI_CTX_DB_PATH) return process.env.PI_CTX_DB_PATH; const sessionFile = ctx?.sessionManager?.getSessionFile?.() ?? ctx?.sessionManager?.sessionFile ?? ctx?.sessionFile; const managerDir = ctx?.sessionManager?.getSessionDir?.() ?? ctx?.sessionManager?.sessionDir; const sessionDir = typeof sessionFile === "string" && sessionFile ? dirname(sessionFile) : typeof managerDir === "string" && managerDir ? managerDir : process.env.PI_CODING_AGENT_SESSION_DIR; if (typeof sessionDir !== "string" || !sessionDir) { throw new Error("ctx requires a Pi session dir; use PI_CTX_DB_PATH for tests/no-session runs"); } const base = join(sessionDir, "ctx"); mkdirSync(base, { recursive: true }); const hash = createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 16); return join(base, `${hash}.db`);}function jsonText(value: unknown): string { try { return JSON.stringify(value); } catch { return String(value); }}function normalizeQueries(query: string | string[] | undefined): string[] { if (Array.isArray(query)) return query.map(q => q.trim()).filter(Boolean); if (typeof query === "string" && query.trim()) return [query.trim()]; return [];}function sourceFilter(source: string | undefined): string | undefined { const s = source?.trim(); return s ? `%${s}%` : undefined; return truncateBytes(snippet.trim()); if (current.length > 0 && (current.length >= MAX_CHUNK_LINES || currentBytes + n > MAX_CHUNK_BYTES)) { flush(i); } if (current.length > 0 && (current.length >= MAX_CHUNK_LINES || currentBytes + n > MAX_CHUNK_BYTES)) flush(i);export function stateRoot(env: NodeJS.ProcessEnv = process.env, os = platform(), home = homedir()): string { if (os === "win32") return join(env.LOCALAPPDATA ?? join(home, "AppData", "Local"), "pi"); if (os === "darwin") return join(home, "Library", "Application Support", "pi"); return join(env.XDG_STATE_HOME ?? join(home, ".local", "state"), "pi");}export function defaultDbPath(cwd = process.cwd(), ctx?: any): string { if (process.env.PI_CTX_DB_PATH) return process.env.PI_CTX_DB_PATH; const sessionFile = ctx?.sessionManager?.getSessionFile?.() ?? ctx?.sessionManager?.sessionFile ?? ctx?.sessionFile; if (typeof sessionFile !== "string" || !sessionFile) throw new Error("ctx requires a Pi session file; set PI_CTX_DB_PATH for no-session runs"); const sessionId = basename(sessionFile).replace(/\.jsonl$/, ""); const cwdHash = createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 16); const base = join(stateRoot(), "ctx"); mkdirSync(base, { recursive: true }); return join(base, `${sessionId}-${cwdHash}.db`);} indexText(input: { kind: string; label: string; text: string; metadata?: unknown }): { sourceId: number; chunkCount: number; bytes: number; label: string } { const meta = input.metadata === undefined ? null : JSON.stringify(input.metadata); const source = this.#db.prepare("INSERT INTO sources(kind, label, bytes, metadata) VALUES (?, ?, ?, ?)") .run(input.kind, input.label, bytes, input.metadata === undefined ? null : jsonText(input.metadata)); .run(input.kind, input.label, bytes, meta); const insert = this.#db.prepare("INSERT INTO chunks_fts(source_id, title, text, label, kind) VALUES (?, ?, ?, ?, ?)"); for (const q of clean) { const rows = src ? this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? AND label LIKE ? ORDER BY score LIMIT ?").all(q, src, limit) as SearchRow[] : this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY score LIMIT ?").all(q, limit) as SearchRow[]; lines.push(`## ${q}`); for (const query of clean) { const match = ftsQuery(query); const rows = source ? this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? AND label LIKE ? ORDER BY score LIMIT ?").all(match, `%${source}%`, limit) as SearchRow[] : this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY score LIMIT ?").all(match, limit) as SearchRow[]; lines.push(`## ${query}`); lines.push(snippetForQuery(row.text, q, 2500)); lines.push(snippetForQuery(row.text, query)); intentSearch(indexed: { sourceId: number; chunkCount: number; bytes: number; label: string }, query: string, maxResults = 5): string { const rows = this.#db.prepare("SELECT source_id, title, text, label, kind, bm25(chunks_fts) AS score FROM chunks_fts WHERE chunks_fts MATCH ? AND source_id = ? ORDER BY score LIMIT ?") .all(query, indexed.sourceId, maxResults) as SearchRow[]; const kb = (indexed.bytes / 1024).toFixed(1); if (rows.length === 0) { return [ `ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).`, `No sections matched "${query}".`, `Use ctx search with source "${indexed.label}".`, ].join("\n"); } const lines = [ `ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).`, `${rows.length} sections matched "${query}":`, "", ]; for (const row of rows) { const preview = row.text.split(/\r?\n/).find(Boolean)?.slice(0, 160) ?? ""; lines.push(`- ${row.title}: ${preview}`); } lines.push(""); lines.push(`Use ctx search with source "${indexed.label}" for details.`); return lines.join("\n"); } const kb = (indexed.bytes / 1024).toFixed(1); return `ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).\nUse ctx search with source "${indexed.label}".`; } stats(): { sources: number; bytes: number; recent: SourceRow[] } { const row = this.#db.prepare("SELECT COUNT(*) AS sources, COALESCE(SUM(bytes), 0) AS bytes FROM sources").get() as { sources: number; bytes: number }; const recent = this.#db.prepare("SELECT id, kind, label, bytes, created_at FROM sources ORDER BY id DESC LIMIT 8").all() as SourceRow[]; return { sources: Number(row.sources), bytes: Number(row.bytes), recent }; } formatStats(): string { const stats = this.stats(); const lines = [`ctx: ${stats.sources} sources, ${(stats.bytes / 1024).toFixed(1)}KB stored`]; if (stats.recent.length) { lines.push("recent:"); for (const s of stats.recent) lines.push(`- ${s.label} ${s.kind} ${(s.bytes / 1024).toFixed(1)}KB`); } lines.push("usage: /ctx <query> | /ctx --purge"); return lines.join("\n"); } purge(): void { this.#db.exec("DELETE FROM chunks_fts; DELETE FROM sources;"); return `ctx:stored ${indexed.label} (${(indexed.bytes / 1024).toFixed(1)}KB, ${indexed.chunkCount} chunks).\nStored output is not in the workspace. Call the ctx tool with {"query":"...","source":"${indexed.label}"}.`;async function runProcess(command: string, args: string[], opts: { cwd: string; input?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<RunResult> { return await new Promise((resolve) => { let stdout = ""; let stderr = ""; let settled = false; const child = spawn(command, args, { cwd: opts.cwd, env: opts.env ?? process.env, stdio: [opts.input === undefined ? "ignore" : "pipe", "pipe", "pipe"], signal: opts.signal, }); const finish = (result: RunResult) => { if (settled) return; settled = true; if (timer) clearTimeout(timer); resolve(result); }; const timer = opts.timeoutMs && opts.timeoutMs > 0 ? setTimeout(() => { try { child.kill("SIGTERM"); } catch { /* noop */ } finish({ stdout, stderr, exitCode: null, timedOut: true }); }, opts.timeoutMs) : undefined; child.stdout?.setEncoding("utf8"); child.stderr?.setEncoding("utf8"); child.stdout?.on("data", (chunk: string) => { stdout += chunk; }); child.stderr?.on("data", (chunk: string) => { stderr += chunk; }); child.on("error", (err) => finish({ stdout, stderr: stderr + String(err), exitCode: 1, timedOut: false })); child.on("close", (code) => finish({ stdout, stderr, exitCode: code, timedOut: false })); if (opts.input !== undefined && child.stdin) { child.stdin.end(opts.input); } });async function withTempFile<T>(prefix: string, suffix: string, content: string, fn: (path: string) => Promise<T>): Promise<T> { const dir = await mkdtemp(join(tmpdir(), prefix)); try { const file = join(dir, `script${suffix}`); await writeFile(file, content, "utf8"); return await fn(file); } finally { await rm(dir, { recursive: true, force: true }).catch(() => {}); }function resultText(result: RunResult): { text: string; isError: boolean } { const isError = result.timedOut || (result.exitCode !== 0 && result.exitCode !== null); let text = result.stdout; if (result.stderr) text += (text ? "\n" : "") + result.stderr; if (result.timedOut) text += `\n(timed out)`; if (!text) text = "(no output)"; return { text, isError };function finalizeOutput(store: CtxStore, source: { kind: string; label: string; metadata?: unknown }, text: string, isError: boolean, query?: string | string[]): ToolPatch { const bytes = byteLen(text); const queries = normalizeQueries(query); if (queries.length && bytes > INTENT_SEARCH_THRESHOLD) { const indexed = store.indexText({ ...source, text }); return { content: [{ type: "text", text: store.intentSearch(indexed, queries.join(" ")) }], isError }; } if (isError && bytes > INTENT_SEARCH_THRESHOLD) { const indexed = store.indexText({ ...source, text }); return { content: [{ type: "text", text: store.intentSearch(indexed, ERROR_QUERY) }], isError }; } if (bytes > LARGE_OUTPUT_THRESHOLD) { const indexed = store.indexText({ ...source, text }); return { content: [{ type: "text", text: store.pointer(indexed) }], isError }; } return { content: [{ type: "text", text: truncateBytes(text) }], isError };}export async function executeCtxOperation(store: CtxStore, params: CtxToolParams, cwd: string, signal?: AbortSignal): Promise<ToolPatch> { const timeoutMs = "timeoutMs" in params ? params.timeoutMs : undefined; const query = "query" in params ? params.query : undefined; switch (params.op) { case "search": { return { content: [{ type: "text", text: store.search(normalizeQueries(params.query), { source: params.source, limit: params.limit }) }] }; } case "run-sh": { const r = await runProcess("/bin/sh", ["-c", params.script], { cwd, timeoutMs, signal }); const { text, isError } = resultText(r); return finalizeOutput(store, { kind: "run-sh", label: `run-sh:${shortHash(params.script)}`, metadata: { script: params.script } }, text, isError, query); } case "run-js": { return await withTempFile("pi-ctx-js-", ".js", params.code, async (file) => { const r = await runProcess("bun", [file], { cwd, timeoutMs, signal }); const { text, isError } = resultText(r); return finalizeOutput(store, { kind: "run-js", label: `run-js:${shortHash(params.code)}`, metadata: { code: params.code } }, text, isError, query); }); } case "run-py": { return await withTempFile("pi-ctx-py-", ".py", params.code, async (file) => { const r = await runProcess("python3", [file], { cwd, timeoutMs, signal }); const { text, isError } = resultText(r); return finalizeOutput(store, { kind: "run-py", label: `run-py:${shortHash(params.code)}`, metadata: { code: params.code } }, text, isError, query); }); } case "file-sh": { const path = isAbsolute(params.path) ? params.path : resolve(cwd, params.path); const r = await runProcess("/bin/sh", ["-c", params.script], { cwd, timeoutMs, signal, env: { ...process.env, CTX_FILE: path } }); const { text, isError } = resultText(r); return finalizeOutput(store, { kind: "file-sh", label: `file-sh:${params.path}`, metadata: { path: params.path, script: params.script } }, text, isError, query); } case "file-js": { const path = isAbsolute(params.path) ? params.path : resolve(cwd, params.path); const wrapper = `const path = ${JSON.stringify(path)};\nconst text = await Bun.file(path).text();\n${params.code}\n`; return await withTempFile("pi-ctx-file-js-", ".js", wrapper, async (file) => { const r = await runProcess("bun", [file], { cwd, timeoutMs, signal }); const { text, isError } = resultText(r); return finalizeOutput(store, { kind: "file-js", label: `file-js:${params.path}`, metadata: { path: params.path, code: params.code } }, text, isError, query); }); } case "file-py": { const path = isAbsolute(params.path) ? params.path : resolve(cwd, params.path); const wrapper = `path = ${JSON.stringify(path)}\ntext = open(path, 'r', encoding='utf-8', errors='replace').read()\n${params.code}\n`; return await withTempFile("pi-ctx-file-py-", ".py", wrapper, async (file) => { const r = await runProcess("python3", [file], { cwd, timeoutMs, signal }); const { text, isError } = resultText(r); return finalizeOutput(store, { kind: "file-py", label: `file-py:${params.path}`, metadata: { path: params.path, code: params.code } }, text, isError, query); }); } } const fullPath = event.details?.fullOutputPath; if (typeof fullPath === "string") { try { if (existsSync(fullPath)) full = readFileSync(fullPath, "utf8"); } catch (err) { return { content: [{ type: "text", text: `ctx:suppressed bash output; failed to read fullOutputPath (${err instanceof Error ? err.message : String(err)})` }], details: { ...(event.details ?? {}), ctxSuppressed: true }, isError: event.isError, }; } } if (!event.isError && bytes <= LARGE_OUTPUT_THRESHOLD) return undefined; if (event.isError && bytes <= INTENT_SEARCH_THRESHOLD) return undefined; try { const command = String(event.input?.command ?? "bash"); const label = `${event.isError ? "bash-error" : "bash"}:${shortHash(command)}`; const indexed = store.indexText({ kind: event.isError ? "bash-error" : "bash", label, text: full, metadata: { command } }); const text = event.isError ? store.intentSearch(indexed, ERROR_QUERY) : store.pointer(indexed); return { content: [{ type: "text", text }], details: { ...(event.details ?? {}), ctxStored: true, ctxSource: label }, isError: event.isError, }; } catch (err) { return { content: [{ type: "text", text: `ctx:suppressed ${bytes}B bash output; storage failed (${err instanceof Error ? err.message : String(err)})` }], details: { ...(event.details ?? {}), ctxSuppressed: true }, isError: event.isError, }; }}function makeStore(ctx?: any): CtxStore { const cwd = ctx?.cwd ?? process.cwd(); return new CtxStore(defaultDbPath(cwd, ctx)); if (!event.isError && bytes <= largeOutputThreshold()) return undefined; if (event.isError && bytes <= errorOutputThreshold()) return undefined; const command = String(event.input?.command ?? "bash"); const label = `${event.isError ? "bash-error" : "bash"}:${shortHash(command)}`; const indexed = store.indexText({ kind: event.isError ? "bash-error" : "bash", label, text: full, metadata: { command } }); const text = event.isError ? `${store.pointer(indexed)}\n\n${store.search([ERROR_QUERY], { source: label, limit: 3 })}` : store.pointer(indexed); const { fullOutputPath: _fullOutputPath, ...safeDetails } = event.details ?? {}; return { content: [{ type: "text", text }], details: { ...safeDetails, ctxStored: true, ctxSource: label }, isError: event.isError, }; op: Type.Union([ Type.Literal("run-sh"), Type.Literal("run-js"), Type.Literal("run-py"), Type.Literal("file-sh"), Type.Literal("file-js"), Type.Literal("file-py"), Type.Literal("search"), ], { description: "Operation" }), script: Type.Optional(Type.String({ description: "Shell script for run-sh/file-sh" })), code: Type.Optional(Type.String({ description: "JS/Python code for run-js/run-py/file-js/file-py" })), path: Type.Optional(Type.String({ description: "File path for file-* ops" })), query: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], { description: "Search query / intent" })), source: Type.Optional(Type.String({ description: "Source label substring for search" })), limit: Type.Optional(Type.Number({ description: "Search results per query" })), timeoutMs: Type.Optional(Type.Number({ description: "Timeout in ms" })),function normalizeParams(raw: any): CtxToolParams { if (!raw || typeof raw !== "object") throw new Error("ctx params object required"); switch (raw.op) { case "run-sh": if (typeof raw.script === "string") return raw; break; case "run-js": if (typeof raw.code === "string") return raw; break; case "run-py": if (typeof raw.code === "string") return raw; break; case "file-sh": if (typeof raw.path === "string" && typeof raw.script === "string") return raw; break; case "file-js": if (typeof raw.path === "string" && typeof raw.code === "string") return raw; break; case "file-py": if (typeof raw.path === "string" && typeof raw.code === "string") return raw; break; case "search": if (typeof raw.query === "string" || Array.isArray(raw.query)) return raw; break; } throw new Error("invalid ctx params for op");}export function registerCtxExtension(pi: Pick<ExtensionAPI, "registerTool" | "registerCommand" | "on">): void {export function registerCtxExtension(pi: Pick<ExtensionAPI, "registerTool" | "on">): void { const { fullOutputPath: _fullOutputPath, ...safeDetails } = event.details ?? {}; name: "ctx", label: "ctx", description: "Run JS/Py/sh analysis off-context; search stored large bash output.", promptSnippet: "Run JS/Py/sh analysis off-context; search stored large bash output.", promptGuidelines: [ "Use ctx run-* for large-output analysis; print only findings.", "Use ctx file-* for large file analysis without reading whole files into context.", "Use ctx search when bash output was stored as ctx:stored.", ], name: TOOL_NAME, label: "ctx search", description: "Search command output that ctx previously stored after it exceeded the safe context threshold.", promptSnippet: "Use only after a tool result says ctx:stored.", promptGuidelines: ["Call ctx with query and optional source from ctx:stored to inspect suppressed large bash output."], async execute(_toolCallId: string, raw: unknown, signal?: AbortSignal, _onUpdate?: unknown, ctx?: any) { async execute(_toolCallId: string, raw: unknown, _signal?: AbortSignal, _onUpdate?: unknown, ctx?: any) { const params = normalizeParams(raw); return await executeCtxOperation(store, params, ctx?.cwd ?? process.cwd(), signal); return executeCtxSearch(store, normalizeSearchParams(raw)); return { content: [{ type: "text", text: `ctx error: ${err instanceof Error ? err.message : String(err)}` }], details: {}, isError: true }; pi.registerCommand("ctx", { description: "ctx stats/search/purge", handler: async (args: unknown, ctx: any) => { const q = String(args ?? "").trim(); const store = makeStore(ctx); try { if (q === "--purge") { if (ctx?.hasUI) { const ok = await ctx.ui.confirm("ctx purge", "Delete ctx index for this project?"); if (!ok) return { text: "ctx purge cancelled" }; } store.purge(); return { text: "ctx purged" }; } if (!q) return { text: store.formatStats() }; return { text: store.search([q], { limit: 5 }) }; } finally { store.close(); } }, });+1 / −1 text lines