Fix the loop stalling after compaction, add an external registry

The compaction bug, which is the important one:

beta.2 taught the pruner to drop any assistant part whose reasoning item it had
removed. That was right about the 400 and wrong about everything else. On a
reasoning model every tool call carries a provider itemId, so past the threshold
the model could no longer see what it had already run, and re-ran the same tools
until maxSteps ended the turn. Reproduced at 12 model calls for a job needing 4,
with nothing but the user message reaching the wire.

The dependency is not the part, it is the itemId. A part carrying one is
serialised as `{ type: 'item_reference', id }`, a pointer to an item stored
provider-side that depends on its reasoning item. Without the itemId the same
content goes out inline and carries no dependency at all. Verified against the
provider's own serialiser: `text` with an itemId becomes item_reference, the
identical part without one becomes output_text.

So `dropOrphanedItems` becomes `detachOrphanedItems`: strip the itemId, keep the
content. Compaction may shorten the history; it must not blank it. The new test
asserts behaviour rather than shape — the loop must end because the model chose
to, and every call after the first must still carry the earlier exchange. A shape
assertion passed the whole time the model was losing its memory.

Registry, via `/registry [list|search|add|remove|installed]`:

Skills and plugins are treated differently on purpose. A skill is prompt text, so
installing one puts a stranger's words into the system prompt of every future
session in this project; the install shows the body first and the origin is
recorded, so /skills always says where an instruction came from. A plugin is a
JSON manifest of deny rules, evaluated by compiled code identical for every
install. Loading TypeScript from a URL is declined outright: a plugin that can
block tool calls could otherwise lie about blocking them.

Validated before anything is written: https only (file: and data: rejected), name
matched against ^[a-z0-9][a-z0-9-]*$ so it cannot escape its directory, size
caps on index and body, every regex compiled, pattern length capped since it runs
on every tool call, and the body's own name checked against the index. Installed
skills rank below your own, so an install can never shadow a skill you wrote.

Interface:
- Context is a percentage of the compaction threshold, amber from two thirds and
  red at 90. A turn about to lose history now says so beforehand.
- Aligned command menu and registry tables; /skills and /plugins name origins.

538 tests, up from 488. The registry is tested against a real local HTTP server,
and the guard is proven to refuse a .env write end to end rather than assumed to.
This commit is contained in:
Muhammad Zakir Ramadhan
2026-09-03 03:07:56 +07:00
parent 8b1895de98
commit 84c60f2022
26 changed files with 1929 additions and 149 deletions
+116 -7
View File
@@ -15,7 +15,7 @@ import { AskPanel, type AskBridge, type AskPending } from './Ask';
import { Diff } from './Diff';
import { Markdown } from './Markdown';
import { Onboard, type OnboardResult } from './Onboard';
import { InfoPanel, OutputPanel, QueuePanel, StatusBar, SubagentPanel, ThinkingPanel, TodoPanel, ActiveTool, FileMenu, type SubagentView } from './Panels';
import { InfoPanel, OutputPanel, QueuePanel, RegistryPanel, InstallPrompt, StatusBar, SubagentPanel, ThinkingPanel, TodoPanel, ActiveTool, FileMenu, type RegistryRow, type SubagentView } from './Panels';
import { PromptInput } from './PromptInput';
type Line =
@@ -139,6 +139,15 @@ export type AppHooks = {
instructionFiles: () => string[];
/** Ignore-aware workspace paths for `@` completion, loaded on first use. */
listPaths: () => Promise<string[]>;
/** Registry index, installed set, and the install/remove actions. */
registry: {
list: () => Promise<RegistryRow[]>;
installed: () => Promise<RegistryRow[]>;
/** Fetches and validates without writing, so the body can be shown first. */
stage: (name: string) => Promise<{ row: RegistryRow; url: string; preview: string }>;
install: (name: string) => Promise<string>;
remove: (name: string) => Promise<string>;
};
/** Prompt to hand the model for /init. */
initPrompt: string;
history: string[];
@@ -198,19 +207,42 @@ function Approval({ pending }: { pending: Pending }) {
}
function CommandMenu({ matches, index }: { matches: CommandSpec[]; index: number }) {
const width = Math.max(...matches.map((c) => `/${c.name}${c.arg ? ` ${c.arg}` : ''}`.length)) + 1;
return (
<Box flexDirection="column" marginTop={1}>
{matches.map((c, i) => (
<Text key={c.name} color={i === index ? 'cyan' : undefined} dimColor={i !== index}>
{i === index ? '> ' : ' '}
{`/${c.name}${c.arg ? ` ${c.arg}` : ''}`.padEnd(18)} {c.summary}
</Text>
<Box key={c.name}>
<Text color={i === index ? 'cyan' : undefined}>{i === index ? '> ' : ' '}</Text>
<Text color={i === index ? 'cyan' : undefined} bold={i === index}>
{`/${c.name}${c.arg ? ` ${c.arg}` : ''}`.padEnd(width)}
</Text>
<Text dimColor>{c.summary}</Text>
</Box>
))}
<Text dimColor>up/down move | tab complete | enter run | esc dismiss</Text>
</Box>
);
}
/** Keyboard wrapper around InstallPrompt, so the prompt itself stays presentational. */
function InstallConfirm({
staged,
onDone,
}: {
staged: { row: RegistryRow; url: string; preview: string };
onDone: (yes: boolean) => void;
}) {
useInput((input, key) => {
const c = input.toLowerCase();
if (c === 'y' || key.return) onDone(true);
else if (c === 'n' || key.escape) onDone(false);
});
return (
<InstallPrompt name={staged.row.name} kind={staged.row.kind} url={staged.url} preview={staged.preview} />
);
}
export function App({
session,
bridge,
@@ -260,8 +292,12 @@ export function App({
const [notebook, setNotebook] = useState<NotebookState>(session.notebook.state());
const [agents, setAgents] = useState<SubagentView[]>([]);
const [panel, setPanel] = useState<{ title: string; hint?: string; body: string } | undefined>();
const [registry, setRegistry] = useState<{ title: string; hint?: string; rows: RegistryRow[] } | undefined>();
const [installing, setInstalling] = useState<
{ row: RegistryRow; url: string; preview: string } | undefined
>();
const modal = pending !== undefined || asking !== undefined || onboarding;
const modal = pending !== undefined || asking !== undefined || onboarding || installing !== undefined;
const anyPicker = modelPicker !== undefined || agentPicker || thinkPicker;
const matches = matchCommands(draft);
const menuOpen = matches.length > 0 && !menuDismissed && !busy && !modal && !anyPicker && !panel;
@@ -371,6 +407,10 @@ export function App({
setPanel(undefined);
return true;
}
if (key.escape && registry) {
setRegistry(undefined);
return true;
}
// The file picker gets first refusal: while an `@` token is open its keys
// mean navigation, not history recall or command completion.
@@ -425,7 +465,7 @@ export function App({
}
return false;
},
[draft, fileMatches.length, fileOpen, highlighted, highlightedPath, matches.length, menuOpen, panel, token],
[draft, fileMatches.length, fileOpen, highlighted, highlightedPath, matches.length, menuOpen, panel, registry, token],
);
const onDraftChange = useCallback((value: string, at: number) => {
@@ -536,6 +576,7 @@ export function App({
setFileIndex(0);
setFileDismissed(false);
setPanel(undefined);
setRegistry(undefined);
// Enter on an open menu runs the highlighted entry, so `/mo` + enter works.
const chosen = menuOpen && highlighted ? `/${highlighted.name}` : raw;
@@ -676,6 +717,50 @@ export function App({
push({ kind: 'user', text: chosen.trim() });
setPanel({ title: 'plugins', body: hooks.listPlugins() });
return;
case 'registry': {
push({ kind: 'user', text: chosen.trim() });
setWorking(true);
try {
if (action.action === 'add') {
// Staged, not installed: nothing is written until the prompt is answered.
setInstalling(await hooks.registry.stage(action.arg!));
return;
}
if (action.action === 'remove') {
push({ kind: 'info', text: await hooks.registry.remove(action.arg!) });
return;
}
if (action.action === 'installed') {
const rows = await hooks.registry.installed();
setRegistry({
title: 'installed',
hint: rows.length === 0 ? 'nothing installed yet' : `${rows.length} from the registry`,
rows,
});
return;
}
const all = await hooks.registry.list();
const rows =
action.action === 'search' && action.arg
? all.filter(
(r) =>
r.name.includes(action.arg!.toLowerCase()) ||
r.description.toLowerCase().includes(action.arg!.toLowerCase()),
)
: all;
setRegistry({
title: action.arg ? `registry: ${action.arg}` : 'registry',
hint: `${rows.length} of ${all.length} available`,
rows,
});
} catch (e) {
push({ kind: 'error', text: e instanceof Error ? e.message : String(e) });
} finally {
setWorking(false);
}
return;
}
case 'memory': {
push({ kind: 'user', text: chosen.trim() });
setWorking(true);
@@ -799,6 +884,29 @@ export function App({
<InfoPanel title={panel.title} {...(panel.hint ? { hint: panel.hint } : {})} lines={panel.body} />
)}
{registry && (
<RegistryPanel title={registry.title} {...(registry.hint ? { hint: registry.hint } : {})} rows={registry.rows} />
)}
{installing && (
<InstallConfirm
staged={installing}
onDone={async (yes) => {
const staged = installing;
setInstalling(undefined);
if (!yes) {
push({ kind: 'info', text: `install cancelled: ${staged.row.name}` });
return;
}
try {
push({ kind: 'info', text: await hooks.registry.install(staged.row.name) });
} catch (e) {
push({ kind: 'error', text: e instanceof Error ? e.message : String(e) });
}
}}
/>
)}
{asking && <AskPanel pending={asking} />}
{pending && <Approval pending={pending} />}
@@ -937,6 +1045,7 @@ export function App({
agent={hooks.agentName()}
thinking={hooks.thinkingLevel()}
contextTokens={session.estimatedTokens()}
contextLimit={session.compactThreshold()}
cost={(() => {
const spend = costOf(hooks.config().model, session.inputTokens, session.outputTokens);
return spend === undefined ? 'unpriced' : formatUsd(spend);
+115 -1
View File
@@ -216,6 +216,7 @@ export function StatusBar({
agent,
thinking,
contextTokens,
contextLimit,
cost,
toolCount,
}: {
@@ -223,14 +224,25 @@ export function StatusBar({
agent: string;
thinking: string;
contextTokens: number;
/** Threshold compaction fires at, so the bar means something. */
contextLimit?: number;
cost: string;
toolCount: number;
}) {
const pct = contextLimit ? Math.min(100, Math.round((contextTokens / contextLimit) * 100)) : undefined;
// Amber from two thirds, red once compaction is imminent: the point is to warn
// before a turn silently loses its history, not after.
const contextColor = pct === undefined ? undefined : pct >= 90 ? 'red' : pct >= 66 ? 'yellow' : undefined;
return (
<Box>
<Text dimColor>{`${model} `}</Text>
<Text color="cyan">{agent}</Text>
<Text dimColor>{`/${thinking} ${toolCount} tools ~${contextTokens} ctx ${cost}`}</Text>
<Text dimColor>{`/${thinking} ${toolCount} tools `}</Text>
<Text color={contextColor} dimColor={contextColor === undefined}>
{pct === undefined ? `~${contextTokens} ctx` : `${pct}% ctx`}
</Text>
<Text dimColor>{` ${cost}`}</Text>
</Box>
);
}
@@ -258,3 +270,105 @@ export function InfoPanel({ title, hint, lines }: { title: string; hint?: string
</Box>
);
}
export type RegistryRow = {
name: string;
kind: 'skill' | 'plugin';
description: string;
author?: string;
installed?: boolean;
};
const KIND_COLOR: Record<RegistryRow['kind'], string> = { skill: 'green', plugin: 'magenta' };
/**
* The registry index as a table.
*
* `kind` is coloured rather than spelled out on every row: skill and plugin carry
* very different risk, and a reader scanning the list should see that at a glance.
*/
export function RegistryPanel({
rows,
hint,
title = 'registry',
}: {
rows: readonly RegistryRow[];
hint?: string;
title?: string;
}) {
if (rows.length === 0) {
return <InfoPanel title={title} {...(hint ? { hint } : {})} lines="nothing found" />;
}
const width = Math.min(22, Math.max(...rows.map((r) => r.name.length)) + 1);
return (
<Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginBottom={1}>
<Text color="cyan" bold>
{title}
</Text>
{hint && <Text dimColor>{hint}</Text>}
{rows.map((r) => (
<Box key={`${r.kind}:${r.name}`}>
<Text color={KIND_COLOR[r.kind]}>{r.kind === 'skill' ? 'S' : 'P'} </Text>
<Text bold>{r.name.padEnd(width)}</Text>
<Text dimColor>{r.description.length > 58 ? `${r.description.slice(0, 58)}...` : r.description}</Text>
{r.installed && <Text color="green">{' installed'}</Text>}
</Box>
))}
<Text dimColor>{'S skill P plugin | /registry add <name>'}</Text>
</Box>
);
}
/**
* Confirmation before an install writes anything.
*
* A skill body becomes part of the system prompt of every future session in this
* project, so it is shown in full first. The wording says that plainly rather than
* asking a generic "are you sure".
*/
export function InstallPrompt({
name,
kind,
url,
preview,
lines = 14,
}: {
name: string;
kind: 'skill' | 'plugin';
url: string;
preview: string;
lines?: number;
}) {
const body = preview.split('\n');
const shown = body.slice(0, lines);
const hidden = body.length - shown.length;
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
<Text color="yellow" bold>
{`install ${kind} "${name}"?`}
</Text>
<Text dimColor>{url}</Text>
<Box marginTop={1} flexDirection="column">
{shown.map((l, i) => (
<Text key={i} dimColor>
{` ${l}`}
</Text>
))}
{hidden > 0 && <Text dimColor>{` ... ${hidden} more lines`}</Text>}
</Box>
<Box marginTop={1} flexDirection="column">
<Text color="yellow">
{kind === 'skill'
? 'A skill is instructions the agent follows. This text joins your system prompt.'
: 'A plugin adds refusal rules. It is data, not code: nothing here is executed.'}
</Text>
<Text>
<Text color="green">y</Text> install | <Text color="red">n</Text> cancel
</Text>
</Box>
</Box>
);
}