xonecas.io
64875
Mc

mini-coder / commit 9a0dcab

chore: docs cleanup

xonecas2026-02-20 9a0dcab324e0746769ce5636d33bd4175003f5c2 parent 212f231

4 files changed

PLAN.md+0−200
@@ -1,200 +0,0 @@
1-# mini-coder — Implementation Plan
2-
3-A small, fast CLI coding agent built with Bun.js. Focused on developer flow,
4-elegant output, and a reliable core feature set.
5-
6----
7-
8-## Setup
9-
10-- Runtime: Bun.js
11-- Language: TypeScript (strict mode)
12-- Binary: `mc` (globally installable via `bun install -g .`)
13-- Config + sessions: `~/.config/mini-coder/`
14-
15----
16-
17-## Dependencies
18-
19-```
20-ai # AI SDK v6 core
21-@ai-sdk/anthropic # Claude via Zen or direct
22-@ai-sdk/openai # GPT via Zen or direct
23-@ai-sdk/google # Gemini via Zen or direct
24-@ai-sdk/openai-compatible # MiniMax, GLM, Kimi via Zen
25-ollama-ai-provider # Local Ollama
26-yoctocolors # ANSI colors (16-color safe, inherits terminal theme)
27-zod # Tool input schemas
28-```
29-
30----
31-
32-## Provider Strategy
33-
34-Uses the correct AI SDK package per endpoint type, following the OpenCode Zen docs:
35-
36-| Provider | Package | Endpoint / Notes |
37-| ------------------------------- | -------------------------- | --------------------------------------------- |
38-| OpenCode Zen — Anthropic models | `@ai-sdk/anthropic` | `https://opencode.ai/zen/v1/messages` |
39-| OpenCode Zen — OpenAI models | `@ai-sdk/openai` | `https://opencode.ai/zen/v1/responses` |
40-| OpenCode Zen — Google models | `@ai-sdk/google` | `https://opencode.ai/zen/v1/models/<model>` |
41-| OpenCode Zen — OpenAI-compat | `@ai-sdk/openai-compatible`| `https://opencode.ai/zen/v1/chat/completions` |
42-| Ollama (local) | `ollama-ai-provider` | `http://localhost:11434` (auto-discovered) |
43-
44-### ENV Auto-discovery
45-
46-| ENV var | Effect |
47-| ------------------ | ----------------------------------------- |
48-| `OPENCODE_API_KEY` | Enables OpenCode Zen provider |
49-| `OLLAMA_BASE_URL` | Override Ollama URL (default: localhost) |
50-
51----
52-
53-## Module Architecture
54-
55-```
56-src/
57- index.ts # Entry point — CLI args, wires agent + session
58- cli/
59- input.ts # Raw-mode stdin reader
60- # - Line editing (left/right/backspace/ctrl-keys)
61- # - History (up/down arrows, SQLite-backed)
62- # - @ prefix → file reference autocomplete
63- # - ! prefix → shell passthrough
64- output.ts # ANSI rendering
65- # - Streaming text with cursor animation
66- # - Tool call display (glob/grep/read → formatted args)
67- # - Edit tool → unified diff output
68- # - Shell tool → command + output block
69- # - Status bar: model/provider/cwd/git branch/tokens
70- commands.ts # Slash command registry + handlers
71- # - /model → pick model from connected providers
72- # - /plan → toggle read-only plan mode
73- # - /mcp → list/add/remove MCP servers
74- # - /review → subagent code review
75- llm-api/
76- providers.ts # Provider factory
77- # - ENV-based auto-discovery
78- # - Returns LanguageModel for a given model ID string
79- # - Supports "zen/claude-sonnet-4-6", "ollama/llama3", etc.
80- turn.ts # Single conversation turn
81- # - streamText with tool loop (maxSteps)
82- # - Yields streaming events: text delta, tool call, tool result
83- # - Returns complete turn: messages + usage stats
84- types.ts # Shared types: Message, Turn, ToolCall, ProviderConfig
85- agent/
86- agent.ts # Main agent REPL loop
87- # - Reads input → calls turn → renders output → repeat
88- # - Manages conversation history in memory + persists to DB
89- # - Handles /plan mode (no tool execution)
90- # - Abort on Ctrl+C mid-turn
91- tools.ts # Tool registry + hook system
92- # - Registers all built-in tools
93- # - Runs post-tool hooks (e.g. auto-format after edit)
94- tools/
95- glob.ts # Glob pattern file discovery
96- grep.ts # Regex content search across files
97- read.ts # File read (with line range support)
98- edit.ts # File edit — exact string replacement (old → new)
99- shell.ts # Shell command execution with streaming stdout/stderr
100- subagent.ts # Spawn a nested mini-coder agent instance
101- mcp/
102- client.ts # MCP server connection (stdio + HTTP transports)
103- manager.ts # Add/remove/list MCP servers, persist to config
104- session/
105- db.ts # bun:sqlite schema + query helpers
106- # - sessions table: id, title, cwd, created_at, updated_at
107- # - messages table: id, session_id, role, content, created_at
108- # - prompt_history table: id, text, created_at
109- manager.ts # new / resume / list session operations
110-```
111-
112----
113-
114-## Build Phases
115-
116-### Phase 1 — Foundation
117-
118-- [ ] `bun init` — project setup, `package.json`, `tsconfig.json`, `.gitignore`
119-- [ ] `session/db.ts` — SQLite schema and CRUD helpers
120-- [ ] `llm-api/types.ts` — shared type definitions
121-- [ ] `llm-api/providers.ts` — ENV-based provider factory
122-- [ ] `llm-api/turn.ts` — streaming turn with tool loop
123-
124-### Phase 2 — Tools
125-
126-- [ ] `tools/glob.ts` — glob file search
127-- [ ] `tools/grep.ts` — regex content search
128-- [ ] `tools/read.ts` — file read
129-- [ ] `tools/edit.ts` — file edit (string replace)
130-- [ ] `tools/shell.ts` — shell execution
131-- [ ] `tools/subagent.ts` — nested agent
132-
133-### Phase 3 — CLI
134-
135-- [ ] `cli/input.ts` — raw-mode line editor with history, `@`, `!`
136-- [ ] `cli/output.ts` — ANSI output, tool rendering, diffs, status bar
137-- [ ] `cli/commands.ts` — slash command handlers
138-
139-### Phase 4 — Agent Loop
140-
141-- [ ] `agent/tools.ts` — tool registry and hook system
142-- [ ] `agent/agent.ts` — main REPL loop
143-- [ ] `session/manager.ts` — session new/resume/list
144-- [ ] `src/index.ts` — entry point, CLI args (--new, --resume, --list)
145-
146-### Phase 5 — MCP
147-
148-- [ ] `mcp/client.ts` — MCP client (stdio + HTTP)
149-- [ ] `mcp/manager.ts` — `/mcp` command integration
150-
151----
152-
153-## UI Design Notes
154-
155-- Use only the 16 ANSI colors — colors inherit from the user's terminal theme
156-- No heavy box-drawing unless it reads well in monospace
157-- Status bar (always visible below input):
158- `[model] [provider] [cwd] [git-branch] [ctx%] [↑tokens ↓tokens]`
159-- Tool call output format:
160- - `glob "**/*.ts"` → compact tree of matched paths
161- - `read src/foo.ts:10-30` → file + line range
162- - `edit src/foo.ts` → unified diff (- old / + new)
163- - `shell git status` → command + scrollable output block
164-- Prompt animation: simple spinner (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏) while LLM is running
165-
166----
167-
168-## Configuration Schema
169-
170-`~/.config/mini-coder/config.json`:
171-
172-```json
173-{
174- "defaultModel": "zen/claude-sonnet-4-6",
175- "providers": {
176- "zen": { "apiKey": "..." },
177- "ollama": { "baseUrl": "http://localhost:11434" }
178- },
179- "mcpServers": [
180- { "name": "exa", "transport": "http", "url": "https://..." }
181- ]
182-}
183-```
184-
185----
186-
187-## Out of Scope for v1
188-
189-- LSP integration
190-- Image / screenshot support
191-- Web search tool
192-
193----
194-
195-## Conventions
196-
197-- Agent skill files: `.agents/` in project dir or `~/.config/mini-coder/agents/`
198- (follows skills.sh convention)
199-- Context files: `AGENTS.md` or `CLAUDE.md` in project root (same as oh-my-pi / opencode)
200-- No mocked/offline tests — integration tests only against real providers
TODO.md+146−3
@@ -4,7 +4,7 @@ Besides undoing the conversation turn, it should restore some snapshot, using gi
44
55 ---
66
7-Subagent needs visibity on the ui somehow... that accounts for multiple in parallel... Needs planning
7+Subagent needs visibity on the ui somehow... that accounts for multiple in parallel... Needs planning, maybe a tree view showing the subagent's tool calls before the output.
88
99 ---
1010
@@ -15,7 +15,7 @@ Subagent needs visibity on the ui somehow... that accounts for multiple in paral
1515
1616 ---
1717
18-# LLMs don't know their cwd:
18+# LLMs don't know their cwd?:
1919
2020 ```
2121 ▶ create a readme file and introduce yourself
@@ -44,9 +44,152 @@ claude-sonnet-4-6 ~/src/mini-coder ↑40.4k ↓125
4444 | Env Var | Default Model |
4545 |---|---|
4646 | `OPENCODE_API_KEY` | `zen/claude-sonnet-4-6` |
47-| `ANTHROPIC_API_KEY` | `anthropic/claude-sonnet-4-5-20250929` |
47+| `ANTHROPIC_API_KEY` | `anthropic/claude-sonnet--5-20250929` |
4848 | `OPENAI_API_KEY` | `openai/gpt-4o` |
4949 | `GOOGLE_API_KEY` / `GEMINI_API_KEY` | `google/gemini-2.0-flash` |
5050 | *(none)* | `ollama/llama3.2` (fallback) |
5151
5252 ---
53+
54+Oauth Open AI support?
55+
56+## How opencode Implements OpenAI (Codex) OAuth Login
57+
58+The implementation is spread across several layers, all in `packages/opencode/src/plugin/codex.ts` as the core, wired together through a plugin/provider-auth system.
59+
60+---
61+
62+### Architecture Overview
63+
64+```
65+UI (dialog-connect-provider.tsx)
66+ ↓ HTTP
67+Server routes (server/routes/provider.ts)
68+ ↓
69+ProviderAuth namespace (provider/auth.ts)
70+ ↓
71+Plugin system (plugin/index.ts)
72+ ↓
73+CodexAuthPlugin (plugin/codex.ts) ← OAuth logic lives here
74+ ↓
75+Auth storage (auth/index.ts) ← Persists tokens to auth.json
76+```
77+
78+---
79+
80+### 1. The Plugin: `plugin/codex.ts`
81+
82+This is the heart of the OpenAI OAuth flow. It registers itself for the `"openai"` provider and exposes **two OAuth methods** plus a fallback API key method:
83+
84+#### Method 1: **Browser-based (PKCE + redirect)**
85+```
86+label: "ChatGPT Pro/Plus (browser)"
87+type: "oauth", method: "auto"
88+```
89+- Spawns a local HTTP server on port `1455` (`http://localhost:1455/auth/callback`) as the OAuth redirect URI
90+- Generates a **PKCE** (`code_verifier` / `code_challenge`) pair using `crypto.subtle.digest("SHA-256")`
91+- Generates a CSRF `state` token
92+- Builds the authorization URL against `https://auth.openai.com/oauth/authorize` with:
93+ - `client_id: "app_EMoamEEZ73f0CkXaXp7hrann"`
94+ - `scope: "openid profile email offline_access"`
95+ - `code_challenge_method: "S256"`
96+ - `codex_cli_simplified_flow: "true"`, `originator: "opencode"`
97+- Returns `method: "auto"` — the UI opens the URL, then polls by awaiting the callback promise
98+- When the browser redirects back, the local server handles `/auth/callback`, validates `state` (CSRF check), then POSTs the code + PKCE verifier to `https://auth.openai.com/oauth/token` to exchange for tokens
99+
100+#### Method 2: **Headless (Device Code flow)**
101+```
102+label: "ChatGPT Pro/Plus (headless)"
103+type: "oauth", method: "auto"
104+```
105+- POSTs to `https://auth.openai.com/api/accounts/deviceauth/usercode` to get a `device_auth_id` and `user_code`
106+- Returns `url: "https://auth.openai.com/codex/device"` and `instructions: "Enter code: <user_code>"`
107+- Polls `https://auth.openai.com/api/accounts/deviceauth/token` until approved, then exchanges the `authorization_code` (plus `code_verifier` returned by the server) at `https://auth.openai.com/oauth/token`
108+
109+#### Method 3: **API Key (manual)**
110+```
111+label: "Manually enter API Key"
112+type: "api"
113+```
114+
115+---
116+
117+### 2. Token Handling
118+
119+After a successful OAuth exchange, the plugin returns:
120+```ts
121+{ type: "success", refresh: "...", access: "...", expires: Date.now() + expires_in * 1000, accountId: "..." }
122+```
123+
124+`accountId` is extracted from the **JWT `id_token`** claims, looking for `chatgpt_account_id` (used to set the `ChatGPT-Account-Id` header for org subscriptions).
125+
126+The `auth.ts` `loader` hook intercepts every API call:
127+- If the **access token is expired**, it silently **refreshes** via `refresh_token` at `https://auth.openai.com/oauth/token`
128+- Strips the dummy `Authorization` header set by the AI SDK
129+- Injects `Authorization: Bearer <access_token>` and optionally `ChatGPT-Account-Id: <accountId>`
130+- **Rewrites the URL** for `/v1/responses` or `/chat/completions` requests to the Codex endpoint: `https://chatgpt.com/backend-api/codex/responses`
131+
132+A special constant `OAUTH_DUMMY_KEY = "opencode-oauth-dummy-key"` is returned as `apiKey` to satisfy the AI SDK's requirement for an API key, while the real auth is handled in the custom `fetch` interceptor.
133+
134+---
135+
136+### 3. Storage: `auth/index.ts`
137+
138+All tokens are persisted to `~/.opencode/auth.json` (mode `0o600`) as a discriminated union:
139+```ts
140+{ type: "oauth", refresh: "...", access: "...", expires: 1234567890, accountId?: "..." }
141+```
142+
143+---
144+
145+### 4. Server Routes: `server/routes/provider.ts`
146+
147+Two HTTP endpoints (via Hono) expose the OAuth flow to the UI:
148+
149+| Endpoint | Purpose |
150+|---|---|
151+| `POST /:providerID/oauth/authorize` | Calls `ProviderAuth.authorize()` → triggers the plugin's `authorize()` → returns `{ url, method, instructions }` |
152+| `POST /:providerID/oauth/callback` | Calls `ProviderAuth.callback()` → triggers the plugin's `callback(code?)` → persists tokens via `Auth.set()` |
153+| `GET /auth` | Lists all auth methods from all plugins |
154+
155+---
156+
157+### 5. `ProviderAuth` Coordinator: `provider/auth.ts`
158+
159+Acts as the bridge between the server routes and plugins:
160+- `authorize()` — calls the plugin's `method.authorize()` and stores the pending `AuthOuathResult` in instance state
161+- `callback()` — retrieves the pending result, calls `result.callback(code?)`, then:
162+ - If result has `key` → saves `{ type: "api", key }` to `Auth`
163+ - If result has `refresh` → saves `{ type: "oauth", access, refresh, expires, accountId? }` to `Auth`
164+
165+---
166+
167+### 6. UI: `dialog-connect-provider.tsx`
168+
169+The UI presents the method list and drives the flow:
170+
171+```
172+Method selected → selectMethod(index)
173+ └─ if type === "oauth":
174+ → calls provider.oauth.authorize({ providerID, method: index })
175+ → stores authorization { url, method: "auto"|"code", instructions }
176+ └─ if method === "auto": OAuthAutoView
177+ Opens URL via platform.openLink()
178+ Shows confirmation code from instructions (e.g. "Enter code: XXXX")
179+ Calls provider.oauth.callback({ providerID, method }) — awaits completion
180+ if method === "code": OAuthCodeView
181+ Opens URL via platform.openLink()
182+ User pastes the code manually
183+ Calls provider.oauth.callback({ providerID, method, code })
184+```
185+
186+---
187+
188+### Key Constants (OpenAI-specific)
189+| Constant | Value |
190+|---|---|
191+| `CLIENT_ID` | `app_EMoamEEZ73f0CkXaXp7hrann` |
192+| `ISSUER` | `https://auth.openai.com` |
193+| `CODEX_API_ENDPOINT` | `https://chatgpt.com/backend-api/codex/responses` |
194+| `OAUTH_PORT` | `1455` |
195+| Scopes | `openid profile email offline_access` |
mini-coder-idea.md+3−3
@@ -16,7 +16,7 @@ Elegant output that focus on the conversation with the agent and their actions.
1616 Accurate and reliable core set of features.
1717 Fast and performant
1818 Community oriented, all of the inspirations have their own dotfile format, try to follow the existing
19-conventions and not introduce more specs. (skills.sh installs to `.agents` which could be a good one for us)
19+conventions and not introduce more specs. (skills.sh installs to `.agents,AGENTS.md` which could be a good one for us)
2020
2121 ## Features:
2222
@@ -28,9 +28,9 @@ conventions and not introduce more specs. (skills.sh installs to `.agents` which
2828 - `glob`, `grep`, `read`, `edit`, `shell`, and `subagent` tools for LLMs
2929 - tool hooks support (do command automatically after certain tools)
3030 - Commands in CLI prompt:
31- - `/model` command allows the user to pick a model from connected providers. As well as thinking effort for the model if supported.
31+ - `/model` command allows the user to pick a model from connected providers. As well as thinking effort for the model if supported. Selection persists accross sessions.
3232 - `/review` command sends a subagent with a specific prompt to review code well
33- - `/mcp` list/add/remove mcp servers
33+ - `/mcp` list/add/remove mcp servers. servers are stored in sqlite
3434 - `/plan` for a read-only mode (`/plan` again to turn off)
3535 - Connect to streaming MCPs (Example: https://exa.ai/docs/reference/exa-mcp)
3636
src/agent/agent.ts+23−9
@@ -58,7 +58,6 @@ function loadContextFile(cwd: string): string | null {
5858 const candidates = [
5959 join(cwd, "AGENTS.md"),
6060 join(cwd, "CLAUDE.md"),
61- join(cwd, ".agents", "system.md"),
6261 join(getConfigDir(), "AGENTS.md"),
6362 ];
6463 for (const p of candidates) {
@@ -125,7 +124,10 @@ function dbMessagesToCore(messages: Message[]): any[] {
125124
126125 // ─── Shell passthrough (! prefix) ─────────────────────────────────────────────
127126
128-async function runShellPassthrough(command: string, cwd: string): Promise<string> {
127+async function runShellPassthrough(
128+ command: string,
129+ cwd: string,
130+): Promise<string> {
129131 const proc = Bun.spawn(["bash", "-c", command], {
130132 cwd,
131133 stdout: "pipe",
@@ -150,7 +152,7 @@ async function runShellPassthrough(command: string, cwd: string): Promise<string
150152 export interface AgentOptions {
151153 model: string;
152154 cwd: string;
153- sessionId?: string; // resume existing
155+ sessionId?: string; // resume existing
154156 initialPrompt?: string; // non-interactive first message
155157 }
156158
@@ -187,7 +189,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
187189 const runSubagent = async (
188190 prompt: string,
189191 model?: string,
190- depth = 0
192+ depth = 0,
191193 ): Promise<{ result: string; inputTokens: number; outputTokens: number }> => {
192194 const subModel = model ?? currentModel;
193195 const subMessages: Message[] = [{ role: "user", content: prompt }];
@@ -249,10 +251,19 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
249251 let planMode = false;
250252
251253 const cmdCtx: CommandContext = {
252- get currentModel() { return currentModel; },
253- setModel: (m) => { currentModel = m; session.model = m; },
254- get planMode() { return planMode; },
255- setPlanMode: (v) => { planMode = v; },
254+ get currentModel() {
255+ return currentModel;
256+ },
257+ setModel: (m) => {
258+ currentModel = m;
259+ session.model = m;
260+ },
261+ get planMode() {
262+ return planMode;
263+ },
264+ setPlanMode: (v) => {
265+ planMode = v;
266+ },
256267 cwd,
257268 runSubagent: (prompt, model) => runSubagent(prompt, model),
258269 undoLastTurn: () => {
@@ -378,7 +389,10 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
378389 signal: abortController.signal,
379390 });
380391
381- const { inputTokens, outputTokens, newMessages } = await renderTurn(events, spinner);
392+ const { inputTokens, outputTokens, newMessages } = await renderTurn(
393+ events,
394+ spinner,
395+ );
382396 process.removeListener("SIGINT", onSigInt);
383397
384398 // newMessages are raw ModelMessage objects — push directly into coreHistory