Something went wrong. Try again.
small gleam coding and (not yet) persistent agent daemon with a detachable cli
Something went wrong. Try again.
TSX
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151import assert from "node:assert/strict"import { createServer } from "node:http"import { PassThrough } from "node:stream"import test from "node:test"import { render } from "ink"import { ContextInspector, parseContextPage, parseContextSnapshot } from "./context-inspector.js"
const until = async (ready: () => boolean, what: string): Promise<void> => { for (let attempt = 0; attempt < 400; attempt++) { if (ready()) return await new Promise(resolve => setTimeout(resolve, 5)) } throw new Error(`timed out: ${what}`)}
const terminal = () => { const stdin = Object.assign(new PassThrough(), { isTTY: true, setRawMode: () => stdin, ref: () => stdin, unref: () => stdin }) as unknown as NodeJS.ReadStream const stdout = Object.assign(new PassThrough(), { isTTY: true, columns: 120, rows: 30 }) as unknown as NodeJS.WriteStream let painted = "" stdout.on("data", (chunk: Buffer) => { painted += chunk.toString() }) return { stdin, stdout, painted: () => painted, clear: () => { painted = "" } }}
const snapshot = { state: "ready", captured_at: 1234, provider: "fixture", model: "fixture-model", protocol: "responses", context_window_tokens: 128_000, compaction: { strategy: "rolling", status: "compacted", source: "rolling observation recorded during request preparation", trigger_free_percent: 10, input_limit_tokens: 128_000, estimated_input_tokens: 117_200, estimate_method: "pinned tokenizer estimate", before_items: 42, after_items: 14, }, sections: [ { id: "instructions", label: "system instructions", kind: "instructions", source: "albedo core + enabled extension instructions", item_count: 2, byte_count: 900, preview: "core instructions…", pages: 1 }, { id: "extension-0", label: "extension context · skills", kind: "extension_context", source: "skills context plugin loaded when runtime session opened", item_count: 1, byte_count: 240, preview: "<extension-context…", pages: 1 }, { id: "history", label: "prepared conversation", kind: "history", source: "durable transcript through rolling compaction", item_count: 14, byte_count: 4_200, preview: "summary + recent user recap + verbatim tail", pages: 2 }, { id: "tools", label: "tool schemas", kind: "tools", source: "enabled extension tool registry", item_count: 5, byte_count: 1_500, preview: "python, bash, skills…", pages: 1 }, ],}
test("context inspector shows ordered sources and paged exact content using only read-only requests", { timeout: 10_000 }, async t => { const requests: { method?: string; url?: string }[] = [] const server = createServer((req, res) => { requests.push({ method: req.method, url: req.url }) res.setHeader("content-type", "application/json") if (req.url === "/health") res.end(JSON.stringify({ capabilities: ["session_context"] })) else if (req.url === "/sessions/session/context") res.end(JSON.stringify(snapshot)) else if (req.url === "/sessions/session/context/history/0") res.end(JSON.stringify({ section: "history", page: 0, pages: 2, content: "[summary · generated by rolling compaction]\nkept fact\n\n[user recap · derived from durable transcript]\nrequested feature", omitted: "image payload bytes; dimensions and position remain represented", })) else { res.writeHead(404); res.end(JSON.stringify({ error: `unexpected ${req.method} ${req.url}` })) } }) await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve)) t.after(() => { server.closeAllConnections(); server.close() }) const address = server.address(); assert(address && typeof address !== "string") const tty = terminal() let cancelled = 0 const app = render(<ContextInspector connection={{ port: address.port, token: "fixture", pid: 1, version: 2 }} sessionId="session" onCancel={() => { cancelled++ }} />, { stdin: tty.stdin, stdout: tty.stdout, patchConsole: false, exitOnCtrlC: false, }) t.after(() => app.unmount()) const write = async (input: string): Promise<void> => { tty.stdin.write(input); await app.waitUntilRenderFlush() }
await until(() => tty.painted().includes("system instructions") && tty.painted().includes("tool schemas"), "context summary") const output = tty.painted() assert(output.indexOf("system instructions") < output.indexOf("extension context · skills")) assert(output.indexOf("extension context · skills") < output.indexOf("prepared conversation")) assert(output.indexOf("prepared conversation") < output.indexOf("tool schemas")) assert(output.includes("fixture · fixture-model · responses")) assert(output.includes("128,000 tokens (configured)")) assert(output.includes("rolling · applied")) assert(output.includes("trigger: keep 10% free")) assert(output.includes("117,200 tokens · pinned tokenizer estimate")) assert(output.includes("900 measured bytes")) assert(output.includes("durable transcript and request-only context are separate"))
await write("\x1b[B"); await write("\x1b[B"); tty.clear(); await write("\r") await until(() => tty.painted().includes("kept fact") && tty.painted().includes("image payload bytes"), "history detail") assert(tty.painted().includes("page 1/2")) assert.deepEqual(requests.map(item => item.method), requests.map(() => "GET"), "inspection must remain read-only") assert.deepEqual(requests.map(item => item.url), ["/health", "/sessions/session/context", "/sessions/session/context/history/0"])
tty.clear(); await write("\x1b") await until(() => tty.painted().includes("system instructions"), "escape to sections") assert.equal(cancelled, 0) await write("\x1b") await until(() => cancelled === 1, "escape to chat")})
test("pending snapshot stays explicit and refresh does not prepare or execute anything", { timeout: 10_000 }, async t => { let reads = 0 const paths: string[] = [] const server = createServer((req, res) => { paths.push(`${req.method} ${req.url}`) res.setHeader("content-type", "application/json") if (req.url === "/health") res.end(JSON.stringify({ capabilities: ["session_context"] })) else if (req.url === "/sessions/session/context") { reads++; res.end(JSON.stringify({ state: "pending", reason: "runtime session has not prepared a provider request" })) } else { res.writeHead(500); res.end(JSON.stringify({ error: "inspector attempted an unrelated operation" })) } }) await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve)) t.after(() => { server.closeAllConnections(); server.close() }) const address = server.address(); assert(address && typeof address !== "string") const tty = terminal() const app = render(<ContextInspector connection={{ port: address.port, token: "fixture", pid: 1, version: 2 }} sessionId="session" onCancel={() => {}} />, { stdin: tty.stdin, stdout: tty.stdout, patchConsole: false, exitOnCtrlC: false, }) t.after(() => app.unmount()) await until(() => tty.painted().includes("pending · no request has been prepared"), "pending state") assert(tty.painted().includes("runtime session has not prepared a provider request")) tty.stdin.write("r"); await app.waitUntilRenderFlush() await until(() => reads === 2, "refresh") assert(paths.every(path => path === "GET /health" || path === "GET /sessions/session/context"))})
test("old daemon capability preflight prevents unsupported context requests", { timeout: 10_000 }, async t => { let contextReads = 0 const server = createServer((req, res) => { res.setHeader("content-type", "application/json") if (req.url === "/health") res.end(JSON.stringify({ capabilities: [] })) else { contextReads++; res.end(JSON.stringify(snapshot)) } }) await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve)) t.after(() => { server.closeAllConnections(); server.close() }) const address = server.address(); assert(address && typeof address !== "string") const tty = terminal() const app = render(<ContextInspector connection={{ port: address.port, token: "fixture", pid: 1, version: 2 }} sessionId="session" onCancel={() => {}} />, { stdin: tty.stdin, stdout: tty.stdout, patchConsole: false, exitOnCtrlC: false, }) t.after(() => app.unmount()) await until(() => tty.painted().includes("daemon upgrade needed for /context"), "upgrade warning") assert.equal(contextReads, 0)})
test("context decoders bound metadata and page content", () => { assert.equal(parseContextSnapshot(snapshot).state, "ready") assert.throws(() => parseContextSnapshot({ ...snapshot, sections: Array.from({ length: 1_001 }, () => snapshot.sections[0]) }), /invalid context metadata/) assert.throws(() => parseContextPage({ section: "history", page: 0, pages: 1, content: "x".repeat(65_537) }, "history"), /invalid context page/) assert.throws(() => parseContextPage({ section: "wrong", page: 0, pages: 1, content: "safe" }, "history"), /invalid context page/)})