Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ agents through SQL and a CLI. Nothing leaves the machine.
- **Nudges** (toasts, never added to the model's context): a call re-wrote the prompt cache, with the reason
(a compaction, a model switch, idle past the cache's lifetime, or a change at the start of the request, which
is worth a look); the context passed 200k.
- **`/quantext`:** opens or closes a pane with the session's last 50 messages (nudges, `/clear-tools` results,
viewer steps), newest first, so a toast you missed is still there. While the pane is closed, the status line
counts the new ones (`· 2 new`).
- **`/clear-tools [outputs] [keep N]`:** compacts by replacing old tool calls (their inputs) and old tool outputs
with short stubs instead of a summary, in one pass, so the prompt cache is written once. `outputs` clears only
the outputs; `keep N` leaves the last N whole. Also as `/compact tools [outputs] [keep N]`. The next call
Expand Down
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ Each step ends with tests, and later steps never reach below the layer they depe
| 6 | **Query layer + CLI**: `qx ingest`, `qx sessions`, `qx call`, `qx sql` with views | 1 | An agent answers "top tool outputs by lifetime cost" with `qx sql` |
| 7 | **API + engine process**: HTTP JSON + SSE, Host check, single instance, idle exit | 1 | SSE fires on a new call; a second start reuses the running engine |
| 8 | **Live context viewer**: reuse the eduagent visualiser components with a read-only Claude Code adapter; the teaching features above | 1 | A running session updates in the browser call by call; meets the UX bar |
| 9 | **Mod**: status line, nudges, `/clear-tools` from in-process `usage`; `/quantext view` starts the engine and opens the viewer | 1 | Works on a fresh Claude Code install; harness features work with no Node or Bun |
| 9 | **Mod**: status line, nudges (kept in the `/quantext` pane), `/clear-tools` from in-process `usage`; `/quantext view` starts the engine and opens the viewer | 1 | Works on a fresh Claude Code install; harness features work with no Node or Bun |
| 10 | **Agent surface**: schema docs, a skill, MCP later | **2** | The reviewer questions are answered and checked in the viewer |

Code from the earlier prototype (the Python parser and incremental store, pricing, the mod widget) is ported inside
Expand Down
11 changes: 8 additions & 3 deletions packages/mod/src/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,19 @@ export async function updateLive($: EngineInterface, fn: (l: Live) => Live): Pro
export const inputOf = (u: TurnUsage): number =>
u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens;

/** `qx $14.46 · ctx 333k · cache 60%`; undefined before the first measurement. */
export function statusLabel(l: Live): string | undefined {
if (l.ctx === 0) return undefined;
/**
* `qx $14.46 · ctx 333k · cache 60% · 2 new`, the last part while messages came with the pane closed;
* undefined before the first measurement and with nothing new.
*/
export function statusLabel(l: Live, fresh = 0): string | undefined {
const news = fresh > 0 ? [`${fresh} new`] : [];
if (l.ctx === 0) return news.length > 0 ? `qx ${news.join("")}` : undefined;
const total = l.read + l.input;
const parts = [
...(l.usd === undefined ? [] : [usd(l.usd)]),
`ctx ${tokens(l.ctx)}`,
...(total > 0 ? [`cache ${Math.round((100 * l.read) / total)}%`] : []),
...news,
];
return `qx ${parts.join(" · ")}`;
}
85 changes: 85 additions & 0 deletions packages/mod/src/messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* The mod's messages: each one a toast, and kept, newest first, for the pane that bare `/quantext` opens and
* closes. A toast lasts seconds; the pane keeps the session's newest 50. While the pane is closed the footer
* counts the new ones.
*/
import type { EngineInterface, RenderElement, RenderInput } from "claude-code";
import { atom, read, update } from "claude-code";
import type { Messages } from "../types/index.js";

export const PANE = "quantext";
const TITLE = "Quantext";
const KEEP = 50;
/** Inline above the prompt the frame grows with its rows: there only the newest few. */
const INLINE = 5;
const EMPTY: Messages = { list: [], unread: 0 };
// Change the tag when a message's fields change: it declines what an earlier version stored.
const messages = atom({ plugin: "quantext", key: "messages" } as const, EMPTY, { shape: "messages-1" });

/** Whether the pane is on screen; a failed look counts as closed, so a message counts as new. */
async function paneIsShown($: EngineInterface): Promise<boolean> {
try {
return (await $.ui.panes()).some((p) => p.id === PANE && p.isPlaced && p.isShown);
} catch (error) {
$.ui.log(`quantext: could not list the panes: ${String(error)}`, { to: "debug" });
return false;
}
}

/** Shows `text` as a toast and keeps it for the pane. */
export async function say($: EngineInterface, text: string): Promise<void> {
$.ui.toast(text);
const at = await $.clock.now();
const seen = await paneIsShown($);
await update($, messages, (m) => ({
list: [{ at, text }, ...m.list].slice(0, KEEP),
unread: seen ? 0 : m.unread + 1,
}));
}

/** How many messages came while the pane was closed. */
export async function unread($: EngineInterface): Promise<number> {
return (await read($, messages)).unread;
}

/** Opens the pane, or closes it when it is open; answers what it did, for the command's reply. */
export async function togglePane($: EngineInterface): Promise<string> {
if ((await $.ui.panes()).some((p) => p.id === PANE)) {
await $.ui.close({ id: PANE });
return "quantext: messages pane closed.";
}
const opened = await $.ui.open({ id: PANE, title: TITLE });
await update($, messages, (m) => ({ ...m, unread: 0 }));
return opened.isPlaced
? "quantext: messages pane opened; /quantext again closes it."
: `quantext: the messages pane waits to be drawn (${opened.reason}).`;
}

/** `14:05`, in the person's time zone. */
function clockTime(at: number): string {
const d = new Date(at);
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}

/** `h` with a component tag: `h` is typed for every tag (a string too), so it may answer a bare string or null. */
const el = (...args: Parameters<typeof h>): RenderElement => h(...args) as RenderElement;

/** Draws the pane: one row per message, its time, then its words without the "quantext: " the title says. */
export async function drawPane($: EngineInterface, e: RenderInput<"Pane">): Promise<RenderElement> {
const { Box, Text } = $.ui.resolve(e);
const { list } = await read($, messages);
if (list.length === 0) return el(Text, { dimColor: true }, "No messages yet. Quantext's toasts land here.");
const shown = e.props.placement === "inline" ? list.slice(0, INLINE) : list;
return el(
Box,
{ flexDirection: "column" },
...shown.map((m) =>
el(
Box,
{ flexDirection: "row", gap: 1 },
el(Text, { dimColor: true }, clockTime(m.at)),
el(Text, { wrap: "wrap" }, m.text.replace(/^quantext: /, "")),
),
),
);
}
26 changes: 15 additions & 11 deletions packages/mod/src/register.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/** The Quantext mod: a footer label and nudges from in-process usage, /clear-tools, /quantext view. */
/** The Quantext mod: a footer label and nudges from in-process usage, a messages pane, /clear-tools, /quantext view. */
import type { EngineInterface, Register } from "claude-code";
import type { ClearArgs } from "./clear-tools.ts";
import { clearRequest, clearTools, clearWhat, compactArgs, parseClearArgs, USAGE } from "./clear-tools.ts";
import { EMPTY, inputOf, readLive, statusLabel, updateLive } from "./live.ts";
import { drawPane, PANE, say, togglePane, unread } from "./messages.ts";
import { CACHE_TTL_MS, cacheBreakNudge, cacheHeld, contextNudge } from "./nudges.ts";
import { openViewer } from "./viewer.ts";

Expand All @@ -16,7 +17,7 @@ async function clearNow($: EngineInterface, a: ClearArgs): Promise<void> {
await $.command.run({ command: "compact", args });
} catch (error) {
const why = error instanceof Error ? error.message : String(error);
$.ui.toast(`/clear-tools failed: ${why}; try /compact ${args}`);
await say($, `/clear-tools failed: ${why}; try /compact ${args}`);
}
}

Expand Down Expand Up @@ -57,8 +58,8 @@ export const register: Register = (on) => {
});
await $.command.register({
name: "quantext",
description: "Quantext: open the live context viewer (starts the engine when it is not running)",
argumentHint: "view",
description: "Quantext: open or close the messages pane; view: open the live context viewer",
argumentHint: "[view]",
});
if (e.isInteractive) remeasureSoon($); // show the context before the first call
return started;
Expand All @@ -82,7 +83,7 @@ export const register: Register = (on) => {
...(e.cost === undefined ? {} : { usd: e.cost.usd }),
bigCtxNudged: l.bigCtxNudged || nudge !== undefined,
}));
if (nudge !== undefined) $.ui.toast(nudge);
if (nudge !== undefined) await say($, nudge);
return r;
});

Expand All @@ -106,17 +107,18 @@ export const register: Register = (on) => {
lastCtx: inputOf(u),
model: u.model,
}));
if (nudge !== undefined) $.ui.toast(nudge);
if (nudge !== undefined) await say($, nudge);
return r;
});

on("command.run", { command: "quantext" }, async ($, e) => {
if (e.args.trim().toLowerCase() !== "view") return { text: "Usage: /quantext view" };
const arg = e.args.trim().toLowerCase();
if (arg === "") return { text: await togglePane($) };
if (arg !== "view") return { text: "Usage: /quantext (the messages pane) or /quantext view (the viewer)" };
// The flow waits up to ~11 s, past a hook's budget: it runs from a timer and answers with toasts.
$.clock.after(
0,
() =>
void openViewer($).catch((error: unknown) => $.ui.toast(`quantext: /quantext view failed: ${String(error)}`)),
() => void openViewer($).catch((error: unknown) => say($, `quantext: /quantext view failed: ${String(error)}`)),
);
return { text: "quantext: opening the viewer…" };
});
Expand All @@ -137,7 +139,7 @@ export const register: Register = (on) => {
await updateLive($, (l) => ({ ...l, bigCtxNudged: false, compacted: true }));
remeasureSoon($);
}
if (note !== undefined) $.ui.toast(note); // after the update, so a failed clear shows no "Cleared"
if (note !== undefined) await say($, note); // after the update, so a failed clear shows no "Cleared"
return r;
}).catch((_$, e, next) => {
// A failed clear must not fall back to a paid summary; any other failure leaves it to Claude Code.
Expand All @@ -155,9 +157,11 @@ export const register: Register = (on) => {
return r;
});

on("ui.render", { component: "Pane", requestId: PANE }, ($, e) => drawPane($, e));

// Appends to the footer's mode labels, so the labels of other plugins stay.
on("ui.render", { component: "SessionMode" }, async ($, e, next) => {
const label = statusLabel(await readLive($));
const label = statusLabel(await readLive($), await unread($));
if (label === undefined) return next(e);
return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } });
});
Expand Down
24 changes: 14 additions & 10 deletions packages/mod/src/viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
* runs (or when the one found does not serve the viewer's page: it is stopped first), and open the viewer. The engine is started only here, never by itself (ARCHITECTURE "Starting the
* engine"). Each step's outcome reaches the person as a toast.
*/

import type { EngineInterface } from "claude-code";
import type { EngineAddress } from "./engine-file.ts";
import { engineUrl, parseEngineFile, parseEngineVersion, parseHealth, printable } from "./engine-file.ts";
import { say } from "./messages.ts";
import { INSTALL_HINT, MIN_BUN, MIN_NODE, meetsVersion } from "./runtime.ts";

/** How long one `/health` may take: a local engine answers in milliseconds. */
Expand Down Expand Up @@ -140,23 +142,24 @@ async function openUrl($: EngineInterface, url: string, cwd: string): Promise<bo
export async function openViewer($: EngineInterface): Promise<void> {
const home = await $.env.get("HOME");
if (home === undefined || home === "") {
$.ui.toast("quantext: HOME is not set, so the engine's folder (~/.quantext) cannot be found.");
await say($, "quantext: HOME is not set, so the engine's folder (~/.quantext) cannot be found.");
return;
}
const dataDir = `${home}/.quantext`;
const engineDir = `${$.plugin.root}/engine`;
const version = await bundledVersion($, engineDir);
if (version === undefined) {
$.ui.toast("quantext: this plugin has no bundled engine (engine/); reinstall it.");
await say($, "quantext: this plugin has no bundled engine (engine/); reinstall it.");
return;
}

let found = await findEngine($, dataDir, version);
if (found.kind === "same" && !(await servesPage($, found.port))) {
const { pid } = found;
$.ui.toast(`quantext: the engine (pid ${pid}) does not serve the viewer; starting it again…`);
await say($, `quantext: the engine (pid ${pid}) does not serve the viewer; starting it again…`);
if (!(await stopEngine($, dataDir, version, pid, engineDir))) {
$.ui.toast(
await say(
$,
`quantext: the engine (pid ${pid}) does not serve the viewer and did not stop; ` +
`stop it (kill -9 ${pid}), then run /quantext view again.`,
);
Expand All @@ -167,33 +170,34 @@ export async function openViewer($: EngineInterface): Promise<void> {
if (found.kind === "none") {
const runtime = await findRuntime($, engineDir);
if (runtime === undefined) {
$.ui.toast(INSTALL_HINT);
await say($, INSTALL_HINT);
return;
}
$.ui.toast("quantext: starting the engine…");
await say($, "quantext: starting the engine…");
const log = `${dataDir}/engine.log`;
const argv = ["sh", "-c", START_SCRIPT, runtime, `${engineDir}/engine.js`, log, dataDir];
const started = await tryRun($, argv, engineDir);
if (started?.exitCode !== 0) {
const why = printable(started?.stderr.trim() ?? "").slice(0, STDERR_SHOWN) || "sh did not run";
$.ui.toast(`quantext: the engine could not be started (${why}).`);
await say($, `quantext: the engine could not be started (${why}).`);
return;
}
found = await waitForEngine($, dataDir, version);
if (found.kind === "none") {
$.ui.toast(`quantext: the engine did not answer within ${START_TIMEOUT_MS / 1000} s; see ${log}`);
await say($, `quantext: the engine did not answer within ${START_TIMEOUT_MS / 1000} s; see ${log}`);
return;
}
}
if (found.kind === "other") {
$.ui.toast(
await say(
$,
`quantext: an engine of version ${found.version} (pid ${found.pid}) runs; this plugin brings ${version}. ` +
`Stop it (kill ${found.pid}), then run /quantext view again.`,
);
return;
}
const opened = await openUrl($, found.url, engineDir);
$.ui.toast(`quantext: the viewer is at ${found.url}${opened ? "" : " (open it in a browser)"}`);
await say($, `quantext: the viewer is at ${found.url}${opened ? "" : " (open it in a browser)"}`);
}

/** The bundled engine's version, or undefined when the plugin has no engine. */
Expand Down
Loading
Loading