1 -import { spawn }
from "node:child_process";
2 1 import { createHash }
from "node:crypto";
3 -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync }
from "node:fs";
4 -import { mkdtemp, rm, writeFile }
from "node:fs/promises";
5 -import { tmpdir }
from "node:os";
6 -import { dirname, isAbsolute, join, resolve }
from "node:path";
2 +import { existsSync, mkdirSync, readFileSync }
from "node:fs";
3 +import { basename, dirname, join, resolve }
from "node:path";
4 +import { homedir, platform }
from "node:os";
7 5 import { Type }
from "typebox";
8 6 import type { ExtensionAPI }
from "@earendil-works/pi-coding-agent";
10 -const INTENT_SEARCH_THRESHOLD
= 5_000;
11 -const LARGE_OUTPUT_THRESHOLD
= 102_400;
12 -const MAX_RETURN_BYTES
= 12_000;
8 +const TOOL_NAME
= "ctx";
9 +const LARGE_OUTPUT_THRESHOLD
= 20_000;
10 +const ERROR_OUTPUT_THRESHOLD
= 5_000;
13 11 const MAX_CHUNK_BYTES
= 16_000;
14 12 const MAX_CHUNK_LINES
= 200;
15 -const ERROR_QUERY
= "errors failures exceptions panic traceback assertion failed error";
13 +const MAX_SNIPPET_BYTES
= 2_500;
14 +const ERROR_QUERY
= "error failed failure exception panic traceback assertion";
17 16 type TextContent = { type
: "text"; text
: string };
18 17 type ToolPatch = { content
: TextContent[]; details
?: Record<
string,
unknown>; isError
?: boolean };
20 -export type CtxToolParams = 21 - | { op
: "run-sh"; script
: string; query
?: string | string[]; timeoutMs
?: number }
22 - | { op
: "run-js"; code
: string; query
?: string | string[]; timeoutMs
?: number }
23 - | { op
: "run-py"; code
: string; query
?: string | string[]; timeoutMs
?: number }
24 - | { op
: "file-sh"; path
: string; script
: string; query
?: string | string[]; timeoutMs
?: number }
25 - | { op
: "file-js"; path
: string; code
: string; query
?: string | string[]; timeoutMs
?: number }
26 - | { op
: "file-py"; path
: string; code
: string; query
?: string | string[]; timeoutMs
?: number }
27 - | { op
: "search"; query
: string | string[]; source
?: string; limit
?: number };
29 -interface SourceRow {
18 +export type CtxSearchParams = { query
: string | string[]; source
?: string; limit
?: number };
37 20 interface SearchRow {
46 -interface RunResult {
49 - exitCode
: number | null;
29 +function envThreshold(name
: string, fallback
: number)
: number {
30 + const raw
= process.
env[name];
31 + if (raw
=== undefined)
return fallback;
32 + const n
= Number(raw);
33 + return Number.
isFinite(n)
&& n
>= 0 ? n
: fallback;
36 +function largeOutputThreshold()
: number {
37 + return envThreshold(
"PI_CTX_LARGE_OUTPUT_THRESHOLD", LARGE_OUTPUT_THRESHOLD);
40 +function errorOutputThreshold()
: number {
41 + return envThreshold(
"PI_CTX_ERROR_OUTPUT_THRESHOLD", ERROR_OUTPUT_THRESHOLD);
53 44 function byteLen(text
: string)
: number {
54 45 return Buffer.
byteLength(text,
"utf8");
57 -function truncateBytes(text
: string, max
= MAX_RETURN_BYTES)
: string {
48 +function truncateBytes(text
: string, max
= MAX_SNIPPET_BYTES)
: string {
58 49 if (
byteLen(text)
<= max)
return text;
72 63 return content.
map((c
: any)
=> c?.
type === "text" && typeof c.
text === "string" ? c.
text : "").
join(
"\n");
66 +function shortHash(text
: string)
: string {
67 + return createHash(
"sha256").
update(text).
digest(
"hex").
slice(
0,
8);
75 70 function queryTerms(query
: string)
: string[] {
76 71 return [
...query.
matchAll(
/[\p{L}\p{N}_]{2,}/gu)]
77 72 .
map(match
=> match[
0].
toLowerCase())
78 73 .
filter(term
=> ![
"and",
"or",
"not",
"near"].
includes(term));
81 -function snippetForQuery(text
: string, query
: string, max
= 2500)
: string {
82 - if (
byteLen(text)
<= max)
return text.
trim();
76 +function ftsQuery(query
: string)
: string {
77 + const terms
= queryTerms(query).
slice(
0,
24);
78 + if (terms.
length === 0)
return `"${query.replaceAll('"', '""')}"`;
79 + return terms.
map(term
=> `"${term.replaceAll('"', '""')}"`).
join(
" OR ");
82 +function snippetForQuery(text
: string, query
: string)
: string {
83 + if (
byteLen(text)
<= MAX_SNIPPET_BYTES)
return text.
trim();
83 84 const lower
= text.
toLowerCase();
85 86 for (
const term
of queryTerms(query)) {
86 87 const next
= lower.
indexOf(term);
87 88 if (next
>= 0 && (pos
< 0 || next
< pos)) pos
= next;
89 - if (pos
< 0)
return truncateBytes(text.
trim(), max);
90 - let start
= Math.
max(
0, pos
- Math.
floor(max
/ 3));
90 + if (pos
< 0)
return truncateBytes(text.
trim());
91 + let start
= Math.
max(
0, pos
- Math.
floor(MAX_SNIPPET_BYTES
/ 3));
91 92 const newline
= text.
lastIndexOf(
"\n", pos);
92 93 if (newline
>= 0 && newline
>= start
- 500) start
= newline
+ 1;
93 94 let snippet
= text.
slice(start);
94 95 if (start
> 0) snippet
= `…\n${snippet}`;
95 - return truncateBytes(snippet.
trim(), max);
98 -function shortHash(text
: string)
: string {
99 - return createHash(
"sha256").
update(text).
digest(
"hex").
slice(
0,
8);
102 -export function defaultDbPath(cwd
= process.
cwd(), ctx
?: any)
: string {
103 - if (
process.
env.PI_CTX_DB_PATH)
return process.
env.PI_CTX_DB_PATH;
104 - const sessionFile
= ctx?.sessionManager?.
getSessionFile?.()
105 - ?? ctx?.sessionManager?.sessionFile
106 - ?? ctx?.sessionFile;
107 - const managerDir
= ctx?.sessionManager?.
getSessionDir?.()
108 - ?? ctx?.sessionManager?.sessionDir;
109 - const sessionDir
= typeof sessionFile
=== "string" && sessionFile
110 - ? dirname(sessionFile)
111 - : typeof managerDir
=== "string" && managerDir
113 - : process.
env.PI_CODING_AGENT_SESSION_DIR;
114 - if (
typeof sessionDir
!== "string" || !sessionDir) {
115 - throw new Error(
"ctx requires a Pi session dir; use PI_CTX_DB_PATH for tests/no-session runs");
117 - const base
= join(sessionDir,
"ctx");
118 - mkdirSync(base, { recursive:
true });
119 - const hash
= createHash(
"sha256").
update(
resolve(cwd)).
digest(
"hex").
slice(
0,
16);
120 - return join(base,
`${hash}.db`);
123 -function jsonText(value
: unknown)
: string {
124 - try {
return JSON.
stringify(value); }
catch {
return String(value); }
127 -function normalizeQueries(query
: string | string[]
| undefined)
: string[] {
128 - if (
Array.
isArray(query))
return query.
map(q
=> q.
trim()).
filter(
Boolean);
129 - if (
typeof query
=== "string" && query.
trim())
return [query.
trim()];
133 -function sourceFilter(source
: string | undefined)
: string | undefined {
134 - const s
= source?.
trim();
135 - return s
? `%${s}%` : undefined;
96 + return truncateBytes(snippet.
trim());
138 99 function chunkText(text
: string)
: Array<{ title
: string; text
: string }> {
151 112 for (
let i
= 0; i
< lines.
length; i
++) {
152 113 const line
= lines[i]
?? "";
153 114 const n
= byteLen(line)
+ 1;
154 - if (current.
length > 0 && (current.
length >= MAX_CHUNK_LINES
|| currentBytes
+ n
> MAX_CHUNK_BYTES)) {
115 + if (current.
length > 0 && (current.
length >= MAX_CHUNK_LINES
|| currentBytes
+ n
> MAX_CHUNK_BYTES))
flush(i);
157 116 current.
push(line);
158 117 currentBytes
+= n;
161 120 return chunks.
length ? chunks
: [{ title:
"output", text }];
123 +export function stateRoot(env
: NodeJS.
ProcessEnv = process.
env, os
= platform(), home
= homedir())
: string {
124 + if (os
=== "win32")
return join(env.LOCALAPPDATA
?? join(home,
"AppData",
"Local"),
"pi");
125 + if (os
=== "darwin")
return join(home,
"Library",
"Application Support",
"pi");
126 + return join(env.XDG_STATE_HOME
?? join(home,
".local",
"state"),
"pi");
129 +export function defaultDbPath(cwd
= process.
cwd(), ctx
?: any)
: string {
130 + if (
process.
env.PI_CTX_DB_PATH)
return process.
env.PI_CTX_DB_PATH;
131 + const sessionFile
= ctx?.sessionManager?.
getSessionFile?.()
132 + ?? ctx?.sessionManager?.sessionFile
133 + ?? ctx?.sessionFile;
134 + if (
typeof sessionFile
!== "string" || !sessionFile)
throw new Error(
"ctx requires a Pi session file; set PI_CTX_DB_PATH for no-session runs");
135 + const sessionId
= basename(sessionFile).
replace(
/\.jsonl$/,
"");
136 + const cwdHash
= createHash(
"sha256").
update(
resolve(cwd)).
digest(
"hex").
slice(
0,
16);
137 + const base
= join(
stateRoot(),
"ctx");
138 + mkdirSync(base, { recursive:
true });
139 + return join(base,
`${sessionId}-${cwdHash}.db`);
164 142 export class CtxStore {
166 144 readonly dbPath
: string;
195 173 indexText(input: { kind: string; label: string; text: string; metadata
?: unknown }): { sourceId: number; chunkCount: number; bytes: number; label: string } {
196 174 const bytes
= byteLen(input.
text);
175 + const meta
= input.metadata
=== undefined ? null : JSON.
stringify(input.metadata);
197 176 const source
= this.#db.
prepare(
"INSERT INTO sources(kind, label, bytes, metadata) VALUES (?, ?, ?, ?)")
198 - .
run(input.kind, input.
label, bytes, input.metadata
=== undefined ? null : jsonText(input.metadata));
177 + .
run(input.kind, input.
label, bytes, meta);
199 178 const sourceId
= Number(source.lastInsertRowid);
200 179 const insert
= this.#db.
prepare(
"INSERT INTO chunks_fts(source_id, title, text, label, kind) VALUES (?, ?, ?, ?, ?)");
201 180 const chunks
= chunkText(input.
text);
210 189 const clean
= queries.
map(q
=> q.
trim()).
filter(
Boolean);
211 190 if (clean.
length === 0)
return "ctx: empty query";
212 191 const limit
= Math.
max(
1,
Math.
min(opts.limit
?? 3,
10));
213 - const src
= sourceFilter(opts.
source);
192 + const source
= opts.
source?.
trim();
214 193 const lines
: string[]
= [];
215 - for (
const q
of clean) {
217 - ? 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[]
218 - : 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[];
219 - lines.
push(
`## ${q}`);
194 + for (
const query
of clean) {
195 + const match
= ftsQuery(query);
196 + const rows
= source
197 + ? 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[]
198 + : 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[];
199 + lines.
push(
`## ${query}`);
220 200 if (rows.
length === 0) {
221 201 lines.
push(
"no matches");
224 204 for (
const row
of rows) {
225 205 lines.
push(
`### ${row.label} · ${row.title}`);
226 - lines.
push(
snippetForQuery(row.
text, q,
2500));
206 + lines.
push(
snippetForQuery(row.
text, query));
229 209 return lines.
join(
"\n");
232 - intentSearch(indexed: { sourceId: number; chunkCount: number; bytes: number; label: string }, query: string, maxResults
= 5): string {
233 - 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 ?")
234 - .
all(query, indexed.sourceId, maxResults)
as SearchRow[];
235 - const kb
= (indexed.bytes
/ 1024).
toFixed(
1);
236 - if (rows.
length === 0) {
238 - `ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).`,
239 - `No sections matched "${query}".`,
240 - `Use ctx search with source "${indexed.label}".`,
244 - `ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).`,
245 - `${rows.length} sections matched "${query}":`,
248 - for (
const row
of rows) {
249 - const preview
= row.
text.
split(
/\r?\n/).
find(
Boolean)?.
slice(
0,
160)
?? "";
250 - lines.
push(
`- ${row.title}: ${preview}`);
253 - lines.
push(
`Use ctx search with source "${indexed.label}" for details.`);
254 - return lines.
join(
"\n");
257 212 pointer(indexed: { chunkCount: number; bytes: number; label: string }): string {
258 - const kb
= (indexed.bytes
/ 1024).
toFixed(
1);
259 - return `ctx:stored ${indexed.label} (${kb}KB, ${indexed.chunkCount} chunks).\nUse ctx search with source "${indexed.label}".`;
262 - stats(): { sources: number; bytes: number; recent: SourceRow[] } {
263 - const row
= this.#db.
prepare(
"SELECT COUNT(*) AS sources, COALESCE(SUM(bytes), 0) AS bytes FROM sources").
get()
as { sources
: number; bytes
: number };
264 - const recent
= this.#db.
prepare(
"SELECT id, kind, label, bytes, created_at FROM sources ORDER BY id DESC LIMIT 8").
all()
as SourceRow[];
265 - return { sources:
Number(row.sources), bytes:
Number(row.bytes), recent };
268 - formatStats(): string {
269 - const stats
= this.
stats();
270 - const lines
= [
`ctx: ${stats.sources} sources, ${(stats.bytes / 1024).toFixed(1)}KB stored`];
271 - if (stats.recent.
length) {
272 - lines.
push(
"recent:");
273 - for (
const s
of stats.recent) lines.
push(
`- ${s.label} ${s.kind} ${(s.bytes / 1024).toFixed(1)}KB`);
275 - lines.
push(
"usage: /ctx <query> | /ctx --purge");
276 - return lines.
join(
"\n");
280 - this.#db.
exec(
"DELETE FROM chunks_fts; DELETE FROM sources;");
213 + 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}"}.`;
288 -async function runProcess(command
: string, args
: string[], opts
: { cwd
: string; input
?: string; env
?: NodeJS.
ProcessEnv; timeoutMs
?: number; signal
?: AbortSignal })
: Promise<
RunResult> {
289 - return await new Promise((resolve)
=> {
292 - let settled
= false;
293 - const child
= spawn(command, args, {
295 - env: opts.env
?? process.
env,
296 - stdio: [opts.
input === undefined ? "ignore" : "pipe",
"pipe",
"pipe"],
297 - signal: opts.signal,
299 - const finish = (result
: RunResult)
=> {
300 - if (settled)
return;
302 - if (timer)
clearTimeout(timer);
305 - const timer
= opts.timeoutMs
&& opts.timeoutMs
> 0 ? setTimeout(()
=> {
306 - try { child.
kill(
"SIGTERM"); }
catch { }
307 - finish({ stdout, stderr, exitCode:
null, timedOut:
true });
308 - }, opts.timeoutMs)
: undefined;
309 - child.stdout?.
setEncoding(
"utf8");
310 - child.stderr?.
setEncoding(
"utf8");
311 - child.stdout?.
on(
"data", (chunk
: string)
=> { stdout
+= chunk; });
312 - child.stderr?.
on(
"data", (chunk
: string)
=> { stderr
+= chunk; });
313 - child.
on(
"error", (err)
=> finish({ stdout, stderr: stderr
+ String(err), exitCode:
1, timedOut:
false }));
314 - child.
on(
"close", (code)
=> finish({ stdout, stderr, exitCode: code, timedOut:
false }));
315 - if (opts.
input !== undefined && child.stdin) {
316 - child.stdin.
end(opts.
input);
221 +function makeStore(ctx
?: any)
: CtxStore {
222 + return new CtxStore(
defaultDbPath(ctx?.cwd
?? process.
cwd(), ctx));
321 -async function withTempFile<
T>(prefix
: string, suffix
: string, content
: string,
fn: (path
: string)
=> Promise<
T>)
: Promise<
T> {
322 - const dir
= await mkdtemp(
join(
tmpdir(), prefix));
324 - const file
= join(dir,
`script${suffix}`);
325 - await writeFile(file, content,
"utf8");
326 - return await fn(file);
328 - await rm(dir, { recursive:
true, force:
true }).
catch(()
=> {});
225 +function normalizeQueries(query
: string | string[])
: string[] {
226 + return Array.
isArray(query)
? query.
map(q
=> q.
trim()).
filter(
Boolean)
: [query.
trim()].
filter(
Boolean);
332 -function resultText(result
: RunResult)
: { text
: string; isError
: boolean } {
333 - const isError
= result.timedOut
|| (result.exitCode
!== 0 && result.exitCode
!== null);
334 - let text
= result.stdout;
335 - if (result.stderr) text
+= (text
? "\n" : "")
+ result.stderr;
336 - if (result.timedOut) text
+= `\n(timed out)`;
337 - if (
!text) text
= "(no output)";
338 - return { text, isError };
229 +function normalizeSearchParams(raw
: any)
: CtxSearchParams {
230 + if (
!raw
|| typeof raw
!== "object")
throw new Error(
"ctx params object required");
231 + if (
typeof raw.query
=== "string" || Array.
isArray(raw.query))
return raw;
232 + throw new Error(
"ctx requires query");
341 -function finalizeOutput(store
: CtxStore, source
: { kind
: string; label
: string; metadata
?: unknown }, text
: string, isError
: boolean, query
?: string | string[])
: ToolPatch {
342 - const bytes
= byteLen(text);
343 - const queries
= normalizeQueries(query);
344 - if (queries.
length && bytes
> INTENT_SEARCH_THRESHOLD) {
345 - const indexed
= store.
indexText({
...source, text });
346 - return { content: [{ type:
"text", text: store.
intentSearch(indexed, queries.
join(
" ")) }], isError };
348 - if (isError
&& bytes
> INTENT_SEARCH_THRESHOLD) {
349 - const indexed
= store.
indexText({
...source, text });
350 - return { content: [{ type:
"text", text: store.
intentSearch(indexed, ERROR_QUERY) }], isError };
352 - if (bytes
> LARGE_OUTPUT_THRESHOLD) {
353 - const indexed
= store.
indexText({
...source, text });
354 - return { content: [{ type:
"text", text: store.
pointer(indexed) }], isError };
356 - return { content: [{ type:
"text", text:
truncateBytes(text) }], isError };
359 -export async function executeCtxOperation(store
: CtxStore, params
: CtxToolParams, cwd
: string, signal
?: AbortSignal)
: Promise<
ToolPatch> {
360 - const timeoutMs
= "timeoutMs" in params
? params.timeoutMs
: undefined;
361 - const query
= "query" in params
? params.query
: undefined;
362 - switch (params.op) {
364 - return { content: [{ type:
"text", text: store.
search(
normalizeQueries(params.query), { source: params.
source, limit: params.limit }) }] };
367 - const r
= await runProcess(
"/bin/sh", [
"-c", params.script], { cwd, timeoutMs, signal });
368 - const { text, isError }
= resultText(r);
369 - return finalizeOutput(store, { kind:
"run-sh", label:
`run-sh:${shortHash(params.script)}`, metadata: { script: params.script } }, text, isError, query);
372 - return await withTempFile(
"pi-ctx-js-",
".js", params.
code,
async (file)
=> {
373 - const r
= await runProcess(
"bun", [file], { cwd, timeoutMs, signal });
374 - const { text, isError }
= resultText(r);
375 - return finalizeOutput(store, { kind:
"run-js", label:
`run-js:${shortHash(params.code)}`, metadata: { code: params.
code } }, text, isError, query);
379 - return await withTempFile(
"pi-ctx-py-",
".py", params.
code,
async (file)
=> {
380 - const r
= await runProcess(
"python3", [file], { cwd, timeoutMs, signal });
381 - const { text, isError }
= resultText(r);
382 - return finalizeOutput(store, { kind:
"run-py", label:
`run-py:${shortHash(params.code)}`, metadata: { code: params.
code } }, text, isError, query);
386 - const path
= isAbsolute(params.path)
? params.path
: resolve(cwd, params.path);
387 - const r
= await runProcess(
"/bin/sh", [
"-c", params.script], { cwd, timeoutMs, signal, env: {
...process.
env, CTX_FILE: path } });
388 - const { text, isError }
= resultText(r);
389 - return finalizeOutput(store, { kind:
"file-sh", label:
`file-sh:${params.path}`, metadata: { path: params.path, script: params.script } }, text, isError, query);
392 - const path
= isAbsolute(params.path)
? params.path
: resolve(cwd, params.path);
393 - const wrapper
= `const path = ${JSON.stringify(path)};\nconst text = await Bun.file(path).text();\n${params.code}\n`;
394 - return await withTempFile(
"pi-ctx-file-js-",
".js", wrapper,
async (file)
=> {
395 - const r
= await runProcess(
"bun", [file], { cwd, timeoutMs, signal });
396 - const { text, isError }
= resultText(r);
397 - return finalizeOutput(store, { kind:
"file-js", label:
`file-js:${params.path}`, metadata: { path: params.path, code: params.
code } }, text, isError, query);
401 - const path
= isAbsolute(params.path)
? params.path
: resolve(cwd, params.path);
402 - const wrapper
= `path = ${JSON.stringify(path)}\ntext = open(path, 'r', encoding='utf-8', errors='replace').read()\n${params.code}\n`;
403 - return await withTempFile(
"pi-ctx-file-py-",
".py", wrapper,
async (file)
=> {
404 - const r
= await runProcess(
"python3", [file], { cwd, timeoutMs, signal });
405 - const { text, isError }
= resultText(r);
406 - return finalizeOutput(store, { kind:
"file-py", label:
`file-py:${params.path}`, metadata: { path: params.path, code: params.
code } }, text, isError, query);
235 +export function executeCtxSearch(store
: CtxStore, params
: CtxSearchParams)
: ToolPatch {
236 + return { content: [{ type:
"text", text: store.
search(
normalizeQueries(params.query), { source: params.
source, limit: params.limit }) }] };
412 239 export function handleBashToolResult(store
: CtxStore, event
: any)
: ToolPatch | undefined {
413 240 if (
event?.toolName
!== "bash")
return undefined;
414 241 const visible
= textOf(
event.
content);
415 - const fullPath
= event.details?.fullOutputPath;
416 242 let full
= visible;
417 - if (
typeof fullPath
=== "string") {
419 - if (
existsSync(fullPath)) full
= readFileSync(fullPath,
"utf8");
422 - content: [{ type:
"text", text:
`ctx:suppressed bash output; failed to read fullOutputPath (${err instanceof Error ? err.message : String(err)})` }],
423 - details: {
...(
event.details
?? {}), ctxSuppressed:
true },
424 - isError:
event.isError,
243 + const fullPath
= event.details?.fullOutputPath;
244 + if (
typeof fullPath
=== "string" && existsSync(fullPath)) full
= readFileSync(fullPath,
"utf8");
428 245 const bytes
= byteLen(full);
429 - if (
!event.isError
&& bytes
<= LARGE_OUTPUT_THRESHOLD)
return undefined;
430 - if (
event.isError
&& bytes
<= INTENT_SEARCH_THRESHOLD)
return undefined;
432 - const command
= String(
event.
input?.command
?? "bash");
433 - const label
= `${event.isError ? "bash-error" : "bash"}:${shortHash(command)}`;
434 - const indexed
= store.
indexText({ kind:
event.isError
? "bash-error" : "bash", label, text: full, metadata: { command } });
435 - const text
= event.isError
? store.
intentSearch(indexed, ERROR_QUERY)
: store.
pointer(indexed);
437 - content: [{ type:
"text", text }],
438 - details: {
...(
event.details
?? {}), ctxStored:
true, ctxSource: label },
439 - isError:
event.isError,
443 - content: [{ type:
"text", text:
`ctx:suppressed ${bytes}B bash output; storage failed (${err instanceof Error ? err.message : String(err)})` }],
444 - details: {
...(
event.details
?? {}), ctxSuppressed:
true },
445 - isError:
event.isError,
450 -function makeStore(ctx
?: any)
: CtxStore {
451 - const cwd
= ctx?.cwd
?? process.
cwd();
452 - return new CtxStore(
defaultDbPath(cwd, ctx));
246 + if (
!event.isError
&& bytes
<= largeOutputThreshold())
return undefined;
247 + if (
event.isError
&& bytes
<= errorOutputThreshold())
return undefined;
248 + const command
= String(
event.
input?.command
?? "bash");
249 + const label
= `${event.isError ? "bash-error" : "bash"}:${shortHash(command)}`;
250 + const indexed
= store.
indexText({ kind:
event.isError
? "bash-error" : "bash", label, text: full, metadata: { command } });
251 + const text
= event.isError
252 + ? `${store.pointer(indexed)}\n\n${store.search([ERROR_QUERY], { source: label, limit: 3 })}` 253 + : store.
pointer(indexed);
254 + const { fullOutputPath: _fullOutputPath,
...safeDetails }
= event.details
?? {};
256 + content: [{ type:
"text", text }],
257 + details: {
...safeDetails, ctxStored:
true, ctxSource: label },
258 + isError:
event.isError,
455 262 const Params
= Type.
Object({
457 - Type.
Literal(
"run-sh"), Type.
Literal(
"run-js"), Type.
Literal(
"run-py"),
458 - Type.
Literal(
"file-sh"), Type.
Literal(
"file-js"), Type.
Literal(
"file-py"), Type.
Literal(
"search"),
459 - ], { description:
"Operation" }),
460 - script: Type.
Optional(Type.
String({ description:
"Shell script for run-sh/file-sh" })),
461 - code: Type.
Optional(Type.
String({ description:
"JS/Python code for run-js/run-py/file-js/file-py" })),
462 - path: Type.
Optional(Type.
String({ description:
"File path for file-* ops" })),
463 - query: Type.
Optional(Type.
Union([Type.
String(), Type.
Array(Type.
String())], { description:
"Search query / intent" })),
464 - source: Type.
Optional(Type.
String({ description:
"Source label substring for search" })),
465 - limit: Type.
Optional(Type.
Number({ description:
"Search results per query" })),
466 - timeoutMs: Type.
Optional(Type.
Number({ description:
"Timeout in ms" })),
263 + query: Type.
Union([Type.
String(), Type.
Array(Type.
String())], { description:
"Search query" }),
264 + source: Type.
Optional(Type.
String({ description:
"Source label from ctx:stored" })),
265 + limit: Type.
Optional(Type.
Number({ description:
"Max results per query" })),
469 -function normalizeParams(raw
: any)
: CtxToolParams {
470 - if (
!raw
|| typeof raw
!== "object")
throw new Error(
"ctx params object required");
472 - case "run-sh":
if (
typeof raw.script
=== "string")
return raw;
break;
473 - case "run-js":
if (
typeof raw.
code === "string")
return raw;
break;
474 - case "run-py":
if (
typeof raw.
code === "string")
return raw;
break;
475 - case "file-sh":
if (
typeof raw.path
=== "string" && typeof raw.script
=== "string")
return raw;
break;
476 - case "file-js":
if (
typeof raw.path
=== "string" && typeof raw.
code === "string")
return raw;
break;
477 - case "file-py":
if (
typeof raw.path
=== "string" && typeof raw.
code === "string")
return raw;
break;
478 - case "search":
if (
typeof raw.query
=== "string" || Array.
isArray(raw.query))
return raw;
break;
480 - throw new Error(
"invalid ctx params for op");
483 -export function registerCtxExtension(pi
: Pick<
ExtensionAPI,
"registerTool" | "registerCommand" | "on">)
: void {
268 +export function registerCtxExtension(pi
: Pick<
ExtensionAPI,
"registerTool" | "on">)
: void {
484 269 pi.
on(
"tool_result", (event
: any, ctx
: any)
=> {
485 270 let store
: CtxStore | undefined;
487 272 store
= makeStore(ctx);
488 273 return handleBashToolResult(store,
event);
490 - const text
= textOf(
event?.
content);
491 - const maybeLarge
= event?.toolName
=== "bash" && (
event?.details?.fullOutputPath
|| byteLen(text)
> LARGE_OUTPUT_THRESHOLD);
275 + const visible
= textOf(
event?.
content);
276 + const maybeLarge
= event?.toolName
=== "bash" && (
event?.details?.fullOutputPath
|| byteLen(visible)
> largeOutputThreshold());
492 277 if (
!maybeLarge)
return undefined;
278 + const { fullOutputPath: _fullOutputPath,
...safeDetails }
= event.details
?? {};
494 - content: [{ type:
"text", text:
`ctx:suppressed bash output; store unavailable (${err instanceof Error ? err.message : String(err)})` }],
495 - details: {
...(
event.details
?? {}), ctxSuppressed:
true },
280 + content: [{ type:
"text", text:
`ctx:suppressed bash output; storage failed (${err instanceof Error ? err.message : String(err)})` }],
281 + details: {
...safeDetails, ctxSuppressed:
true },
496 282 isError:
event.isError,
503 289 pi.
registerTool({
506 - description:
"Run JS/Py/sh analysis off-context; search stored large bash output.",
507 - promptSnippet:
"Run JS/Py/sh analysis off-context; search stored large bash output.",
508 - promptGuidelines: [
509 - "Use ctx run-* for large-output analysis; print only findings.",
510 - "Use ctx file-* for large file analysis without reading whole files into context.",
511 - "Use ctx search when bash output was stored as ctx:stored.",
291 + label:
"ctx search",
292 + description:
"Search command output that ctx previously stored after it exceeded the safe context threshold.",
293 + promptSnippet:
"Use only after a tool result says ctx:stored.",
294 + promptGuidelines: [
"Call ctx with query and optional source from ctx:stored to inspect suppressed large bash output."],
513 295 parameters: Params,
514 - async execute(_toolCallId
: string, raw
: unknown, signal
?: AbortSignal, _onUpdate
?: unknown, ctx
?: any) {
296 + async execute(_toolCallId
: string, raw
: unknown, _signal
?: AbortSignal, _onUpdate
?: unknown, ctx
?: any) {
515 297 const store
= makeStore(ctx);
517 - const params
= normalizeParams(raw);
518 - return await executeCtxOperation(store, params, ctx?.cwd
?? process.
cwd(), signal);
299 + return executeCtxSearch(store,
normalizeSearchParams(raw));
520 301 return { content: [{ type:
"text", text:
`ctx error: ${err instanceof Error ? err.message : String(err)}` }], details: {}, isError:
true };
527 - pi.
registerCommand(
"ctx", {
528 - description:
"ctx stats/search/purge",
529 - handler:
async (args
: unknown, ctx
: any)
=> {
530 - const q
= String(args
?? "").
trim();
531 - const store
= makeStore(ctx);
533 - if (q
=== "--purge") {
535 - const ok
= await ctx.ui.
confirm(
"ctx purge",
"Delete ctx index for this project?");
536 - if (
!ok)
return { text:
"ctx purge cancelled" };
539 - return { text:
"ctx purged" };
541 - if (
!q)
return { text: store.
formatStats() };
542 - return { text: store.
search([q], { limit:
5 }) };
550 309 export default function (pi
: ExtensionAPI)
: void {