repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(klaus): improve runtime integration and token setup

f404e81530b8351cc7894754a8951e8ba2e79f80

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (17)

docs/super/specs/2026-08-21-klaus-plan-spec.md

Modified
250 250 Provider registration itself performs no network request and no auth refresh.
251 251 Authenticated model discovery is lazy and bounded.
253 +### Long-lived token minting
255 +Klaus registers exactly one slash command for minting: `/klaus-setup-token`.
256 +It registers no CLI flag, because Pi applies extension flag values only after all extensions have loaded, so a flag cannot stop the TUI from starting.
258 +The command runs the Claude Code `setup-token` OAuth flow natively inside Pi and never spawns the Claude runtime.
259 +The child runtime is an Ink application that emits nothing without a TTY and full-screen escape sequences with one, so it cannot be embedded in Pi.
261 +The flow is authorization code with PKCE (S256) against `https://claude.com/cai/oauth/authorize` with the public Claude Code client id, scope `user:inference`, the manual redirect `https://platform.claude.com/oauth/code/callback`, and a random `state`.
262 +The token exchange posts JSON to `https://platform.claude.com/v1/oauth/token` with `grant_type=authorization_code`, the code, redirect URI, client id, code verifier, state, and `expires_in` of one year in seconds.
263 +Klaus rejects pasted input whose `state` differs from the generated one before any request.
265 +In TUI mode the whole visit happens inside one focused component, the Bureau of Tokens counter, so the animation frames the flow instead of interrupting it.
266 +Klaus opens the authorization URL in the browser and the counter opens at the same moment: the block-art snail clerk and the clerical form type themselves in above a live sign-in link and code field, and a `STATUS` row reports the current phase with a spinner.
267 +The link and the code field accept input from the first frame; the intro never gates the flow.
268 +Terminals that support OSC 8 receive one short hyperlinked label rather than the raw URL, because a wrapped or truncated link text would cut the escape sequence; terminals without OSC 8 get the wrapped URL instead.
269 +Pressing `c` while the code field is empty copies the authorization URL to the clipboard and reports the result inline.
270 +Accepted code shapes are the callback page's `code#state`, a redirect URL, a query string, or a bare code.
272 +Submitting moves the same counter to the exchange phase, then stamps the outcome in place: `APPROVED` with the validity row, the quip, and the clipboard verdict, or `DENIED` with the failure reason.
273 +`r` on a denied stamp files a fresh application: new PKCE, new URL, browser reopened, same counter.
274 +The first key press skips a running stamp animation, the next one closes the counter; Escape and the interrupt key cancel at any point, and only a cancellation before minting notifies `application withdrawn`.
275 +The animation timer is cleared on close and disposal, and its cadence follows the phase: fast during the intro and the stamp, slow while the human is signing in, off once the counter is static.
277 +Colors follow Anthropic's brand ramp, from book cloth through Claude orange, kraft, and manilla to cloud, for the mascot, title sweep, and approved stamp.
278 +The ramp uses true color when the theme reports it and falls back to ordered theme colors otherwise; form, ground, and verdict rows use theme colors, so success, warning, and error stay legible.
280 +The counter is responsive in three width tiers, selected per render so terminal resizes retake effect immediately: full at 62 columns or more, compact from 42, tiny below that.
281 +Narrower tiers use a smaller mascot, fewer sparkles, a shorter title and stamp, and abbreviated form labels; rows that still do not fit wrap instead of truncating.
282 +No rendered line exceeds the supplied width at any tier.
283 +Intro timing is width independent, so hints and skipping behave the same in every terminal size.
285 +Outside the TUI there is no counter: a plain input dialog collects the code, and notifications report the outcome, carrying the token when no clipboard tool worked.
287 +On success Klaus copies the token to the system clipboard using the first working tool of: `wl-copy`, `xclip -selection clipboard`, `xsel --clipboard --input` (Linux), `pbcopy` (macOS), `clip` (Windows), `termux-clipboard-set` (Termux).
288 +When no clipboard tool works, the counter prints the token itself, matching Claude Code's own fallback behavior.
290 +Klaus never persists the minted token: no cache, settings, session, or log writes.
291 +Minting is credential creation for the user, not credential storage, and does not violate the authentication non-goals of this spec.
293 +The counter is part of the contract: a bureaucratic joke at Anthropic's expense, with a snail clerk, delivered in Claude Code's own maximalist style.
253 295 ## Child isolation
255 297 Every Claude child uses a Klaus-owned `CLAUDE_CONFIG_DIR`.
639 681 - Pi `minimal` maps to SDK `low`.
640 682 - Directly supported levels retain their meaning.
641 683 - Unsupported levels clamp to the highest supported level not above the request.
642 -- A clamp emits one warning per Pi session and level combination.
684 +- Adaptive-thinking models always use adaptive thinking plus an effort level, matching Pi's native treatment of them.
685 +- A Pi thinking budget never pins an adaptive-thinking model into fixed-budget thinking; budgets apply only to budget-based models (Haiku).
644 687 Cold replay omits historical thinking and signatures because they are neither safely portable nor required for canonical Pi history.
645 688 A live resumed SDK lineage may preserve opaque signed thinking through its own session cache.
668 711 ### Output limits
670 -The Agent SDK exposes no enforceable response-token limit matching Pi `maxTokens`.
671 -Klaus silently ignores `maxTokens`.
672 -It does not reject requests, warn, or inject best-effort output-length instructions.
673 -This preserves Pi compaction and extensions that set the option.
713 +The Agent SDK `query()` options expose no enforceable response-token limit matching Pi `maxTokens`.
714 +Klaus honors Pi `maxTokens` through the runtime's `CLAUDE_CODE_MAX_OUTPUT_TOKENS` child environment variable instead.
716 +The value is read once per request from the Pi `SimpleStreamOptions`, carried on the Klaus request, validated as a positive safe integer, and set only when Pi supplies it.
717 +An absent Pi `maxTokens` leaves the variable unset so the runtime default applies; the variable is never inherited from the host environment.
718 +A `maxTokens` change across a tool-boundary continuation is an incompatibility that closes the continuation and replays canonically.
675 720 ### Payload hook

extensions/klaus/README.md

Modified
1 -# Klaus
1 +# klaus
3 -Klaus exposes current Claude models as a Pi provider through Anthropic's Claude Agent SDK.
3 +Exposes selected Claude models as a Pi provider through Anthropic's Claude Agent SDK.
4 4 Pi remains responsible for context, tools, compaction, hooks, and UI.
6 6 ## Install / load
9 9 Log in to Anthropic through Pi, then select a `klaus/*` model.
11 11 Klaus uses Anthropic's proprietary Claude Agent SDK and native Claude Code runtime under Anthropic's commercial terms.
12 -It accepts Pi-managed Anthropic OAuth only.
12 +It accepts only Pi-managed Anthropic OAuth.
14 14 On Termux Android ARM64, Klaus installs the exact matched Linux ARM64 runtime into user state and launches it through `glibc-runner`.
15 15 Install the runner with `pkg install glibc-repo && pkg install glibc-runner`.
17 -## State
17 +## Behavior
19 -Persisted primary Pi sessions mirror opaque Claude cache entries under the configured Pi session directory in `.klaus/`.
20 -Klaus never uses normal `~/.claude` sessions.
21 -The cache duplicates conversation data, is plaintext like Pi sessions, grows until manually removed, and uses private file permissions.
19 +Persisted primary Pi sessions mirror opaque Claude cache entries under `.klaus/` in the configured Pi session directory.
20 +Klaus does not use normal `~/.claude` sessions.
21 +The plaintext cache duplicates conversation data, uses private file permissions, and grows until manually removed.
23 +Klaus forwards Pi tools to Claude without changing their names, descriptions, order, or schemas.
24 +Required JSON-schema constrained sampling is rejected.
26 +When a cached resume point is invalid or corrupted, Klaus replays canonical visible conversation history.
27 +Replay excludes private reasoning, signatures, usage accounting, timestamps, and tool-result details.
23 29 Reported cost is API-equivalent spend calculated with Pi's Anthropic rates, not the subscription charge.
24 30 Fable may consume separate usage credits and warns before first use in each Pi session.
26 32 ## Commands / tools / settings
28 -None.
34 +- Slash command:
35 + `/klaus-setup-token` mints a long-lived Claude OAuth token with your Claude subscription, natively inside Pi.
36 + In the TUI the whole visit runs in one animated Bureau of Tokens counter: it opens the sign-in page in the browser, shows a live link (`c` copies it) and code field, exchanges the pasted code, copies the token to the clipboard, and stamps `APPROVED` or `DENIED` in place (`r` retries, Esc cancels).
37 + The counter is sized to the terminal in three width tiers and prints the token when no clipboard tool is available.
38 + Outside the TUI it falls back to a plain input dialog and notifications.
39 +- Environment variable:
40 + `KLAUS_DEBUG_LOG` writes structured NDJSON trace records to the specified file when set before Klaus loads.
41 +- Tools and hooks:
42 + none registered by the extension.
30 44 See the [binding specification](../../docs/super/specs/2026-08-21-klaus-plan-spec.md).

extensions/klaus/__tests__/runtime.test.ts

Modified
89 89 }, 60_000);
91 + it("maps Pi maxTokens onto the child output cap", async () => {
92 + process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS = "hostile-ambient";
93 + const runtime = await createChildRuntime("fake", {}, {}, 32768);
94 + runtimes.push(runtime);
95 + expect(runtime.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBe("32768");
97 + const uncapped = await createChildRuntime("fake", {}, {});
98 + runtimes.push(uncapped);
99 + expect(uncapped.env).not.toHaveProperty("CLAUDE_CODE_MAX_OUTPUT_TOKENS");
100 + }, 60_000);
102 + it("rejects invalid maxTokens values", async () => {
103 + await expect(createChildRuntime("fake", {}, {}, 0)).rejects.toThrow(
104 + /invalid maxTokens/,
105 + );
106 + await expect(
107 + createChildRuntime("fake", {}, {}, Number.NaN),
108 + ).rejects.toThrow(/invalid maxTokens/);
109 + }, 60_000);
91 111 it("does not depend on a shared predictable klaus directory", async () => {
92 112 const root = await mkdtemp(join(tmpdir(), "klaus-runtime-test-"));
93 113 roots.push(root);

extensions/klaus/__tests__/setup-scene.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import {
3 + renderScene,
4 + SCENE_INTRO_TICKS,
5 + type SceneState,
6 + sceneFormLines,
7 + sceneLayout,
8 + sceneOutcomeTicks,
9 + sceneVerdictLines,
10 +} from "../src/setup-scene";
12 +const LONG_LIVED = "sk-ant-oat01-abcdefghijklmnopqrstuvwxyz0123456789";
13 +const URL =
14 + "https://claude.com/cai/oauth/authorize?code=true&client_id=9d1c250a&scope=user%3Ainference&state=abc";
16 +const theme = {
17 + fg: (_color: string, text: string) => text,
18 + bold: (text: string) => text,
19 + getColorMode: () => "256color",
20 +} as never;
22 +const truecolorTheme = {
23 + fg: (_color: string, text: string) => text,
24 + bold: (text: string) => text,
25 + getColorMode: () => "truecolor",
26 +} as never;
28 +function state(overrides: Partial<SceneState> = {}): SceneState {
29 + return {
30 + tick: SCENE_INTRO_TICKS,
31 + phaseTick: 0,
32 + phase: "signin",
33 + input: ["Code: "],
34 + hyperlinks: true,
35 + url: URL,
36 + clipboard: "idle",
37 + hints: "enter submit · c copy link · esc cancel",
38 + now: 0,
39 + ...overrides,
40 + };
43 +function approved(overrides: Partial<SceneState> = {}): SceneState {
44 + const base = state({
45 + phase: "approved",
46 + input: [],
47 + token: LONG_LIVED,
48 + tokenCopied: true,
49 + expiresInSeconds: 365 * 24 * 60 * 60,
50 + hints: "any key to close",
51 + ...overrides,
52 + });
53 + return { ...base, phaseTick: overrides.phaseTick ?? sceneOutcomeTicks(base) };
56 +function text(scene: SceneState, width = 100, active = theme): string {
57 + return renderScene(scene, width, active).map(stripAnsi).join("\n");
60 +function stripAnsi(value: string): string {
61 + return value
62 + .replace(/\x1b\[[0-9;]*m/g, "")
63 + .replace(/\x1b\]8;;[^\x1b]*\x1b\\/g, "");
66 +describe("Bureau of Tokens scene", () => {
67 + it("keeps one counter on screen across every phase", () => {
68 + const signin = text(state());
69 + expect(signin).toContain("✻ KLAUS · BUREAU OF TOKENS · WINDOW 08/15 ✻");
70 + expect(signin).toContain("✦ APPLICATION");
71 + expect(signin).toContain("◈ STATUS");
72 + expect(signin).toContain("at the window, waiting for your code");
73 + expect(signin).toContain("Open the Claude sign-in page");
74 + expect(signin).toContain("Code: ");
75 + expect(signin).not.toContain("APPROVED");
77 + const exchanging = text(state({ phase: "exchanging", input: [] }));
78 + expect(exchanging).toContain("consulting the archive");
79 + expect(exchanging).toContain("✦ APPLICATION");
80 + expect(exchanging).not.toContain("Open the Claude sign-in page");
81 + expect(exchanging).not.toContain("Code: ");
83 + const done = text(approved());
84 + expect(done).toContain("✦ APPLICATION");
85 + expect(done).toContain("stamped, filed, and forgotten");
86 + expect(done).toContain("✷ VALID UNTIL ...... 1971-01-01");
87 + expect(done).toContain("A P P R O V E D");
88 + expect(done).toContain("✔ Token in clipboard.");
89 + expect(done).not.toContain(LONG_LIVED);
90 + });
92 + it("keeps the link and the code field live from the first frame", () => {
93 + const first = text(state({ tick: 0 }));
94 + expect(first).toContain("Open the Claude sign-in page");
95 + expect(first).toContain("Code: ");
96 + expect(first).not.toContain("KLAUS");
97 + expect(first).not.toContain("APPLICATION");
99 + const midIntro = text(state({ tick: 13 }));
100 + expect(midIntro).toContain("█");
101 + expect(midIntro).toContain("KLAUS");
102 + expect(midIntro).toContain("Code: ");
103 + expect(midIntro).not.toContain("APPLICATION");
104 + });
106 + it("stamps DENIED with the failure and a retry hint", () => {
107 + const denied = state({
108 + phase: "denied",
109 + input: [],
110 + error: "Anthropic rejected the authorization code.",
111 + hints: "r retry · esc close",
112 + });
113 + const rendered = text({
114 + ...denied,
115 + phaseTick: sceneOutcomeTicks(denied),
116 + });
117 + expect(rendered).toContain("D E N I E D");
118 + expect(rendered).toContain("✗ Anthropic rejected the authorization code.");
119 + expect(rendered).toContain("rejected at the window");
120 + expect(rendered).toContain("r retry · esc close");
121 + expect(rendered).not.toContain("VALID UNTIL");
122 + });
124 + it("keeps the stamp dim before it lands", () => {
125 + const raised = text(approved({ phaseTick: 1 }));
126 + expect(raised).toContain("A P P R O V E D");
127 + expect(raised).not.toContain("Token in clipboard.");
128 + });
130 + it("prints the token when the clipboard failed", () => {
131 + const rendered = text(approved({ tokenCopied: false }));
132 + expect(rendered).toContain(LONG_LIVED);
133 + expect(rendered).not.toContain("✔ Token in clipboard.");
134 + });
136 + it("links the sign-in page with OSC 8 and falls back to the raw URL", () => {
137 + const linked = renderScene(state(), 100, theme).join("\n");
138 + expect(linked).toContain(`\x1b]8;;${URL}\x1b\\`);
139 + expect(stripAnsi(linked)).not.toContain("code=true");
141 + const plain = renderScene(state({ hyperlinks: false }), 100, theme).join(
142 + "\n",
143 + );
144 + expect(plain).not.toContain("\x1b]8;;");
145 + expect(plain).toContain("code=true");
146 + });
148 + it("reports the clipboard result for the sign-in link", () => {
149 + expect(text(state({ clipboard: "copied" }))).toContain(
150 + "✔ Link copied to clipboard.",
151 + );
152 + expect(text(state({ clipboard: "failed" }))).toContain(
153 + "⚠ No clipboard tool found.",
154 + );
155 + });
156 +});
158 +describe("Bureau of Tokens responsiveness", () => {
159 + it("picks a layout tier from the available width", () => {
160 + expect(sceneLayout(200)).toBe("full");
161 + expect(sceneLayout(62)).toBe("full");
162 + expect(sceneLayout(61)).toBe("compact");
163 + expect(sceneLayout(42)).toBe("compact");
164 + expect(sceneLayout(41)).toBe("tiny");
165 + expect(sceneLayout(12)).toBe("tiny");
166 + });
168 + it("shrinks mascot, title, stamp, and labels as width drops", () => {
169 + const wide = text(approved(), 100);
170 + const narrow = text(approved(), 30);
171 + expect(wide.split("\n").length).toBeGreaterThan(narrow.split("\n").length);
172 + expect(narrow).toContain("✻ KLAUS · TOKENS ✻");
173 + expect(narrow).toContain("✔ APPROVED");
174 + expect(narrow).toContain("✻ CLERK: Klaus, since 1961");
175 + expect(narrow).toContain("◈ STATUS: stamped");
176 + expect(narrow).not.toContain("PROCESSING FEE");
177 + });
179 + it("wraps long rows instead of truncating them in a tiny terminal", () => {
180 + const rendered = text(approved({ tokenCopied: false }), 20);
181 + expect(rendered.replace(/\n/g, "")).toContain(LONG_LIVED.slice(0, 20));
182 + expect(rendered).toContain("paperwork.");
183 + });
185 + it("never exceeds the supplied width in any phase", () => {
186 + const scenes = [
187 + state({ tick: 4 }),
188 + state(),
189 + state({ hyperlinks: false }),
190 + state({ phase: "exchanging", input: [] }),
191 + approved(),
192 + approved({ tokenCopied: false }),
193 + ];
194 + for (const width of [12, 16, 20, 24, 30, 41, 42, 50, 61, 62, 80, 200]) {
195 + for (const scene of scenes) {
196 + for (const line of renderScene(scene, width, theme)) {
197 + expect(stripAnsi(line).length).toBeLessThanOrEqual(
198 + Math.max(width, 12),
199 + );
203 + });
205 + it("paints with the Anthropic brand ramp only in true color", () => {
206 + const mascot = (active: never) =>
207 + renderScene(state({ tick: 6 }), 100, active)[0] ?? "";
208 + expect(mascot(truecolorTheme)).toContain("\x1b[38;2;");
209 + expect(mascot(theme)).not.toContain("\x1b[38;2;");
210 + });
211 +});
213 +describe("Bureau of Tokens copy", () => {
214 + it("adds the validity row only once a token exists", () => {
215 + expect(sceneFormLines(state()).some((line) => line.includes("VALID"))).toBe(
216 + false,
217 + );
218 + expect(
219 + sceneFormLines(approved()).some((line) => line.includes("VALID")),
220 + ).toBe(true);
221 + expect(
222 + sceneFormLines(approved({ expiresInSeconds: undefined })).some((line) =>
223 + line.includes("VALID"),
224 + ),
225 + ).toBe(false);
226 + });
228 + it("has no verdict before an outcome", () => {
229 + expect(sceneVerdictLines(state())).toEqual([]);
230 + expect(sceneVerdictLines(state({ phase: "exchanging" }))).toEqual([]);
231 + expect(sceneVerdictLines(approved())).toHaveLength(2);
232 + expect(sceneOutcomeTicks(state())).toBe(0);
233 + expect(sceneOutcomeTicks(approved())).toBeGreaterThan(0);
234 + });
235 +});

extensions/klaus/__tests__/setup-token.test.ts

Added
new file mode 100644
1 +import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2 +import {
3 + getCapabilities,
4 + resetCapabilitiesCache,
5 + setCapabilities,
6 +} from "@earendil-works/pi-tui";
7 +import { afterEach, describe, expect, it } from "vitest";
8 +import {
9 + AUTHORIZE_URL,
10 + buildAuthorizeUrl,
11 + type ClipboardRunner,
12 + clipboardCandidates,
13 + copyToClipboard,
14 + EXPIRES_IN_SECONDS,
15 + exchangeCode,
16 + generatePkce,
17 + openerCandidates,
18 + type Pkce,
19 + parseAuthorizationInput,
20 + REDIRECT_URI,
21 + runSetupTokenCommand,
22 + TOKEN_URL,
23 +} from "../src/setup-token";
25 +const LONG_LIVED = "sk-ant-oat01-abcdefghijklmnopqrstuvwxyz0123456789";
26 +const PKCE: Pkce = {
27 + verifier: "verifier",
28 + challenge: "challenge",
29 + state: "st",
30 +};
32 +const KEYS: Record<string, string> = {
33 + "tui.select.cancel": "\x1b",
34 + "app.interrupt": "\x03",
35 +};
37 +function jsonResponse(body: unknown, status = 200): Response {
38 + return new Response(typeof body === "string" ? body : JSON.stringify(body), {
39 + status,
40 + });
43 +type Component = {
44 + render: (width: number) => string[];
45 + handleInput?: (data: string) => void;
46 +};
48 +function tuiCtx() {
49 + const components: Component[] = [];
50 + const notifications: Array<{ message: string; level: string }> = [];
51 + const statuses: Array<string | undefined> = [];
52 + const ctx = {
53 + hasUI: true,
54 + mode: "tui",
55 + ui: {
56 + custom: (
57 + factory: (
58 + tui: unknown,
59 + theme: unknown,
60 + keybindings: unknown,
61 + done: (value: unknown) => void,
62 + ) => Component,
63 + ) =>
64 + new Promise((resolve) => {
65 + components.push(
66 + factory(
67 + { requestRender() {} },
68 + {
69 + fg: (_style: string, text: string) => text,
70 + bold: (text: string) => text,
71 + getColorMode: () => "256color",
72 + },
73 + {
74 + matches: (data: string, action: string) =>
75 + KEYS[action] === data,
76 + },
77 + resolve,
78 + ),
79 + );
80 + }),
81 + notify: (message: string, level: string) => {
82 + notifications.push({ message, level });
83 + },
84 + setStatus: (_key: string, value: string | undefined) => {
85 + statuses.push(value);
86 + },
87 + },
88 + } as unknown as ExtensionContext;
89 + return { ctx, components, notifications, statuses };
92 +async function waitFor<T>(
93 + probe: () => T | undefined,
94 + timeoutMs = 6000,
95 +): Promise<T> {
96 + const deadline = Date.now() + timeoutMs;
97 + for (;;) {
98 + const value = probe();
99 + if (value !== undefined) return value;
100 + if (Date.now() > deadline) throw new Error("timed out");
101 + await new Promise((resolve) => setTimeout(resolve, 10));
105 +describe("Klaus setup-token authorization", () => {
106 + it("builds a PKCE authorize URL with the setup-token scope", async () => {
107 + const pkce = await generatePkce();
108 + expect(pkce.verifier).not.toBe(pkce.state);
109 + const url = new URL(buildAuthorizeUrl(pkce));
110 + expect(`${url.origin}${url.pathname}`).toBe(AUTHORIZE_URL);
111 + expect(url.searchParams.get("scope")).toBe("user:inference");
112 + expect(url.searchParams.get("redirect_uri")).toBe(REDIRECT_URI);
113 + expect(url.searchParams.get("code_challenge")).toBe(pkce.challenge);
114 + expect(url.searchParams.get("code_challenge_method")).toBe("S256");
115 + expect(url.searchParams.get("state")).toBe(pkce.state);
116 + expect(url.searchParams.get("client_id")).toMatch(/^[0-9a-f-]{36}$/);
117 + });
119 + it("parses code#state, redirect URLs, query strings, and bare codes", () => {
120 + expect(parseAuthorizationInput(" abc#st ")).toEqual({
121 + code: "abc",
122 + state: "st",
123 + });
124 + expect(
125 + parseAuthorizationInput(`${REDIRECT_URI}?code=abc&state=st`),
126 + ).toEqual({ code: "abc", state: "st" });
127 + expect(parseAuthorizationInput("code=abc&state=st")).toEqual({
128 + code: "abc",
129 + state: "st",
130 + });
131 + expect(parseAuthorizationInput("abc")).toEqual({ code: "abc" });
132 + expect(parseAuthorizationInput(" ")).toBeUndefined();
133 + expect(parseAuthorizationInput("#st")).toBeUndefined();
134 + });
135 +});
137 +describe("Klaus setup-token exchange", () => {
138 + it("posts the long-lived exchange request and returns the token", async () => {
139 + const requests: Array<{ url: string; body: unknown }> = [];
140 + const minted = await exchangeCode(
141 + { code: "abc", state: "st" },
142 + PKCE,
143 + async (url, init) => {
144 + requests.push({ url, body: JSON.parse(String(init.body)) });
145 + return jsonResponse({
146 + access_token: LONG_LIVED,
147 + expires_in: EXPIRES_IN_SECONDS,
148 + });
149 + },
150 + );
151 + expect(minted).toEqual({
152 + token: LONG_LIVED,
153 + expiresInSeconds: EXPIRES_IN_SECONDS,
154 + });
155 + expect(requests[0]?.url).toBe(TOKEN_URL);
156 + expect(requests[0]?.body).toMatchObject({
157 + grant_type: "authorization_code",
158 + code: "abc",
159 + redirect_uri: REDIRECT_URI,
160 + code_verifier: "verifier",
161 + state: "st",
162 + expires_in: EXPIRES_IN_SECONDS,
163 + });
164 + });
166 + it("rejects state mismatches before any request", async () => {
167 + let called = false;
168 + await expect(
169 + exchangeCode({ code: "abc", state: "other" }, PKCE, async () => {
170 + called = true;
171 + return jsonResponse({});
172 + }),
173 + ).rejects.toThrow(/state mismatch/);
174 + expect(called).toBe(false);
175 + });
177 + it("reports HTTP failures, invalid JSON, and missing tokens", async () => {
178 + await expect(
179 + exchangeCode({ code: "abc" }, PKCE, async () =>
180 + jsonResponse("nope", 401),
181 + ),
182 + ).rejects.toThrow(/rejected the authorization code/);
183 + await expect(
184 + exchangeCode({ code: "abc" }, PKCE, async () =>
185 + jsonResponse("<html>", 500),
186 + ),
187 + ).rejects.toThrow(/500/);
188 + await expect(
189 + exchangeCode({ code: "abc" }, PKCE, async () => jsonResponse("<html>")),
190 + ).rejects.toThrow(/invalid JSON/);
191 + await expect(
192 + exchangeCode({ code: "abc" }, PKCE, async () => jsonResponse({})),
193 + ).rejects.toThrow(/no access token/);
194 + });
195 +});
197 +describe("Klaus setup-token counter scene", () => {
198 + afterEach(() => {
199 + resetCapabilitiesCache();
200 + });
202 + function withHyperlinks(hyperlinks: boolean): void {
203 + setCapabilities({ ...getCapabilities(), hyperlinks });
206 + async function openScene(
207 + deps: Parameters<typeof runSetupTokenCommand>[1] = {},
208 + hyperlinks = true,
209 + ) {
210 + withHyperlinks(hyperlinks);
211 + const session = tuiCtx();
212 + const run = runSetupTokenCommand(session.ctx, {
213 + pkce: async () => PKCE,
214 + openUrl: async () => true,
215 + copy: async () => true,
216 + ...deps,
217 + });
218 + const scene = await waitFor(() => session.components[0]);
219 + return { ...session, scene, run };
222 + function type(
223 + scene: { handleInput?: (data: string) => void },
224 + value: string,
225 + ): void {
226 + for (const key of [...value]) scene.handleInput?.(key);
229 + async function waitForText(
230 + scene: { render: (width: number) => string[] },
231 + needle: string,
232 + ): Promise<string> {
233 + return waitFor(() => {
234 + const rendered = scene.render(100).join("\n");
235 + return rendered.includes(needle) ? rendered : undefined;
236 + });
239 + it("runs filing, sign-in, exchange, and stamp in one component", async () => {
240 + const copied: string[] = [];
241 + const opened: string[] = [];
242 + const { scene, run, notifications, components } = await openScene({
243 + openUrl: async (url) => {
244 + opened.push(url);
245 + return true;
246 + },
247 + fetchFn: async () =>
248 + jsonResponse({ access_token: LONG_LIVED, expires_in: 3600 }),
249 + copy: async (text) => {
250 + copied.push(text);
251 + return true;
252 + },
253 + });
255 + expect(opened).toEqual([buildAuthorizeUrl(PKCE)]);
256 + const signin = await waitForText(scene, "waiting for your code");
257 + expect(signin).toContain("BUREAU OF TOKENS");
258 + expect(signin).toContain("Open the Claude sign-in page");
259 + expect(signin).toContain("Code: ");
261 + type(scene, "abc#st");
262 + scene.handleInput?.("\r");
263 + const stamped = await waitForText(scene, "A P P R O V E D");
264 + expect(copied).toEqual([LONG_LIVED]);
265 + expect(stamped).toContain("VALID UNTIL");
266 + expect(stamped).not.toContain("Code: ");
267 + expect(stamped).toContain("any key to skip");
269 + scene.handleInput?.("x");
270 + const settled = scene.render(100).join("\n");
271 + expect(settled).toContain("✔ Token in clipboard.");
272 + expect(settled).toContain("any key to close");
274 + scene.handleInput?.("x");
275 + await run;
276 + expect(components).toHaveLength(1);
277 + expect(notifications).toEqual([]);
278 + });
280 + it("cancels on escape and on interrupt without any exchange", async () => {
281 + for (const key of ["\x1b", "\x03"]) {
282 + let fetched = false;
283 + const { scene, run, notifications } = await openScene({
284 + fetchFn: async () => {
285 + fetched = true;
286 + return jsonResponse({});
287 + },
288 + });
289 + scene.handleInput?.(key);
290 + await run;
291 + expect(fetched).toBe(false);
292 + expect(notifications.at(-1)?.message).toContain("application withdrawn");
294 + });
296 + it("stamps DENIED in place and retries on r", async () => {
297 + const opened: string[] = [];
298 + let attempt = 0;
299 + const { scene, run, notifications } = await openScene({
300 + openUrl: async (url) => {
301 + opened.push(url);
302 + return true;
303 + },
304 + fetchFn: async () => {
305 + attempt++;
306 + return attempt === 1
307 + ? jsonResponse("bad", 401)
308 + : jsonResponse({ access_token: LONG_LIVED });
309 + },
310 + });
312 + await waitForText(scene, "Code: ");
313 + type(scene, "abc");
314 + scene.handleInput?.("\r");
315 + const denied = await waitForText(scene, "rejected the authorization code");
316 + expect(denied).toContain("D E N I E D");
317 + expect(notifications).toEqual([]);
319 + scene.handleInput?.("x");
320 + expect(scene.render(100).join("\n")).toContain("r retry · esc close");
321 + scene.handleInput?.("r");
322 + const retried = await waitForText(scene, "Code: ");
323 + expect(retried).toContain("Open the Claude sign-in page");
324 + expect(retried).toContain("enter submit");
325 + expect(retried).not.toContain("D E N I E D");
326 + expect(opened).toHaveLength(2);
328 + type(scene, "abc");
329 + scene.handleInput?.("\r");
330 + await waitForText(scene, "A P P R O V E D");
331 + scene.handleInput?.("x");
332 + scene.handleInput?.("x");
333 + await run;
334 + });
336 + it("links the sign-in page with OSC 8 and falls back to the raw URL", async () => {
337 + const linked = await openScene({}, true);
338 + await waitForText(linked.scene, "Open the Claude sign-in page");
339 + const link =
340 + linked.scene.render(80).find((line) => line.includes("\x1b]8;;")) ?? "";
341 + expect(link).toContain(`\x1b]8;;${buildAuthorizeUrl(PKCE)}\x1b\\`);
342 + expect(link).toContain("Open the Claude sign-in page");
343 + linked.scene.handleInput?.("\x1b");
344 + await linked.run;
346 + const plain = await openScene({}, false);
347 + await waitForText(plain.scene, "code_challenge");
348 + const rendered = plain.scene.render(80).join("");
349 + expect(rendered).not.toContain("\x1b]8;;");
350 + expect(rendered).toContain("code_challenge");
351 + plain.scene.handleInput?.("\x1b");
352 + await plain.run;
353 + });
355 + it("copies the link on c while the code field is empty", async () => {
356 + const copies: string[] = [];
357 + const { scene, run } = await openScene({
358 + copy: async (text) => {
359 + copies.push(text);
360 + return true;
361 + },
362 + });
363 + await waitForText(scene, "Open the Claude sign-in page");
364 + scene.handleInput?.("c");
365 + await waitForText(scene, "Link copied to clipboard.");
366 + expect(copies).toEqual([buildAuthorizeUrl(PKCE)]);
368 + type(scene, "abc");
369 + scene.handleInput?.("c");
370 + expect(copies).toHaveLength(1);
371 + expect(scene.render(100).join("\n")).toContain("abcc");
372 + scene.handleInput?.("\x1b");
373 + await run;
374 + });
376 + it("uses the plain input dialog outside the TUI and never opens a browser", async () => {
377 + const notifications: Array<{ message: string; level: string }> = [];
378 + const titles: string[] = [];
379 + let opened = false;
380 + const ctx = {
381 + hasUI: true,
382 + mode: "rpc",
383 + ui: {
384 + input: async (title: string) => {
385 + titles.push(title);
386 + return "abc#st";
387 + },
388 + notify: (message: string, level: string) => {
389 + notifications.push({ message, level });
390 + },
391 + setStatus() {},
392 + },
393 + } as unknown as ExtensionContext;
394 + await runSetupTokenCommand(ctx, {
395 + pkce: async () => PKCE,
396 + openUrl: async () => {
397 + opened = true;
398 + return true;
399 + },
400 + fetchFn: async () => jsonResponse({ access_token: LONG_LIVED }),
401 + copy: async () => false,
402 + });
403 + expect(opened).toBe(false);
404 + expect(titles[0]).toContain(AUTHORIZE_URL);
405 + expect(notifications.at(-1)).toEqual({
406 + message: `No clipboard. Token: ${LONG_LIVED}`,
407 + level: "warning",
408 + });
409 + });
410 +});
412 +describe("Klaus setup-token clipboard", () => {
413 + it("prefers wayland, then xclip, then xsel on linux", () => {
414 + expect(clipboardCandidates("linux")).toEqual([
415 + ["wl-copy"],
416 + ["xclip", "-selection", "clipboard"],
417 + ["xsel", "--clipboard", "--input"],
418 + ]);
419 + });
421 + it("uses the platform tool on darwin, win32, and android", () => {
422 + expect(clipboardCandidates("darwin")).toEqual([["pbcopy"]]);
423 + expect(clipboardCandidates("win32")).toEqual([["clip"]]);
424 + expect(clipboardCandidates("android")).toEqual([["termux-clipboard-set"]]);
425 + });
427 + it("stops at the first working tool", async () => {
428 + const attempted: string[][] = [];
429 + const runner: ClipboardRunner = async (command, text) => {
430 + attempted.push(command);
431 + return command[0] === "xclip" && text === LONG_LIVED;
432 + };
433 + await expect(copyToClipboard(LONG_LIVED, runner, "linux")).resolves.toBe(
434 + true,
435 + );
436 + expect(attempted).toEqual([
437 + ["wl-copy"],
438 + ["xclip", "-selection", "clipboard"],
439 + ]);
440 + });
442 + it("reports failure when every tool fails", async () => {
443 + const runner: ClipboardRunner = async () => false;
444 + await expect(copyToClipboard(LONG_LIVED, runner, "linux")).resolves.toBe(
445 + false,
446 + );
447 + });
448 +});
450 +describe("Klaus browser opener", () => {
451 + it("prefers termux, macOS, and Windows openers by platform", () => {
452 + expect(
453 + openerCandidates("https://x", {
454 + platform: "linux",
455 + env: { TERMUX_VERSION: "1" },
456 + }),
457 + ).toEqual([{ command: "termux-open-url", args: ["https://x"] }]);
458 + expect(
459 + openerCandidates("https://x", { platform: "darwin", env: {} }),
460 + ).toEqual([{ command: "open", args: ["https://x"] }]);
461 + expect(
462 + openerCandidates("https://x", { platform: "linux", env: {} }).map(
463 + (candidate) => candidate.command,
464 + ),
465 + ).toEqual(["xdg-open", "wslview", "gio"]);
466 + });
467 +});

extensions/klaus/__tests__/thinking.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { klausThinkingConfig } from "../src/agent-sdk";
4 +describe("Klaus thinking configuration", () => {
5 + it("disables thinking when Pi requests none", () => {
6 + expect(
7 + klausThinkingConfig({
8 + modelId: "claude-opus-5",
9 + thinking: undefined,
10 + thinkingBudget: 16384,
11 + }),
12 + ).toEqual({ type: "disabled" });
13 + });
15 + it("keeps adaptive models adaptive even with a Pi thinking budget", () => {
16 + expect(
17 + klausThinkingConfig({
18 + modelId: "claude-opus-5",
19 + thinking: "high",
20 + thinkingBudget: 16384,
21 + }),
22 + ).toEqual({ type: "adaptive" });
23 + expect(
24 + klausThinkingConfig({
25 + modelId: "claude-fable-5-1",
26 + thinking: "xhigh",
27 + thinkingBudget: 16384,
28 + }),
29 + ).toEqual({ type: "adaptive" });
30 + expect(
31 + klausThinkingConfig({
32 + modelId: "claude-sonnet-5",
33 + thinking: "medium",
34 + }),
35 + ).toEqual({ type: "adaptive" });
36 + });
38 + it("pins budget-based models to fixed budgets", () => {
39 + expect(
40 + klausThinkingConfig({
41 + modelId: "claude-haiku-4-5",
42 + thinking: "medium",
43 + thinkingBudget: 8192,
44 + }),
45 + ).toEqual({ type: "enabled", budgetTokens: 8192 });
46 + });
48 + it("falls back to klaus default budgets for haiku", () => {
49 + expect(
50 + klausThinkingConfig({
51 + modelId: "claude-haiku-4-5",
52 + thinking: "high",
53 + }),
54 + ).toEqual({ type: "enabled", budgetTokens: 16384 });
55 + expect(
56 + klausThinkingConfig({
57 + modelId: "claude-haiku-4-5",
58 + thinking: "minimal",
59 + }),
60 + ).toEqual({ type: "enabled", budgetTokens: 1024 });
61 + });
62 +});

extensions/klaus/index.ts

Modified
16 16 type KlausModelId,
17 17 MODEL_SELECTORS,
18 18 } from "./src/protocol.js";
19 +import { runSetupTokenCommand } from "./src/setup-token.js";
20 21 const MODEL_IDS = Object.keys(MODEL_SELECTORS) as KlausModelId[];
21 22 const FABLE_FALLBACK_IDS = ["claude-opus-4-8", "claude-opus-5"] as const;
65 66 return models;
68 -export default function klaus(pi: ExtensionAPI): void {
69 +export default function klaus(pi: ExtensionAPI): void | Promise<void> {
69 70 dbg?.("index.extension.start");
71 + pi.registerCommand("klaus-setup-token", {
72 + description: "Mint a long-lived Claude OAuth token with your subscription",
73 + async handler(_args, commandCtx) {
74 + await runSetupTokenCommand(commandCtx);
75 + },
76 + });
70 77 let context: ExtensionContext | undefined;
71 78 let warnedFable = false;
72 79 let warnedPromptDrift = false;

extensions/klaus/src/agent-sdk.ts

Modified
4 4 import {
5 5 type EffortLevel,
6 6 type Query,
7 7 query,
8 8 type SDKMessage,
9 9 type SDKUserMessage,
10 + type ThinkingConfig,
10 11 } from "@anthropic-ai/claude-agent-sdk";
11 12 import { dbg } from "./debug.js";
12 13 import type { KlausQueryCallbacks, KlausRequest } from "./protocol.js";
50 51 return level === "minimal" ? "low" : level;
54 +/** Fallback budgets mirror Pi's DEFAULT_THINKING_BUDGETS so a Haiku request
55 + * without Pi-configured budgets behaves like native Pi usage. */
53 56 function defaultThinkingBudget(level: KlausRequest["thinking"]): number {
54 57 switch (level) {
55 58 case "minimal":
56 - return 4096;
59 + return 1024;
57 60 case "low":
58 - return 4096;
61 + return 2048;
59 62 case "medium":
60 - return 10240;
63 + return 8192;
61 64 default:
62 - return 20480;
65 + return 16384;
69 +/** Adaptive-thinking models always run adaptive with effort, matching Pi's
70 + * native treatment of them: Pi thinking budgets are not a lever for these
71 + * models and must not pin them into fixed-budget thinking. Only budget-based
72 + * models (Haiku) consume an explicit budget. */
73 +export function klausThinkingConfig(
74 + request: Pick<KlausRequest, "modelId" | "thinking" | "thinkingBudget">,
75 +): ThinkingConfig {
76 + if (!request.thinking) return { type: "disabled" };
77 + if (request.modelId === "claude-haiku-4-5") {
78 + return {
79 + type: "enabled",
80 + budgetTokens:
81 + request.thinkingBudget ?? defaultThinkingBudget(request.thinking),
82 + };
83 + }
84 + return { type: "adaptive" };
66 87 function errorText(error: unknown): string {
67 88 return error instanceof Error ? error.message : String(error);
192 213 oauthToken,
193 214 request.headers,
194 215 request.env,
216 + request.maxTokens,
196 218 dbg?.("sdk.runtime.ready", {
197 219 executable: runtime.executable,
275 297 resumeSessionAt: request.resumeAt,
276 298 forkSession: request.forkSession,
277 299 permissionMode: "default",
278 - thinking: request.thinking
279 - ? request.thinkingBudget || request.modelId === "claude-haiku-4-5"
280 - ? {
281 - type: "enabled",
282 - budgetTokens:
283 - request.thinkingBudget ??
284 - defaultThinkingBudget(request.thinking),
285 - }
286 - : { type: "adaptive" }
287 - : { type: "disabled" },
300 + thinking: klausThinkingConfig(request),
288 301 effort: effort(request.thinking),
289 302 betas: runtime.betas,
290 303 settings: {

extensions/klaus/src/coordinator.ts

Modified
59 59 cwd: string;
60 60 thinking: SimpleStreamOptions["reasoning"];
61 61 thinkingBudget?: number;
62 + maxTokens?: number;
62 63 systemPrompt: string;
63 64 headers: SimpleStreamOptions["headers"];
64 65 env: SimpleStreamOptions["env"];
490 491 continuation.systemPrompt !== (context.systemPrompt ?? "") ||
491 492 continuation.thinking !== options.reasoning ||
492 493 continuation.thinkingBudget !== thinkingBudget(options) ||
494 + continuation.maxTokens !== options.maxTokens ||
493 495 !sameStringRecord(continuation.headers, options.headers) ||
494 496 !sameStringRecord(continuation.env, options.env);
495 497 dbg?.("coordinator.invoke.compatibility", { incompatible });
657 659 tools,
658 660 thinking: options.reasoning,
659 661 thinkingBudget: thinkingBudget(options),
662 + maxTokens: options.maxTokens,
661 664 sessionId: options.sessionId,
662 665 headers: options.headers ?? {},
676 679 toolNames: request.tools.map((tool) => tool.name),
677 680 thinking: request.thinking,
678 681 thinkingBudget: request.thinkingBudget,
682 + maxTokens: request.maxTokens,
679 683 cwd: request.cwd,
680 684 resume: Boolean(request.resume),
681 685 resumeAt: Boolean(request.resumeAt),
741 745 thinking: options.reasoning,
742 746 thinkingBudget: thinkingBudget(options),
747 + maxTokens: options.maxTokens,
743 748 systemPrompt: context.systemPrompt ?? "",
744 749 headers: options.headers,
745 750 env: options.env,
1222 1227 (request.thinkingBudget === undefined ||
1223 1228 (Number.isInteger(request.thinkingBudget) &&
1224 1229 request.thinkingBudget > 0)) &&
1230 + (request.maxTokens === undefined ||
1231 + (Number.isSafeInteger(request.maxTokens) && request.maxTokens > 0)) &&
1225 1232 (request.timeoutMs === undefined ||
1226 1233 (Number.isFinite(request.timeoutMs) && request.timeoutMs >= 0)) &&
1227 1234 (request.sessionId === undefined ||

extensions/klaus/src/protocol.ts

Modified
40 40 tools: KlausTool[];
41 41 thinking: ThinkingLevel | undefined;
42 42 thinkingBudget?: number;
43 + maxTokens?: number;
43 44 cwd: string;
44 45 sessionId?: string;
45 46 headers: Record<string, string | null>;

extensions/klaus/src/runtime/index.ts

Modified
90 90 oauthToken: string,
91 91 headers: Record<string, string | null>,
92 92 overrides: Record<string, string> = {},
93 + maxTokens?: number,
93 94 ): Promise<ChildRuntime> {
94 95 dbg?.("runtime.create.start", {
95 96 platform: process.platform,
112 113 env.CLAUDE_AGENT_SDK_CLIENT_APP = "klaus/1";
113 114 env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
114 115 env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY = "0";
116 + if (maxTokens !== undefined) {
117 + if (!Number.isSafeInteger(maxTokens) || maxTokens < 1) {
118 + throw new Error(
119 + `Klaus received an invalid maxTokens value ${String(maxTokens)}.`,
120 + );
122 + env.CLAUDE_CODE_MAX_OUTPUT_TOKENS = String(maxTokens);
115 124 if (mapped.serialized) env.ANTHROPIC_CUSTOM_HEADERS = mapped.serialized;
117 126 process.env.VITEST &&

extensions/klaus/src/setup-scene.ts

Added
new file mode 100644
1 +/**
2 + * The Bureau of Tokens counter: one continuous scene that frames the whole
3 + * `setup-token` visit, from filing the application to the stamp. A loving
4 + * parody of Claude Code's own over-the-top welcome animation, in Anthropic
5 + * brand colors and three width tiers.
6 + */
7 +import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
8 +import {
9 + truncateToWidth,
10 + visibleWidth,
11 + wrapTextWithAnsi,
12 +} from "@earendil-works/pi-tui";
14 +export const SCENE_TICK_MS = 70;
16 +export type SceneLayout = "full" | "compact" | "tiny";
17 +export type ScenePhase = "signin" | "exchanging" | "approved" | "denied";
18 +export type ClipboardState = "idle" | "copied" | "failed";
20 +export type SceneState = {
21 + /** Ticks since the scene opened; drives the intro animation and twinkles. */
22 + tick: number;
23 + /** Ticks since the current phase began; drives the stamp and verdict. */
24 + phaseTick: number;
25 + phase: ScenePhase;
26 + /** Pre-rendered lines of the code field, empty once it is gone. */
27 + input: string[];
28 + hyperlinks: boolean;
29 + url: string;
30 + clipboard: ClipboardState;
31 + hints: string;
32 + token?: string;
33 + tokenCopied?: boolean;
34 + expiresInSeconds?: number;
35 + error?: string;
36 + now?: number;
37 +};
39 +const FULL_MIN_WIDTH = 62;
40 +const COMPACT_MIN_WIDTH = 42;
42 +export function sceneLayout(width: number): SceneLayout {
43 + if (width >= FULL_MIN_WIDTH) return "full";
44 + if (width >= COMPACT_MIN_WIDTH) return "compact";
45 + return "tiny";
48 +/** Anthropic brand ramp: book cloth, Claude orange, kraft, manilla, cloud. */
49 +const BRAND_RAMP: Array<[number, number, number]> = [
50 + [204, 120, 92],
51 + [217, 119, 87],
52 + [212, 162, 127],
53 + [235, 219, 188],
54 + [240, 240, 235],
55 +];
57 +/** Theme-color stand-ins for terminals without true color, same order as the ramp. */
58 +const RAMP_FALLBACK: ThemeColor[] = [
59 + "error",
60 + "accent",
61 + "warning",
62 + "muted",
63 + "text",
64 +];
66 +const SHADES = ["░", "▒", "▓", "█"];
67 +const CARET = "▎";
68 +const TWINKLE = ["✳", "✶", "✷", "✻", "·"];
69 +const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
71 +const MASCOTS: Record<SceneLayout, string[]> = {
72 + full: [
73 + " ▄▄▄███████▄▄▄",
74 + " ▄▄██▀▀▀ ▀▀▀██▄▄",
75 + " ▄█▀▀ ▄▄███████▄▄ ▀▀█▄",
76 + " ██▀ ▄█▀▀ ▀▀█▄ ▀██",
77 + " ██ █▀ ▄▄███▄▄ ▀█ ██",
78 + " ██ █▌ █▀ ▀█ ▐█ ██",
79 + " ██ █▄ ▀▀███▀▀ ▄█ ██",
80 + " ▗▖ ▀█▄ ▀▀█▄▄ ▄▄█▀▀ ▄█▀",
81 + " ▐▌● ▀▀█▄▄ ▀▀█████▀▀ ▄▄█▀",
82 + " ▝▚▄▄▄▄▄▄▀▀███▄▄▄▄▄▄▄▄███▀▀",
83 + ],
84 + compact: [
85 + " ▄▄█████▄▄",
86 + " ▄██▀▀ ▀▀██▄",
87 + " ▄█▀ ▄▄███▄▄ ▀█▄",
88 + " ██ █▀ ▀█ ██",
89 + " ██ █▄ ▀ ▄█ ██",
90 + "▗▖ ▀█▄ ▀▀███▀▀ ▄█▀",
91 + "▐▌● ▀▀██▄▄ ▄▄██▀▀",
92 + "▝▚▄▄▄▄▄▄▄▀▀█████▀▀",
93 + ],
94 + tiny: [
95 + " ▄▄███▄▄",
96 + " ▄█▀ ▄▄▄ ▀█▄",
97 + " ██ █▀ ▀█ ██",
98 + "▗▖▀█▄ ▀▀▀ ▄█▀",
99 + "▐▌● ▀▀█▀▀",
100 + ],
103 +/** Reveal timing stays width independent so hints and skipping behave the same everywhere. */
104 +const MASCOT_REVEAL_TICKS = Math.max(
105 + ...Object.values(MASCOTS).map((mascot) => mascot.length),
108 +const SPARKLES: Record<SceneLayout, Array<{ row: number; col: number }>> = {
109 + full: [
110 + { row: 0, col: 33 },
111 + { row: 2, col: 1 },
112 + { row: 1, col: 32 },
113 + { row: 4, col: 34 },
114 + { row: 3, col: 0 },
115 + { row: 6, col: 34 },
116 + { row: 8, col: 32 },
117 + { row: 5, col: 0 },
118 + ],
119 + compact: [
120 + { row: 0, col: 23 },
121 + { row: 2, col: 0 },
122 + { row: 4, col: 24 },
123 + { row: 6, col: 22 },
124 + { row: 1, col: 1 },
125 + ],
126 + tiny: [
127 + { row: 0, col: 15 },
128 + { row: 2, col: 0 },
129 + { row: 4, col: 15 },
130 + ],
133 +const TITLES: Record<SceneLayout, string> = {
134 + full: "✻ KLAUS · BUREAU OF TOKENS · WINDOW 08/15 ✻",
135 + compact: "✻ KLAUS · BUREAU OF TOKENS ✻",
136 + tiny: "✻ KLAUS · TOKENS ✻",
139 +const LINK_LABEL = "Open the Claude sign-in page";
141 +const STAMPS: Record<SceneLayout, Record<"approved" | "denied", string[]>> = {
142 + full: {
143 + approved: [
144 + "┏━━━━━━━━━━━━━━━━━━━━━┓",
145 + "┃ ✔ A P P R O V E D ┃",
146 + "┗━━━━━━━━━━━━━━━━━━━━━┛",
147 + ],
148 + denied: [
149 + "┏━━━━━━━━━━━━━━━━━┓",
150 + "┃ ✗ D E N I E D ┃",
151 + "┗━━━━━━━━━━━━━━━━━┛",
152 + ],
153 + },
154 + compact: {
155 + approved: ["┏━━━━━━━━━━━━━━┓", "┃ ✔ APPROVED ┃", "┗━━━━━━━━━━━━━━┛"],
156 + denied: ["┏━━━━━━━━━━━━┓", "┃ ✗ DENIED ┃", "┗━━━━━━━━━━━━┛"],
157 + },
158 + tiny: {
159 + approved: ["┏━━━━━━━━━━━━┓", "┃ ✔ APPROVED ┃", "┗━━━━━━━━━━━━┛"],
160 + denied: ["┏━━━━━━━━━━┓", "┃ ✗ DENIED ┃", "┗━━━━━━━━━━┛"],
161 + },
164 +const TITLE_START = MASCOT_REVEAL_TICKS + 1;
165 +const FORM_START = TITLE_START + 6;
166 +const FORM_TICKS_PER_ROW = 2;
167 +/** Ticks until the whole intro has settled: mascot, title, and every form row. */
168 +export const SCENE_INTRO_TICKS = FORM_START + 6 * FORM_TICKS_PER_ROW + 2;
169 +const STAMP_TICKS = 4;
170 +const VERDICT_TICKS_PER_LINE = 4;
172 +type FormRow = { icon: string; label: string; value: string };
174 +function statusValue(state: SceneState, layout: SceneLayout): string {
175 + const spin = SPINNER[state.tick % SPINNER.length];
176 + const pick = (full: string, compact: string, tiny: string) =>
177 + layout === "full" ? full : layout === "compact" ? compact : tiny;
178 + switch (state.phase) {
179 + case "signin":
180 + return `${pick(
181 + "at the window, waiting for your code",
182 + "waiting for your code",
183 + "waiting",
184 + )} ${spin}`;
185 + case "exchanging":
186 + return `${pick("consulting the archive", "consulting the archive", "checking")} ${spin}`;
187 + case "approved":
188 + return pick(
189 + "stamped, filed, and forgotten",
190 + "stamped and filed",
191 + "stamped",
192 + );
193 + case "denied":
194 + return pick(
195 + "rejected at the window",
196 + "rejected at the window",
197 + "rejected",
198 + );
202 +function formRows(state: SceneState, layout: SceneLayout): FormRow[] {
203 + const compact = layout !== "full";
204 + const rows: FormRow[] = [
206 + icon: "✦",
207 + label: compact ? "TOKEN" : "APPLICATION",
208 + value: compact ? "one (1), personal" : "one (1) personal token",
209 + },
210 + { icon: "◆", label: compact ? "FOR" : "FILED BY", value: "you" },
212 + icon: "✻",
213 + label: "CLERK",
214 + value: compact ? "Klaus, since 1961" : "Klaus (in office since 1961)",
215 + },
217 + icon: "✧",
218 + label: compact ? "FEE" : "PROCESSING FEE",
219 + value: "your patience",
220 + },
221 + ];
222 + if (state.phase === "approved" && state.expiresInSeconds !== undefined) {
223 + const until = new Date(
224 + (state.now ?? Date.now()) + state.expiresInSeconds * 1000,
226 + .toISOString()
227 + .slice(0, 10);
228 + rows.push({
229 + icon: "✷",
230 + label: compact ? "VALID" : "VALID UNTIL",
231 + value: until,
232 + });
234 + rows.push({
235 + icon: "◈",
236 + label: "STATUS",
237 + value: statusValue(state, layout),
238 + });
239 + return rows;
242 +export function sceneFormLines(
243 + state: SceneState,
244 + layout: SceneLayout = "full",
245 +): string[] {
246 + const rows = formRows(state, layout);
247 + if (layout === "tiny")
248 + return rows.map((row) => `${row.icon} ${row.label}: ${row.value}`);
249 + const labelWidth = Math.max(...rows.map((row) => row.label.length));
250 + return rows.map(
251 + (row) =>
252 + `${row.icon} ${row.label} ${".".repeat(labelWidth - row.label.length + 3)} ${row.value}`,
253 + );
256 +export function sceneVerdictLines(
257 + state: SceneState,
258 + layout: SceneLayout = "full",
259 +): string[] {
260 + if (state.phase === "denied")
261 + return [`✗ ${state.error ?? "The window closed without a reason."}`];
262 + if (state.phase !== "approved") return [];
263 + const quip =
264 + layout === "full"
265 + ? "⁂ Anthropic calls it safety. Klaus calls it paperwork."
266 + : "⁂ Klaus calls it paperwork.";
267 + return state.tokenCopied
268 + ? [quip, "✔ Token in clipboard."]
269 + : [
270 + quip,
271 + layout === "full"
272 + ? "⚠ No clipboard here. Anthropic is everywhere, a clipboard is not."
273 + : "⚠ No clipboard. Copy it yourself:",
274 + state.token ?? "",
275 + ];
278 +/** Ticks the verdict needs after a phase change, used to decide when a skip is complete. */
279 +export function sceneOutcomeTicks(state: SceneState): number {
280 + if (state.phase !== "approved" && state.phase !== "denied") return 0;
281 + return (
282 + STAMP_TICKS +
283 + sceneVerdictLines({ ...state }, "full").length * VERDICT_TICKS_PER_LINE
284 + );
287 +type Painter = {
288 + sweep(text: string, phase: number): string;
289 + ramp(text: string, step: number): string;
290 + color(color: ThemeColor, text: string): string;
293 +function painter(theme: Theme): Painter {
294 + const truecolor = theme.getColorMode() === "truecolor";
295 + const ramp = (text: string, step: number) => {
296 + const index =
297 + ((Math.round(step) % BRAND_RAMP.length) + BRAND_RAMP.length) %
298 + BRAND_RAMP.length;
299 + if (!truecolor) return theme.fg(RAMP_FALLBACK[index], text);
300 + const [r, g, b] = BRAND_RAMP[index];
301 + return `\x1b[38;2;${r};${g};${b}m${text}\x1b[39m`;
302 + };
303 + return {
304 + ramp,
305 + sweep(text, phase) {
306 + let out = "";
307 + let index = 0;
308 + for (const character of text) {
309 + if (character === " ") {
310 + out += character;
311 + index++;
312 + continue;
314 + out += ramp(character, index * 0.5 + phase * 0.45);
315 + index++;
317 + return out;
318 + },
319 + color: (color, text) => theme.fg(color, text),
320 + };
323 +/** Mascot rows materialize from ░ through █. */
324 +function mascotRow(line: string, age: number): string {
325 + if (age >= SHADES.length - 1) return line;
326 + const shade = SHADES[Math.max(age, 0)];
327 + return line.replace(/[█▀▄▓▒░▗▐▝▚]/g, shade);
330 +function reveal(text: string, characters: number): string {
331 + if (characters >= text.length) return text;
332 + return `${text.slice(0, Math.max(characters, 0))}${characters > 0 ? CARET : ""}`;
335 +function indentFor(blockWidth: number, width: number): string {
336 + return " ".repeat(Math.max(0, Math.floor((width - blockWidth) / 2)));
339 +function place(line: string, indent: string, width: number): string {
340 + return truncateToWidth(`${indent}${line}`, width);
343 +function placeGlyph(line: string, column: number, glyph: string): string {
344 + const padded = line.padEnd(column + 1, " ");
345 + return `${padded.slice(0, column)}${glyph}${padded.slice(column + 1)}`;
348 +function revealBlock(
349 + text: string,
350 + characters: number,
351 + blockWidth: number,
352 +): string[] {
353 + const shown = reveal(text, characters);
354 + return visibleWidth(shown) <= blockWidth
355 + ? [shown]
356 + : wrapTextWithAnsi(shown, blockWidth);
359 +function hyperlinkLine(url: string, label: string): string {
360 + return `↗ \x1b]8;;${url}\x1b\\${label}\x1b]8;;\x1b\\`;
363 +export function renderScene(
364 + state: SceneState,
365 + width: number,
366 + theme: Theme,
367 +): string[] {
368 + const inner = Math.max(width, 12);
369 + const layout = sceneLayout(inner);
370 + const paint = painter(theme);
371 + const lines: string[] = [];
372 + const { tick } = state;
374 + const mascot = MASCOTS[layout];
375 + const mascotWidth = Math.max(...mascot.map((line) => line.length));
376 + const mascotIndent = indentFor(mascotWidth, inner);
377 + const sparkles = SPARKLES[layout].slice(
378 + 0,
379 + Math.max(0, Math.min(SPARKLES[layout].length, Math.floor(tick / 1.5))),
380 + );
381 + for (const [row, art] of mascot.entries()) {
382 + const age = tick - row;
383 + if (age < 0) break;
384 + let line = mascotRow(art, age);
385 + for (const sparkle of sparkles.filter((entry) => entry.row === row)) {
386 + line = placeGlyph(
387 + line,
388 + sparkle.col,
389 + TWINKLE[(tick + sparkle.col) % TWINKLE.length],
390 + );
392 + lines.push(place(paint.ramp(line, row * 0.6), mascotIndent, inner));
394 + if (tick >= mascot.length) {
395 + const groundWidth = Math.min(mascotWidth + 2, inner);
396 + lines.push(
397 + place(
398 + paint.color("dim", "▂".repeat(groundWidth)),
399 + indentFor(groundWidth, inner),
400 + inner,
401 + ),
402 + );
405 + const title = TITLES[layout];
406 + if (tick >= TITLE_START) {
407 + lines.push(
408 + "",
409 + place(
410 + paint.sweep(reveal(title, (tick - TITLE_START) * 5), tick),
411 + indentFor(visibleWidth(title), inner),
412 + inner,
413 + ),
414 + );
417 + const form = sceneFormLines(state, layout);
418 + const formWidth = Math.min(
419 + Math.max(...form.map((line) => visibleWidth(line))),
420 + inner,
421 + );
422 + const formIndent = indentFor(formWidth, inner);
423 + if (tick >= FORM_START) {
424 + lines.push("");
425 + for (const [index, text] of form.entries()) {
426 + const age = tick - FORM_START - index * FORM_TICKS_PER_ROW;
427 + if (age < 0) break;
428 + const isStatus = index === form.length - 1;
429 + const color: ThemeColor = isStatus ? "accent" : "toolOutput";
430 + for (const line of revealBlock(text, age * 14, formWidth))
431 + lines.push(place(paint.color(color, line), formIndent, inner));
435 + // The link and the code field are live from the first frame: the intro
436 + // animation plays above them, it never gates the flow.
437 + if (state.phase === "signin") {
438 + const linkLines = state.hyperlinks
439 + ? [hyperlinkLine(state.url, LINK_LABEL)]
440 + : wrapTextWithAnsi(state.url, inner);
441 + const linkWidth = state.hyperlinks
442 + ? visibleWidth(`↗ ${LINK_LABEL}`)
443 + : Math.min(Math.max(...linkLines.map(visibleWidth)), inner);
444 + const linkIndent = indentFor(linkWidth, inner);
445 + lines.push("");
446 + for (const line of linkLines)
447 + lines.push(place(paint.color("accent", line), linkIndent, inner));
448 + if (state.clipboard !== "idle")
449 + lines.push(
450 + place(
451 + state.clipboard === "copied"
452 + ? paint.color("success", "✔ Link copied to clipboard.")
453 + : paint.color("warning", "⚠ No clipboard tool found."),
454 + linkIndent,
455 + inner,
456 + ),
457 + );
460 + // The code field is aligned with the form block, not with the terminal edge.
461 + if (state.input.length > 0) {
462 + lines.push(
463 + "",
464 + ...state.input.map((line) => place(line, formIndent, inner)),
465 + );
468 + const outcome = state.phase === "approved" || state.phase === "denied";
469 + if (outcome) {
470 + const stamp =
471 + STAMPS[layout][state.phase === "approved" ? "approved" : "denied"];
472 + const stampIndent = indentFor(visibleWidth(stamp[0]), inner);
473 + const shake = state.phaseTick < 2 ? " " : state.phaseTick < 3 ? " " : "";
474 + lines.push("");
475 + for (const row of stamp)
476 + lines.push(
477 + place(
478 + state.phaseTick < 2
479 + ? paint.color("dim", row)
480 + : state.phase === "approved"
481 + ? paint.ramp(row, 0)
482 + : paint.color("error", row),
483 + `${stampIndent}${shake}`,
484 + inner,
485 + ),
486 + );
488 + const verdict = sceneVerdictLines(state, layout);
489 + if (verdict.length > 0 && state.phaseTick >= STAMP_TICKS) {
490 + const verdictWidth = Math.min(
491 + Math.max(...verdict.map((line) => visibleWidth(line))),
492 + inner,
493 + );
494 + const verdictIndent = indentFor(verdictWidth, inner);
495 + lines.push("");
496 + for (const [index, text] of verdict.entries()) {
497 + const age =
498 + state.phaseTick - STAMP_TICKS - index * VERDICT_TICKS_PER_LINE;
499 + if (age < 0) break;
500 + const color: ThemeColor =
501 + state.phase === "denied"
502 + ? "error"
503 + : index === 0
504 + ? "dim"
505 + : state.tokenCopied
506 + ? "success"
507 + : "warning";
508 + for (const line of revealBlock(text, age * 16, verdictWidth))
509 + lines.push(place(paint.color(color, line), verdictIndent, inner));
514 + if (state.hints) {
515 + lines.push(
516 + "",
517 + place(
518 + paint.color("dim", state.hints),
519 + indentFor(visibleWidth(state.hints), inner),
520 + inner,
521 + ),
522 + );
525 + return lines;

extensions/klaus/src/setup-token.ts

Added
new file mode 100644
1 +import { spawn } from "node:child_process";
2 +import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3 +import { getCapabilities, Input } from "@earendil-works/pi-tui";
4 +import { dbg } from "./debug.js";
5 +import {
6 + type ClipboardState,
7 + renderScene,
8 + SCENE_INTRO_TICKS,
9 + SCENE_TICK_MS,
10 + type ScenePhase,
11 + type SceneState,
12 + sceneOutcomeTicks,
13 +} from "./setup-scene.js";
15 +// Same public client as Claude Code and Pi's own Anthropic OAuth flow.
16 +const CLIENT_ID = atob("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
17 +export const AUTHORIZE_URL = "https://claude.com/cai/oauth/authorize";
18 +export const TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
19 +export const REDIRECT_URI = "https://platform.claude.com/oauth/code/callback";
20 +const SCOPE = "user:inference";
21 +export const EXPIRES_IN_SECONDS = 365 * 24 * 60 * 60;
23 +export type Pkce = { verifier: string; challenge: string; state: string };
25 +function base64url(bytes: Uint8Array): string {
26 + return Buffer.from(bytes).toString("base64url");
29 +export async function generatePkce(): Promise<Pkce> {
30 + const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
31 + const digest = await crypto.subtle.digest(
32 + "SHA-256",
33 + new TextEncoder().encode(verifier),
34 + );
35 + return {
36 + verifier,
37 + challenge: base64url(new Uint8Array(digest)),
38 + state: base64url(crypto.getRandomValues(new Uint8Array(32))),
39 + };
42 +export function buildAuthorizeUrl(pkce: Pkce): string {
43 + const params = new URLSearchParams({
44 + code: "true",
45 + client_id: CLIENT_ID,
46 + response_type: "code",
47 + redirect_uri: REDIRECT_URI,
48 + scope: SCOPE,
49 + code_challenge: pkce.challenge,
50 + code_challenge_method: "S256",
51 + state: pkce.state,
52 + });
53 + return `${AUTHORIZE_URL}?${params}`;
56 +export type ParsedAuthorization = { code: string; state?: string };
58 +/** Accepts the callback page's `code#state`, a redirect URL, a query string, or a bare code. */
59 +export function parseAuthorizationInput(
60 + input: string,
61 +): ParsedAuthorization | undefined {
62 + const value = input.trim();
63 + if (!value) return undefined;
64 + try {
65 + const url = new URL(value);
66 + const code = url.searchParams.get("code");
67 + return code
68 + ? { code, state: url.searchParams.get("state") ?? undefined }
69 + : undefined;
70 + } catch {}
71 + if (value.includes("#")) {
72 + const [code, state] = value.split("#", 2);
73 + return code ? { code, state: state || undefined } : undefined;
74 + }
75 + if (value.includes("code=")) {
76 + const params = new URLSearchParams(value);
77 + const code = params.get("code");
78 + return code ? { code, state: params.get("state") ?? undefined } : undefined;
79 + }
80 + return { code: value };
83 +export type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
85 +export type MintedToken = { token: string; expiresInSeconds?: number };
87 +export async function exchangeCode(
88 + parsed: ParsedAuthorization,
89 + pkce: Pkce,
90 + fetchFn: FetchLike = fetch,
91 +): Promise<MintedToken> {
92 + if (parsed.state && parsed.state !== pkce.state)
93 + throw new Error("OAuth state mismatch; start over.");
94 + dbg?.("setupToken.exchange.start");
95 + const response = await fetchFn(TOKEN_URL, {
96 + method: "POST",
97 + headers: { "Content-Type": "application/json", Accept: "application/json" },
98 + body: JSON.stringify({
99 + grant_type: "authorization_code",
100 + code: parsed.code,
101 + redirect_uri: REDIRECT_URI,
102 + client_id: CLIENT_ID,
103 + code_verifier: pkce.verifier,
104 + state: pkce.state,
105 + expires_in: EXPIRES_IN_SECONDS,
106 + }),
107 + signal: AbortSignal.timeout(30_000),
108 + });
109 + const body = await response.text();
110 + dbg?.("setupToken.exchange.response", { status: response.status });
111 + if (!response.ok) {
112 + throw new Error(
113 + response.status === 401
114 + ? "Anthropic rejected the authorization code."
115 + : `Token exchange failed (${response.status}): ${body.slice(0, 200)}`,
116 + );
118 + let data: { access_token?: unknown; expires_in?: unknown };
119 + try {
120 + data = JSON.parse(body) as typeof data;
121 + } catch {
122 + throw new Error("Token exchange returned invalid JSON.");
124 + if (typeof data.access_token !== "string" || !data.access_token)
125 + throw new Error("Token exchange returned no access token.");
126 + return {
127 + token: data.access_token,
128 + expiresInSeconds:
129 + typeof data.expires_in === "number" ? data.expires_in : undefined,
130 + };
133 +export function clipboardCandidates(
134 + platform: NodeJS.Platform = process.platform,
135 +): string[][] {
136 + switch (platform) {
137 + case "darwin":
138 + return [["pbcopy"]];
139 + case "win32":
140 + return [["clip"]];
141 + case "android":
142 + return [["termux-clipboard-set"]];
143 + default:
144 + return [
145 + ["wl-copy"],
146 + ["xclip", "-selection", "clipboard"],
147 + ["xsel", "--clipboard", "--input"],
148 + ];
152 +export type ClipboardRunner = (
153 + command: string[],
154 + text: string,
155 +) => Promise<boolean>;
157 +export async function copyToClipboard(
158 + text: string,
159 + run: ClipboardRunner,
160 + platform: NodeJS.Platform = process.platform,
161 +): Promise<boolean> {
162 + for (const command of clipboardCandidates(platform)) {
163 + if (await run(command, text)) return true;
165 + return false;
168 +export function defaultRunner(
169 + command: string[],
170 + text: string,
171 +): Promise<boolean> {
172 + return new Promise((resolve) => {
173 + const child = spawn(command[0] ?? "", command.slice(1), {
174 + stdio: ["pipe", "ignore", "ignore"],
175 + });
176 + child.on("error", () => resolve(false));
177 + child.on("close", (code) => resolve(code === 0));
178 + child.stdin?.on("error", () => resolve(false));
179 + child.stdin?.end(text);
180 + });
183 +export type OpenerCandidate = {
184 + command: string;
185 + args: string[];
186 + windowsHide?: boolean;
189 +export function openerCandidates(
190 + url: string,
191 + options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
192 +): OpenerCandidate[] {
193 + const platform = options.platform ?? process.platform;
194 + const env = options.env ?? process.env;
195 + if (env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }];
196 + if (platform === "darwin") return [{ command: "open", args: [url] }];
197 + if (platform === "win32")
198 + return [
200 + command: "rundll32.exe",
201 + args: ["url.dll,FileProtocolHandler", url],
202 + windowsHide: true,
203 + },
204 + ];
205 + return [
206 + { command: "xdg-open", args: [url] },
207 + { command: "wslview", args: [url] },
208 + { command: "gio", args: ["open", url] },
209 + ];
212 +async function openBrowser(url: string): Promise<boolean> {
213 + if (process.env.NODE_ENV === "test" || process.env.VITEST) return false;
214 + for (const candidate of openerCandidates(url)) {
215 + if (await trySpawn(candidate.command, candidate.args)) return true;
217 + return false;
220 +function trySpawn(command: string, args: string[]): Promise<boolean> {
221 + return new Promise((resolve) => {
222 + const child = spawn(command, args, {
223 + detached: true,
224 + stdio: "ignore",
225 + windowsHide: true,
226 + });
227 + let settled = false;
228 + const done = (ok: boolean) => {
229 + if (settled) return;
230 + settled = true;
231 + resolve(ok);
232 + };
233 + child.on("error", () => done(false));
234 + child.on("spawn", () => {
235 + child.unref();
236 + done(true);
237 + });
238 + child.on("close", (code) => done(code === 0));
239 + });
242 +function fail(message: string): string {
243 + return `Klaus could not collect a token: ${message}`;
246 +export type SetupTokenDeps = {
247 + pkce?: () => Promise<Pkce>;
248 + fetchFn?: FetchLike;
249 + copy?: typeof copyToClipboard;
250 + run?: ClipboardRunner;
251 + openUrl?: (url: string) => Promise<boolean>;
254 +let inFlight = false;
256 +export async function runSetupTokenCommand(
257 + ctx: ExtensionContext,
258 + deps: SetupTokenDeps = {},
259 +): Promise<void> {
260 + if (!ctx.hasUI) return;
261 + if (inFlight) {
262 + ctx.ui.notify("Klaus is already minting a token.", "warning");
263 + return;
265 + inFlight = true;
266 + dbg?.("setupToken.command.start", { mode: ctx.mode });
267 + try {
268 + if (ctx.mode === "tui") {
269 + await runCounterScene(ctx, deps);
270 + return;
272 + await runDialogFlow(ctx, deps);
273 + } finally {
274 + inFlight = false;
278 +/** RPC and other UI hosts without a TUI: plain dialogs, no scene. */
279 +async function runDialogFlow(
280 + ctx: ExtensionContext,
281 + deps: SetupTokenDeps,
282 +): Promise<void> {
283 + const pkce = await (deps.pkce ?? generatePkce)();
284 + const url = buildAuthorizeUrl(pkce);
285 + const answer = await ctx.ui.input(
286 + `Klaus: sign in at ${url} and paste the code`,
287 + "code#state",
288 + );
289 + const parsed =
290 + answer === undefined ? undefined : parseAuthorizationInput(answer);
291 + if (!parsed) {
292 + dbg?.("setupToken.command.cancelled");
293 + ctx.ui.notify("Klaus: application withdrawn.", "info");
294 + return;
296 + ctx.ui.setStatus("klaus", "minting token…");
297 + let minted: MintedToken;
298 + try {
299 + minted = await exchangeCode(parsed, pkce, deps.fetchFn);
300 + } catch (error) {
301 + ctx.ui.notify(
302 + fail(error instanceof Error ? error.message : String(error)),
303 + "error",
304 + );
305 + return;
306 + } finally {
307 + ctx.ui.setStatus("klaus", undefined);
309 + const copied = await (deps.copy ?? copyToClipboard)(
310 + minted.token,
311 + deps.run ?? defaultRunner,
312 + );
313 + dbg?.("setupToken.command.minted", { copied });
314 + ctx.ui.notify(
315 + copied ? "Token in clipboard." : `No clipboard. Token: ${minted.token}`,
316 + copied ? "info" : "warning",
317 + );
320 +/**
321 + * TUI: one focused component owns the whole visit, from filing the application
322 + * through the sign-in code to the stamp, so the animation frames the flow
323 + * instead of interrupting it.
324 + */
325 +async function runCounterScene(
326 + ctx: ExtensionContext,
327 + deps: SetupTokenDeps,
328 +): Promise<void> {
329 + let pkce = await (deps.pkce ?? generatePkce)();
330 + let url = buildAuthorizeUrl(pkce);
331 + void (deps.openUrl ?? openBrowser)(url);
333 + const outcome = await ctx.ui.custom<"cancelled" | "closed">(
334 + (tui, theme, keybindings, done) => {
335 + const field = new Input({
336 + prompt: "Code: ",
337 + placeholder: "code#state",
338 + placeholderStyle: (text) => theme.fg("dim", text),
339 + });
340 + field.focused = true;
341 + let tick = 0;
342 + let phaseTick = 0;
343 + let phase: ScenePhase = "signin";
344 + let clipboard: ClipboardState = "idle";
345 + let token: string | undefined;
346 + let tokenCopied = false;
347 + let expiresInSeconds: number | undefined;
348 + let failure: string | undefined;
349 + let settled = false;
350 + let timer: NodeJS.Timeout | undefined;
351 + let interval = 0;
353 + const outcomeTicks = () => sceneOutcomeTicks(sceneState([], ""));
354 + const outcomeSettled = () =>
355 + (phase === "approved" || phase === "denied") &&
356 + phaseTick >= outcomeTicks();
358 + function sceneState(input: string[], hints: string): SceneState {
359 + return {
360 + tick,
361 + phaseTick,
362 + phase,
363 + input,
364 + hyperlinks: getCapabilities().hyperlinks,
365 + url,
366 + clipboard,
367 + hints,
368 + token,
369 + tokenCopied,
370 + expiresInSeconds,
371 + error: failure,
372 + };
375 + function hints(): string {
376 + if (phase === "signin")
377 + return [
378 + "enter submit",
379 + field.getValue() === "" ? "c copy link" : "",
380 + "esc cancel",
382 + .filter(Boolean)
383 + .join(" · ");
384 + if (phase === "exchanging") return "esc cancel";
385 + if (!outcomeSettled()) return "any key to skip";
386 + return phase === "denied" ? "r retry · esc close" : "any key to close";
389 + /** Fast during animation, slow while the human is signing in, off when static. */
390 + function schedule(): void {
391 + const desired =
392 + tick < SCENE_INTRO_TICKS
393 + ? SCENE_TICK_MS
394 + : phase === "exchanging"
395 + ? 90
396 + : phase === "signin"
397 + ? 400
398 + : outcomeSettled()
399 + ? 0
400 + : SCENE_TICK_MS;
401 + if (desired === interval) return;
402 + interval = desired;
403 + if (timer) clearInterval(timer);
404 + timer = undefined;
405 + if (desired === 0) return;
406 + timer = setInterval(() => {
407 + tick++;
408 + phaseTick++;
409 + schedule();
410 + tui.requestRender();
411 + }, desired);
412 + timer.unref?.();
415 + function stop(): void {
416 + if (timer) clearInterval(timer);
417 + timer = undefined;
418 + interval = 0;
421 + function finish(result: "cancelled" | "closed"): void {
422 + if (settled) return;
423 + settled = true;
424 + stop();
425 + done(result);
428 + function enterPhase(next: ScenePhase): void {
429 + phase = next;
430 + phaseTick = 0;
431 + schedule();
432 + tui.requestRender();
435 + async function submit(value: string): Promise<void> {
436 + const parsed = parseAuthorizationInput(value);
437 + if (!parsed) return;
438 + enterPhase("exchanging");
439 + try {
440 + const minted = await exchangeCode(parsed, pkce, deps.fetchFn);
441 + token = minted.token;
442 + expiresInSeconds = minted.expiresInSeconds;
443 + tokenCopied = await (deps.copy ?? copyToClipboard)(
444 + minted.token,
445 + deps.run ?? defaultRunner,
446 + );
447 + dbg?.("setupToken.command.minted", { copied: tokenCopied });
448 + enterPhase("approved");
449 + } catch (error) {
450 + failure = error instanceof Error ? error.message : String(error);
451 + dbg?.("setupToken.command.denied", { error: failure });
452 + enterPhase("denied");
456 + async function retry(): Promise<void> {
457 + pkce = await (deps.pkce ?? generatePkce)();
458 + url = buildAuthorizeUrl(pkce);
459 + failure = undefined;
460 + clipboard = "idle";
461 + field.setValue("");
462 + void (deps.openUrl ?? openBrowser)(url);
463 + enterPhase("signin");
466 + function copyLink(): void {
467 + void (deps.copy ?? copyToClipboard)(
468 + url,
469 + deps.run ?? defaultRunner,
470 + ).then((ok) => {
471 + clipboard = ok ? "copied" : "failed";
472 + tui.requestRender();
473 + });
476 + field.onSubmit = (value) => {
477 + if (value.trim()) void submit(value);
478 + };
479 + field.onEscape = () => finish("cancelled");
480 + schedule();
482 + return {
483 + render(width: number) {
484 + // Leave room for the centering indent the scene adds around the form block.
485 + const input =
486 + phase === "signin"
487 + ? field.render(Math.max(Math.min(width, 52), 12))
488 + : [];
489 + return renderScene(sceneState(input, hints()), width, theme);
490 + },
491 + invalidate() {
492 + field.invalidate();
493 + },
494 + handleInput(data: string) {
495 + const cancel =
496 + keybindings.matches(data, "app.interrupt") ||
497 + keybindings.matches(data, "tui.select.cancel");
498 + if (phase === "signin") {
499 + if (cancel) {
500 + finish("cancelled");
501 + return;
503 + if (data === "c" && field.getValue() === "") {
504 + copyLink();
505 + return;
507 + field.handleInput(data);
508 + schedule();
509 + tui.requestRender();
510 + return;
512 + if (phase === "exchanging") {
513 + if (cancel) finish("cancelled");
514 + return;
516 + if (!outcomeSettled()) {
517 + phaseTick = outcomeTicks();
518 + schedule();
519 + tui.requestRender();
520 + return;
522 + if (phase === "denied" && data === "r") {
523 + void retry();
524 + return;
526 + finish("closed");
527 + },
528 + dispose() {
529 + stop();
530 + },
531 + };
532 + },
533 + );
535 + if (outcome === "cancelled") {
536 + dbg?.("setupToken.command.cancelled");
537 + ctx.ui.notify("Klaus: application withdrawn.", "info");

extensions/quota/README.md

Modified
31 31 Supports Anthropic, OpenAI Codex, GitHub Copilot, Gemini CLI, MiniMax, MiniMax
32 32 CN, Zai, and Kimi.
33 +Klaus maps to the Anthropic subscription quota through Pi's Anthropic OAuth
34 +token.
34 36 Only the active model provider is fetched.
35 37 Provider auth is read through Pi model registry auth storage.

extensions/quota/index.ts

Modified
458 458 const PROVIDERS: Record<string, string> = {
459 459 anthropic: "Anthropic",
460 + klaus: "Anthropic",
460 461 "openai-codex": "OpenAI Codex",
461 462 "github-copilot": "GitHub Copilot",
462 463 "google-gemini-cli": "Gemini",
512 513 : undefined;
515 + if (key === "klaus") {
516 + // Klaus streams the Claude subscription through Pi's Anthropic OAuth
517 + // token, so its quota is the Anthropic subscription quota.
518 + const apiKey = await ctx.modelRegistry.getApiKeyForProvider("anthropic");
519 + return apiKey
520 + ? keepCached("Anthropic", async () =>
521 + parseAnthropic(await fetchAnthropic(apiKey)),
523 + : undefined;
514 525 if (key === "github-copilot") {
515 526 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
516 527 return apiKey

extensions/usage/README.md

Modified
25 25 - Parses assistant messages with `usage`, `provider`, and `model` fields.
26 26 - Aggregates sessions, messages, cost, tokens, input, output, and cache by
27 27 provider and model.
28 +- Renders the `klaus` provider as `anthropic (klaus)` because it carries the
29 + Claude subscription traffic.
28 30 - Period tabs:
29 31 Today, This Week, Last Week, All Time.
30 32 - Table keys:

extensions/usage/implementation.ts

Modified
78 78 timestamp: number;
81 +// Claude subscription traffic is stamped with the klaus provider id in session
82 +// files; surface it under its anthropic identity instead.
83 +const PROVIDER_LABELS: Record<string, string> = {
84 + klaus: "anthropic (klaus)",
85 +};
81 87 interface ParsedSession {
82 88 sessionId: string;
83 89 messages: ParsedMessage[];
308 314 (msg.timestamp as number) || (Number.isNaN(fallbackTs) ? 0 : fallbackTs);
310 316 return {
311 - provider: msg.provider as string,
317 + provider:
318 + PROVIDER_LABELS[msg.provider as string] ?? (msg.provider as string),
312 319 model: msg.model as string,
314 321 input,