xonecas.io
64875
Mc

mini-coder / commit e667764

feat: add /login command, fix API key passthrough to streamSimple

/login: overlay Select lists OAuth providers with login status.
Selecting a provider runs the browser-based OAuth flow via pi-ai.
Credentials persisted, provider registered, model auto-selected.
Manual code input not supported (onPrompt rejects).

fix: pass apiKey from state.providers through RunAgentOpts to
streamSimple options. Previously OAuth providers failed with
'No API key for provider' because only env vars were checked.

xonecas2026-04-05 e667764b1fd285ffd8e63df144dd5aa93c96b16b parent e3879f9

3 files changed

TODO.md+1−0
@@ -134,6 +134,7 @@
134134 **Bugs / missing behavior:**
135135
136136 - `agent.ts` never passes `reasoning` (effort level) to `streamSimple()`. The `/effort` command updates `state.effort` but it has no effect on the LLM call. `RunAgentOpts` needs an `effort` field, and the `streamSimple` call needs `{ signal, reasoning: effort }`.
137+- Assistant messages not visibly streaming — text appears as full blocks instead of incrementally, causing jarring scroll jumps. Likely a rendering or event issue in `ui.ts` streaming path.
137138 - Shell tool rendering doesn't show exit code (spec: "Shows the command, head + tail truncated output with a visual marker, and exit code"). `ToolExecResult` carries `isError` but not the numeric exit code.
138139 - Status bar CWD truncation from the left (`…/mini-coder`) on narrow terminals — not implemented, just shows full abbreviated path.
139140 - `Ctrl+Z` suspend/background — not implemented (spec lists it in key bindings).
src/agent.ts+4−0
@@ -70,6 +70,8 @@ export interface RunAgentOpts {
7070 messages: Message[];
7171 /** Working directory for tool execution. */
7272 cwd: string;
73+ /** API key for the provider. */
74+ apiKey?: string;
7375 /** Reasoning effort level (e.g. "low", "medium", "high", "xhigh"). */
7476 effort?: ThinkingLevel;
7577 /** Abort signal for interruption. */
@@ -114,6 +116,7 @@ export async function runAgentLoop(
114116 toolHandlers,
115117 messages,
116118 cwd,
119+ apiKey,
117120 effort,
118121 signal,
119122 onEvent,
@@ -128,6 +131,7 @@ export async function runAgentLoop(
128131
129132 // Stream to LLM
130133 const streamOpts = {
134+ ...(apiKey ? { apiKey } : {}),
131135 ...(effort ? { reasoning: effort } : {}),
132136 ...(signal ? { signal } : {}),
133137 };
src/ui.ts+119−1
@@ -8,7 +8,8 @@
88 * @module
99 */
1010
11-import { homedir } from "node:os";
11+import { exec } from "node:child_process";
12+import { homedir, platform } from "node:os";
1213 import type { SelectInstance } from "@cel-tui/components";
1314 import { Divider, Markdown, Select, Spacer } from "@cel-tui/components";
1415 import {
@@ -28,6 +29,8 @@ import type {
2829 ThinkingLevel,
2930 ToolCall,
3031 } from "@mariozechner/pi-ai";
32+import type { OAuthProviderInterface } from "@mariozechner/pi-ai/oauth";
33+import { getOAuthProviders } from "@mariozechner/pi-ai/oauth";
3134 import { structuredPatch } from "diff";
3235 import type { AgentEvent } from "./agent.ts";
3336 import { runAgentLoop } from "./agent.ts";
@@ -37,6 +40,7 @@ import {
3740 buildPrompt,
3841 buildToolList,
3942 getAvailableModels,
43+ saveOAuthCredentials,
4044 shutdown,
4145 } from "./index.ts";
4246 import { parseInput } from "./input.ts";
@@ -741,6 +745,114 @@ function formatSessionDate(date: Date): string {
741745 return date.toLocaleDateString();
742746 }
743747
748+/** Open a URL in the user's default browser. */
749+function openInBrowser(url: string): void {
750+ const cmd = platform() === "darwin" ? "open" : "xdg-open";
751+ exec(`${cmd} ${JSON.stringify(url)}`);
752+}
753+
754+/**
755+ * Append a system info line to the conversation log.
756+ *
757+ * Used for login progress/status messages that aren't part of the
758+ * agent conversation. Rendered as dimmed italic text.
759+ */
760+function appendInfoMessage(text: string, state: AppState): void {
761+ const msg: Message = {
762+ role: "user",
763+ content: `[${text}]`,
764+ timestamp: Date.now(),
765+ };
766+ state.messages.push(msg);
767+ stickToBottom = true;
768+ cel.render();
769+}
770+
771+/** Handle the /login command: OAuth provider login. */
772+function handleLoginCommand(state: AppState): void {
773+ const oauthProviders = getOAuthProviders();
774+ if (oauthProviders.length === 0) {
775+ return;
776+ }
777+
778+ const items = oauthProviders.map((p) => {
779+ const loggedIn = state.oauthCredentials[p.id] != null;
780+ const status = loggedIn ? " (logged in)" : "";
781+ return {
782+ label: `${p.name}${status}`,
783+ value: p.id,
784+ filterText: p.name,
785+ };
786+ });
787+
788+ const select = Select({
789+ items,
790+ maxVisible: OVERLAY_MAX_VISIBLE,
791+ placeholder: "type to filter providers...",
792+ focused: true,
793+ highlightColor: "color06",
794+ onSelect: (providerId) => {
795+ dismissOverlay();
796+ const provider = oauthProviders.find((p) => p.id === providerId);
797+ if (provider) {
798+ performLogin(provider, state).catch((err) => {
799+ appendInfoMessage(
800+ `Login failed: ${err instanceof Error ? err.message : String(err)}`,
801+ state,
802+ );
803+ });
804+ }
805+ },
806+ onBlur: dismissOverlay,
807+ });
808+
809+ inputFocused = false;
810+ activeOverlay = { select, title: "Login to a provider" };
811+ cel.render();
812+}
813+
814+/** Run the OAuth login flow for a provider. */
815+async function performLogin(
816+ provider: OAuthProviderInterface,
817+ state: AppState,
818+): Promise<void> {
819+ appendInfoMessage(`Logging in to ${provider.name}...`, state);
820+
821+ const credentials = await provider.login({
822+ onAuth: (info) => {
823+ openInBrowser(info.url);
824+ appendInfoMessage(
825+ info.instructions ?? "Opening browser for login...",
826+ state,
827+ );
828+ },
829+ onPrompt: () => {
830+ return Promise.reject(new Error("Manual code input is not supported."));
831+ },
832+ onProgress: (message) => {
833+ appendInfoMessage(message, state);
834+ },
835+ });
836+
837+ // Persist credentials
838+ state.oauthCredentials[provider.id] = credentials;
839+ saveOAuthCredentials(state.oauthCredentials);
840+
841+ // Register the provider's API key
842+ const apiKey = provider.getApiKey(credentials);
843+ state.providers.set(provider.id, apiKey);
844+
845+ // Auto-select model if none was set
846+ if (!state.model) {
847+ const models = getAvailableModels(state);
848+ if (models.length > 0) {
849+ state.model = models[0]!;
850+ }
851+ }
852+
853+ appendInfoMessage(`Logged in to ${provider.name}.`, state);
854+}
855+
744856 /** Dispatch a parsed command. Returns true if handled. */
745857 function handleCommand(command: string, state: AppState): boolean {
746858 switch (command) {
@@ -753,6 +865,9 @@ function handleCommand(command: string, state: AppState): boolean {
753865 case "session":
754866 handleSessionCommand(state);
755867 return true;
868+ case "login":
869+ handleLoginCommand(state);
870+ return true;
756871 default:
757872 return false;
758873 }
@@ -826,6 +941,9 @@ async function submitMessage(text: string, state: AppState): Promise<void> {
826941 toolHandlers,
827942 messages: state.messages,
828943 cwd: state.cwd,
944+ apiKey: state.model
945+ ? state.providers.get(state.model.provider)
946+ : undefined,
829947 effort: state.effort,
830948 signal: state.abortController.signal,
831949 onEvent: (event) => handleAgentEvent(event, state),