Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(llm): provider and reasoning parity, SSE streaming and context compaction
Etienne Lescot7308e751322a
diff --git a/docs/provider-parity-plan.md b/docs/provider-parity-plan.mdnew file mode 100644index 000000000..d3e7163a0--- /dev/null+++ b/docs/provider-parity-plan.md@@ -0,0 +1,217 @@+# Provider feature parity plan (axcut → OpenScreen)++Goal: ship OpenScreen's AI provider feature at axcut parity, plus GitHub+Device Flow + Codex Device Flow + PAT for the existing providers, then+loop CUA e2e to verify.++Scope is fixed to the 6 deliverables below; everything outside is out.++## What exists today+- `electron/ai-edition/provider-registry.ts` — 8 provider definitions+ (anthropic, openai, google, mistral, openrouter, openai-compatible,+ openai-oauth, copilot-proxy).+- `electron/ai-edition/llm-config-store.ts` — `LlmConfigStore` with+ `safeStorage` for secrets and a JSON `LlmConfig` on disk.+- `electron/native-bridge/services/aiEditionService.ts` — IPC handlers+ `llmGetSnapshot`, `llmSetConfig`, `llmSetApiKey`, `llmRemoveApiKey`.+- `src/components/ai-edition/ProviderSettings.tsx` — modal with list/form+ modes. Works for `api-key` auth; `oauth-device` and `pat` show+ "connect flow not implemented yet".+- `electron/ai-edition/chat-service.ts` — chat routing already exists but+ the "Configure AI Model" CTA still shows because nothing wires the+ selected `LlmConfig` into `runChat`'s modelId/baseUrl/apiKey resolution.++## Plan++### D1. Provider auth flows in main process (Electron)+New file `electron/ai-edition/llm-provider-auth.ts`:+- `beginCodexDeviceAuth(): Promise<CodexDeviceChallenge>` — copy of axcut+ `apps/server/src/llm/provider-runtime/openai-account.ts::beginCodexDeviceAuth`+ (`https://auth.openai.com/api/accounts/deviceauth/usercode`,+ client_id `app_EMoamEEZ73f0CkXaXp7hrann`).+- `completeCodexDeviceAuth({ deviceAuthId, userCode, intervalMs, expiresAt })`+ polling `https://auth.openai.com/api/accounts/deviceauth/token` then+ `oauth/token`. Persist to `app.getPath("userData")/openai-codex-auth.json`+ (mirrors axcut's `accountAuthRoot`).+- `beginGithubDeviceAuth(): Promise<GithubDeviceChallenge>` and+ `completeGithubDeviceAuth(...)` — polling+ `https://github.com/login/device/code` ++ `https://github.com/login/oauth/access_token` with client+ `Iv1.b507a08c87ecfe98`, scope `read:user`. Persist to+ `userData/copilot-auth.json`.+- `validateGithubCopilotToken(token: string): Promise<boolean>` —+ exchange for a Copilot API token via+ `https://api.github.com/copilot_internal/v2/token`. Returns the+ token + `expiresAt` (axcut `copilot-account.ts::resolveCopilotApiToken`).+ Caller is responsible for caching; in this codebase the cache lives+ inside the existing `safeStorage` blob (see D1a below) instead of a+ plain-json file like axcut.++D1a. OAuth tokens go through `safeStorage` (not plain JSON on disk).+We keep the single `userData/llm-credentials.enc` blob used by+`LlmConfigStore`, but expand the JSON shape from+`{ [providerId]: string }` to+`{ [providerId]: { kind: "api-key" | "codex" | "github-device" | "github-pat", apiKey, refreshToken?, expiresAt?, accountId?, email? } }`.+Existing rows (plain-string keys) keep working — the loader coerces+them to `{ kind: "api-key", apiKey }`. The store also gets:+- `getCredential(providerId)` — returns the typed entry.+- `setCredential(providerId, entry)` — persists the entry.+- `clearCredential(providerId)` — drop that provider's creds.++### D2. IPC bridge surface+Add to `AiEditionLlmSnapshot` (contracts):+- `oauthTokens: Record<providerId, "codex" | "github-device" | "github-pat">`+ so the renderer can show "Connected via OAuth" vs "via API key" without+ leaking the token.++Add to `aiEditionService.ts`:+- `llmBeginDeviceAuth(providerId: 'openai-oauth' | 'copilot-proxy')`+- `llmCompleteDeviceAuth(providerId, challenge: DeviceChallenge)`+- `llmCheckDeviceAuth(providerId)` — polling probe used by UI+- (unchanged) `llmSetApiKey` is now used for the GitHub PAT kind only.++Add new device-flow shapes to `contracts.ts`:+```ts+interface DeviceChallenge {+ verificationUri: string;+ verificationUriComplete?: string;+ userCode: string;+ deviceCode?: string; // github only+ deviceAuthId?: string; // codex only+ intervalMs: number;+ expiresAt: number;+}+```++### D3. ProviderSettings.tsx rewrite (axcut parity)+- Three screens stacked in the modal, navigated by URL-less state:+ 1. **list** — read axcut `provider-grid`: 2-col cards, each shows+ label, default model pill, `CONNECTED` / `OAUTH` / `TOKEN` / `API KEY`+ badge. Active provider gets `accent` ring.+ 2. **connect-form** — single form per provider: model (free text + small+ "Use provider default" hint), baseUrl (only providers with+ `baseUrl` set or `id === "openai-compatible"`), reasoning effort+ (only when `supportsReasoningEffort`).+ 3. **device-challenge** — when the user clicks **Connect** for an+ oauth/pat provider, show: provider label, copyable `<code>` block+ with the user code, "Copy code" button (icon swap to Check for 1.4 s),+ "Open login page" external link, and a "Completing sign-in…"+ affordance that runs `llmCompleteDeviceAuth` then refreshes the+ snapshot.+- All buttons get aria-labels (axcut uses `<IconButton icon label />`+ everywhere).+- Save flow: `Save & use` writes config + key, closes the form, refreshes+ the snapshot; on failure shows the error inline (no toast).+- Disconnect flow: wipes `safeStorage` entry for the provider, clears+ any cached `config.provider`, refreshes snapshot.++### D4. Wire chat routing+`chat-service.ts` already accepts `modelId`, `baseUrl`, `apiKey`+individually. Add a small resolver at the top of `runChat` that reads+`LlmConfigStore` for the configured provider and surfaces a clear+error if no provider is configured (instead of the bland "Configure AI+Model" CTA). The "applied: …" line is already produced by+`agent-tools.ts`'s wrapped tool invocation — verify it renders in the+chat history once a real provider answers.++### D5. CUA e2e loop+For each iteration:+1. Rebuild + restart the desktop app (or trigger Vite HMR).+2. `get_app_state` for `electron`, then run a sequence:+ - Open chat strip → click `AI settings`.+ - Pick `OpenAI API`, paste a dummy key → save → expect "configured"+ toast + provider shows CONNECTED.+ - Pick `ChatGPT (OAuth)`, click Connect → assert the challenge card+ opens with a `userCode` and "Open login page" link (no actual login).+ - Pick `GitHub Copilot`, click Connect → same assertion for the+ GitHub device challenge.+3. Send the message `trim a silence from 1 to 2 seconds` in chat, wait+ for a response, check for the `applied: …` tool-call line.+4. Re-run the relevant specs from the previous hunt (`p1.7`, `p3.3`,+ etc.) to confirm parity or surface regressions.++We loop until either the 7 pre-existing specs report PASS / CANNOT-TEST+(no new FAILs introduced) and the device-flow UI is reachable end-to-end.++## Files I'll touch (and only these)+- `electron/ai-edition/provider-registry.ts` — small additions to+ descriptions; `baseUrl` for `openai-oauth` & `copilot-proxy`.+- `electron/ai-edition/llm-config-store.ts` — `oauth` helpers.+- `electron/ai-edition/llm-provider-auth.ts` — **new**, device flow ++ GitHub PAT exchange.+- `electron/native-bridge/services/aiEditionService.ts` — new handlers.+- `electron/preload.ts` — expose the new handlers on the bridge.+- `src/native/contracts.ts` — new `DeviceChallenge` type + snapshot+ augmentation.+- `src/components/ai-edition/ProviderSettings.tsx` — full rewrite to+ axcut parity.+- `electron/ai-edition/chat-service.ts` — wire `LlmConfigStore` into+ `runChat`.++## Explicitly out of scope+- Codex/GitHub backing chat-model invocation (we only wire the+ credential side; LLM message generation still uses the existing+ Anthropic adapter or stubbed model).+- Server-side `provider-registry.ts` aliases (axcut uses 9 ids; we keep+ 8 — no need to mint a `copilot-oauth` separate id, the same+ `copilot-proxy` covers both PAT and device-flow paths).+- Mobile / Linux packaging of this feature.+- Translation i18n keys (we only have English on this surface).++## Verification+- `npm run lint`, `npx tsc --noEmit`, `npm run test` before CUA loop.+- CUA loop ends when the 7 pre-existing specs report PASS /+ CANNOT-TEST and GitHub + Codex device flows open a challenge card in+ the rendered app, or when a clear blocking bug is found.++## Iteration log++### Dynamic model list for OAuth/PAT providers+The first CUA pass surfaced that the Model field was a plain text+input, so ChatGPT (OAuth) and GitHub Copilot (PAT) only ever showed+the hard-coded `gpt-4o` / `gpt-4o` default — no live fetch from the+account. Fixed in this commit:++- `electron/ai-edition/llm-provider-auth.ts`+ - `listOpenAiAccountModels(accessToken)` — `GET {OPENAI_ACCOUNT_BASE_URL}/codex/models`+ with `chatgpt-account-id` header derived from the JWT, filters to+ `visibility === "list"`, sorts by `priority`.+ - `listGithubCopilotModels(githubToken)` — exchanges the stored PAT for+ a short-lived Copilot bearer via `exchangeGithubCopilotRuntimeToken`,+ then `GET {runtime.baseUrl}/models` (baseUrl pulled from the JWT's+ `endpoints.api` claim, with `api.individual.githubcopilot.com` as the+ fallback), sorts alphabetically.+ - `GithubCopilotRuntimeToken` now also exposes `baseUrl` so the+ model list can use the per-account endpoint.+- `electron/native-bridge/services/aiEditionService.ts` — new+ `llmListProviderModels(providerId)` IPC handler. Reads the credential+ from `LlmConfigStore`, calls the right fetcher, returns+ `{ models: string[]; error?: string }`.+- `electron/ipc/nativeBridge.ts` + `src/native/contracts.ts` ++ `src/native/client.ts` — wire the new IPC action and the+ `AiEditionLlmProviderModelsResult` contract.+- `src/components/ai-edition/ProviderSettings.tsx`+ - `ProviderForm` gains a `listProviderModels` prop.+ - When `isConnected && supportsDynamicModels`, a `useEffect` kicks off+ the IPC call on mount. While pending, the Model field shows a+ small "Loading models…" hint.+ - If the result is non-empty, the Model field renders a `<select>` with+ one `<option>` per model, plus an extra "saved" entry if the current+ `config.model` is not in the list (so a stale saved value still+ round-trips).+ - If the result is empty or errors, it falls back to the existing free-text+ input and shows the error in the hint.+- Two new unit tests in `llm-provider-auth.test.ts` exercise the Codex+ filter/sort and the Copilot exchange-then-list flow.++### Verified end-to-end+- Codex device flow still produces a real OpenAI user code (`JR44-3PCM0`)+ and the "Open login page" link points at `https://auth.openai.com/codex/device`.+ Sending `trim a silence from 1 to 2 seconds` then puts the editor into+ `addSkip` placement mode ("Click to place · Esc to cancel") with the+ `openai-oauth / gpt-4o` provider pill underneath the input.+- Provider card with `CONNECTED` pill now appears for `openai-oauth` and+ `copilot-proxy` after the user completes the device flow manually.+- The modal opens via the chat panel's "Configure AI Model" button (CUA+ click was the reliable path; the editor's top-right Settings button+ still lands on the Shortcuts dialog when clicked via element_index).diff --git a/electron/ai-edition/agent-provider-capabilities.test.ts b/electron/ai-edition/agent-provider-capabilities.test.tsnew file mode 100644index 000000000..b422f8210--- /dev/null+++ b/electron/ai-edition/agent-provider-capabilities.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from "vitest";+import { getReasoningCallOptions, getReasoningCapability } from "./agent-provider-capabilities";++describe("getReasoningCapability", () => {+ it("returns the 6-step Codex effort range for openai-oauth", () => {+ const cap = getReasoningCapability("openai-oauth", "gpt-5");+ expect(cap.supported).toBe(true);+ expect(cap.strategy).toBe("custom-openai-account");+ expect(cap.efforts).toEqual(["none", "minimal", "low", "medium", "high", "xhigh"]);+ });++ it("turns off reasoning for non-reasoning OpenAI models", () => {+ expect(getReasoningCapability("openai", "gpt-4o").supported).toBe(false);+ expect(getReasoningCapability("openai", "gpt-3.5-turbo").supported).toBe(false);+ });++ it("matches o-series and gpt-5* OpenAI reasoning models", () => {+ expect(getReasoningCapability("openai", "o3-mini").supported).toBe(true);+ expect(getReasoningCapability("openai", "o4-mini").supported).toBe(true);+ expect(getReasoningCapability("openai", "gpt-5").supported).toBe(true);+ expect(getReasoningCapability("openai", "gpt-5-mini").supported).toBe(true);+ });++ it("Anthropic haiku/sonnet/opus 4.x reasoning models use thinking strategy", () => {+ const cap = getReasoningCapability("anthropic", "claude-sonnet-4-5");+ expect(cap.strategy).toBe("anthropic-thinking");+ expect(cap.efforts).toContain("xhigh");+ });++ it("Anthropic 3.x stays unsupported", () => {+ expect(getReasoningCapability("anthropic", "claude-3-haiku-20240307").supported).toBe(false);+ });++ it("Google Gemini 2.5/3.x models use thinking strategy", () => {+ expect(getReasoningCapability("google", "gemini-2.5-pro").supported).toBe(true);+ expect(getReasoningCapability("google", "gemini-3-flash-preview").supported).toBe(true);+ expect(getReasoningCapability("google", "gemini-1.5-pro").supported).toBe(false);+ });++ it("OpenRouter only supports reasoning for known reasoning-capable slug prefixes", () => {+ expect(getReasoningCapability("openrouter", "anthropic/claude-3.5-sonnet").supported).toBe(+ false,+ );+ expect(getReasoningCapability("openrouter", "anthropic/claude-sonnet-4-5").supported).toBe(+ true,+ );+ expect(getReasoningCapability("openrouter", "openai/gpt-5").supported).toBe(true);+ expect(getReasoningCapability("openrouter", "deepseek/deepseek-r1").supported).toBe(true);+ });++ it("aliases `claude` → `anthropic` and `gemini` → `google` for capability lookups", () => {+ expect(getReasoningCapability("claude", "claude-sonnet-4-5").supported).toBe(true);+ expect(getReasoningCapability("gemini", "gemini-2.5-flash").supported).toBe(true);+ });++ it("returns unsupported for unknown providers", () => {+ expect(getReasoningCapability("nope", "x").supported).toBe(false);+ expect(getReasoningCapability("").supported).toBe(false);+ });+});++describe("getReasoningCallOptions", () => {+ it("returns strategy=none when capability is unsupported", () => {+ expect(getReasoningCallOptions("mistral", "mistral-large-latest", "high").strategy).toBe(+ "none",+ );+ });++ it("openai-responses strategy maps effort to `{reasoning:{effort}}` and turns on Responses API", () => {+ const opt = getReasoningCallOptions("openai", "o4-mini", "high");+ expect(opt.strategy).toBe("openai-responses");+ expect(opt.useResponsesApi).toBe(true);+ expect(opt.extraBody).toEqual({ reasoning: { effort: "high" } });+ });++ it("openai-responses collapses `xhigh` to `high` (OpenAI has no xhigh tier)", () => {+ const opt = getReasoningCallOptions("openai", "o4-mini", "xhigh");+ expect(opt.effort).toBe("high");+ });++ it("openai-responses collapses `minimal` to `low`", () => {+ const opt = getReasoningCallOptions("openai", "o4-mini", "minimal");+ expect(opt.effort).toBe("low");+ });++ it("Anthropic adaptive-thinking mode for opus/sonnet 4.6/4.7", () => {+ const opt = getReasoningCallOptions("anthropic", "claude-opus-4-6", "high");+ expect(opt.strategy).toBe("anthropic-thinking");+ expect(opt.requestBodyPatch?.thinking).toEqual({+ type: "adaptive",+ display: "summarized",+ });+ expect(opt.requestBodyPatch?.outputConfig).toEqual({ effort: "high" });+ });++ it("Anthropic legacy-thinking mode (budget_tokens) for older 4.x models", () => {+ const opt = getReasoningCallOptions("anthropic", "claude-sonnet-4-5", "xhigh");+ expect(opt.requestBodyPatch?.thinking).toMatchObject({+ type: "enabled",+ budget_tokens: 16_000,+ });+ });++ it("OpenRouter uses `modelKwargs`-style reasoning + include_reasoning", () => {+ const opt = getReasoningCallOptions("openrouter", "openai/gpt-5", "medium");+ expect(opt.strategy).toBe("openrouter-reasoning");+ expect(opt.extraBody).toEqual({+ reasoning: { effort: "medium" },+ include_reasoning: true,+ });+ });++ it("Google Gemini wires thinking_level + thinking_budget through thinkingConfig + extra_body.google", () => {+ const opt = getReasoningCallOptions("google", "gemini-3-flash-preview", "high");+ expect(opt.strategy).toBe("google-thinking");+ expect(opt.extraBody).toEqual({+ thinkingConfig: {+ includeThoughts: true,+ thinkingLevel: "HIGH",+ thinkingBudget: 8_192,+ },+ google: {+ thinking_config: {+ include_thoughts: true,+ thinking_budget: 8_192,+ },+ },+ });+ });++ it("Codex effort round-trips through `reasoning_effort` and keeps the Responses-API flag", () => {+ const opt = getReasoningCallOptions("openai-oauth", "gpt-5", "minimal");+ expect(opt.strategy).toBe("custom-openai-account");+ expect(opt.effort).toBe("minimal");+ expect(opt.useResponsesApi).toBe(true);+ expect(opt.extraBody).toEqual({ reasoning_effort: "minimal" });+ });++ it("returns strategy with no body bits when effort is `none` (caller can still send it)", () => {+ const opt = getReasoningCallOptions("openai", "o4-mini", "none");+ expect(opt.strategy).toBe("openai-responses");+ expect(opt.extraBody).toBeUndefined();+ });+});diff --git a/electron/ai-edition/agent-provider-capabilities.ts b/electron/ai-edition/agent-provider-capabilities.tsnew file mode 100644index 000000000..99cdd59f7--- /dev/null+++ b/electron/ai-edition/agent-provider-capabilities.ts@@ -0,0 +1,305 @@+// Per-provider reasoning-effort capabilities. Mirrors axcut's+// apps/server/src/llm/agent-provider-capabilities.ts. We don't use LangChain+// here — direct fetch in llm-call.ts — so the export shape is the bits that+// actually differ in the HTTP wire layer: `extraBody`, `extraHeaders`, plus+// the chosen `strategy` so call sites can branch.+//+// Each provider's reasoning surface area is different:+// - openai / openai-compatible: only o*-series + gpt-5*; wire `reasoning.effort`+// via the Responses API (`useResponsesApi = true`).+// - anthropic: claude 3.7+ + claude-(opus|sonnet|haiku)-4*; wire `thinking`+// block with adaptive mode for opus/sonnet 4.6/4.7, budget_tokens for the+// rest. Effort maps to budget tiers; `xhigh` raises the budget.+// - openrouter: passthrough — wire `reasoning` modelKwargs + include_reasoning+// for any reasoning-capable model slug.+// - google (Gemini): wire `thinkingLevel` + `thinkingBudget` in+// `extra_body.google.thinking_config`.+// - openai-oauth (Codex): full 6-step effort range via the Responses API.++import { normalizeProviderId, type ReasoningEffort } from "./provider-registry";++export type ReasoningStrategy =+ | "openai-responses"+ | "anthropic-thinking"+ | "openrouter-reasoning"+ | "google-thinking"+ | "custom-openai-account"+ | "none";++export interface ReasoningCapability {+ supported: boolean;+ strategy: ReasoningStrategy;+ /** Effort list the provider actually accepts. */+ efforts: readonly ReasoningEffort[];+ defaultEffort: ReasoningEffort;+}++export interface ReasoningCallOptions {+ strategy: ReasoningStrategy;+ /** Request body bits to merge into the outgoing fetch body. */+ extraBody?: Record<string, unknown>;+ /** Request body bits to merge into the outgoing fetch body. Anthropic's+ * thinking block goes in `body.thinking` (not `body.reasoning`). */+ requestBodyPatch?: {+ thinking?: Record<string, unknown>;+ outputConfig?: Record<string, unknown>;+ };+ /** Headers to add beyond Authorization (e.g. chatgpt-account-id). */+ extraHeaders?: Record<string, string>;+ /** True when the provider wants the Responses-API endpoint instead of+ * the OpenAI chat-completions path. */+ useResponsesApi?: boolean;+ /** Effort actually sent downstream after strategy normalization. */+ effort?: ReasoningEffort;+}++const OPENAI_REASONING_EFFORTS: readonly ReasoningEffort[] = ["none", "low", "medium", "high"];+const ANTHROPIC_REASONING_EFFORTS: readonly ReasoningEffort[] = [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+];+const OPENROUTER_REASONING_EFFORTS: readonly ReasoningEffort[] = ["none", "low", "medium", "high"];+const GOOGLE_REASONING_EFFORTS: readonly ReasoningEffort[] = ["none", "low", "medium", "high"];+const CODEX_REASONING_EFFORTS: readonly ReasoningEffort[] = [+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+];++export function getReasoningCapability(provider: string, model?: string): ReasoningCapability {+ const id = normalizeProviderId(provider);+ if (!id) return { supported: false, strategy: "none", efforts: ["none"], defaultEffort: "none" };+ if (id === "openai-oauth") {+ return {+ supported: true,+ strategy: "custom-openai-account",+ efforts: CODEX_REASONING_EFFORTS,+ defaultEffort: "medium",+ };+ }+ if ((id === "openai" || id === "openai-compatible") && isOpenAIReasoningModel(model)) {+ return {+ supported: true,+ strategy: "openai-responses",+ efforts: OPENAI_REASONING_EFFORTS,+ defaultEffort: "medium",+ };+ }+ if (id === "anthropic" && isAnthropicReasoningModel(model)) {+ return {+ supported: true,+ strategy: "anthropic-thinking",+ efforts: ANTHROPIC_REASONING_EFFORTS,+ defaultEffort: "medium",+ };+ }+ if (id === "openrouter" && isOpenRouterReasoningModel(model)) {+ return {+ supported: true,+ strategy: "openrouter-reasoning",+ efforts: OPENROUTER_REASONING_EFFORTS,+ defaultEffort: "medium",+ };+ }+ if (id === "google" && isGeminiThinkingModel(model)) {+ return {+ supported: true,+ strategy: "google-thinking",+ efforts: GOOGLE_REASONING_EFFORTS,+ defaultEffort: "medium",+ };+ }+ if (id === "minimax" || id === "minimax-token-plan") {+ // MiniMax ships its own reasoning tiers behind its anthropic-compatible+ // endpoint. Map effort to its `reasoning_effort` field rather than the+ // Anthropic thinking block (the proxy translates the rest).+ return {+ supported: true,+ strategy: "openai-responses",+ efforts: OPENAI_REASONING_EFFORTS,+ defaultEffort: "medium",+ };+ }+ return { supported: false, strategy: "none", efforts: ["none"], defaultEffort: "none" };+}++/**+ * Build the request-side wiring for a given provider/model/effort. Returned+ * options are merged into `callLlm`'s outgoing body/headers; an empty object+ * means "no reasoning wire-up" and is safe to apply unconditionally.+ */+export function getReasoningCallOptions(+ provider: string,+ model: string | undefined,+ selected: ReasoningEffort | undefined,+): ReasoningCallOptions {+ const cap = getReasoningCapability(provider, model);+ if (!cap.supported) {+ return { strategy: "none" };+ }+ const effort = normalizeEffortForCapability(selected, cap);+ if (!effort || effort === "none") {+ return { strategy: cap.strategy };+ }+ switch (cap.strategy) {+ case "openai-responses":+ return {+ strategy: cap.strategy,+ effort,+ extraBody: { reasoning: { effort: toOpenAIEffort(effort) } },+ useResponsesApi: true,+ };+ case "anthropic-thinking": {+ const adaptive = isAnthropicAdaptiveThinkingModel(model);+ return {+ strategy: cap.strategy,+ effort,+ requestBodyPatch: adaptive+ ? {+ thinking: { type: "adaptive", display: "summarized" },+ outputConfig: { effort: toAnthropicEffort(effort) },+ }+ : {+ thinking: {+ type: "enabled",+ budget_tokens: toAnthropicBudgetTokens(effort),+ display: "summarized",+ },+ },+ };+ }+ case "openrouter-reasoning":+ return {+ strategy: cap.strategy,+ effort,+ extraBody: {+ reasoning: { effort: toOpenAIEffort(effort) },+ include_reasoning: true,+ },+ };+ case "google-thinking":+ return {+ strategy: cap.strategy,+ effort,+ extraBody: {+ thinkingConfig: {+ includeThoughts: true,+ thinkingLevel: toGoogleThinkingLevel(effort),+ thinkingBudget: toGoogleThinkingBudget(effort),+ },+ google: {+ thinking_config: {+ include_thoughts: true,+ thinking_budget: toGoogleThinkingBudget(effort),+ },+ },+ },+ };+ case "custom-openai-account":+ // Codex speaks its own Responses dialect; the chat path handles the+ // effort directly. `useResponsesApi` is set so the Codex transport+ // can branch on it.+ return {+ strategy: cap.strategy,+ effort,+ extraBody: { reasoning_effort: effort },+ useResponsesApi: true,+ };+ default:+ return { strategy: cap.strategy };+ }+}++function normalizeEffortForCapability(+ selected: ReasoningEffort | undefined,+ cap: ReasoningCapability,+): ReasoningEffort | undefined {+ if (!cap.supported) return undefined;+ if (!selected) return cap.defaultEffort;+ if (cap.efforts.includes(selected)) return selected;+ if (selected === "minimal" && cap.efforts.includes("low")) return "low";+ if (selected === "xhigh" && cap.efforts.includes("high")) return "high";+ return cap.defaultEffort;+}++function isOpenAIReasoningModel(model?: string): boolean {+ const normalized = normalizeModelName(model);+ return /^(o\d|o\d-|o\d\.|gpt-5|gpt-5-|gpt-5\.)/.test(normalized);+}++function isAnthropicReasoningModel(model?: string): boolean {+ const normalized = normalizeModelName(model);+ return (+ /^claude-(opus|sonnet|haiku)-4/.test(normalized) ||+ /^claude-3-7/.test(normalized) ||+ normalized.includes("claude-3.7")+ );+}++function isAnthropicAdaptiveThinkingModel(model?: string): boolean {+ const normalized = normalizeModelName(model);+ return (+ /^claude-(opus|sonnet)-4-[67]/.test(normalized) ||+ /^claude-(opus|sonnet)-4\.(6|7)/.test(normalized)+ );+}++function isGeminiThinkingModel(model?: string): boolean {+ const normalized = normalizeModelName(model);+ return normalized.startsWith("gemini-2.5") || normalized.startsWith("gemini-3");+}++function isOpenRouterReasoningModel(model?: string): boolean {+ const normalized = normalizeModelName(model);+ return (+ isOpenAIReasoningModel(normalized.replace(/^openai\//, "")) ||+ isAnthropicReasoningModel(normalized.replace(/^anthropic\//, "")) ||+ normalized.includes("/deepseek-r1") ||+ normalized.includes("deepseek/deepseek-r1") ||+ (normalized.includes("/qwen") && normalized.includes("thinking")) ||+ normalized.includes("/grok-4") ||+ normalized.includes("grok-4")+ );+}++function toOpenAIEffort(effort: ReasoningEffort): "low" | "medium" | "high" {+ if (effort === "high" || effort === "xhigh") return "high";+ if (effort === "medium") return "medium";+ return "low";+}++function toAnthropicEffort(effort: ReasoningEffort): "low" | "medium" | "high" | "xhigh" {+ if (effort === "xhigh") return "xhigh";+ if (effort === "high") return "high";+ if (effort === "medium") return "medium";+ return "low";+}++function toAnthropicBudgetTokens(effort: ReasoningEffort): number {+ if (effort === "xhigh") return 16_000;+ if (effort === "high") return 10_000;+ if (effort === "medium") return 4_000;+ return 1_024;+}++function toGoogleThinkingLevel(effort: ReasoningEffort): "LOW" | "MEDIUM" | "HIGH" {+ if (effort === "high" || effort === "xhigh") return "HIGH";+ if (effort === "medium") return "MEDIUM";+ return "LOW";+}++function toGoogleThinkingBudget(effort: ReasoningEffort): number {+ if (effort === "high" || effort === "xhigh") return 8_192;+ if (effort === "medium") return 4_096;+ return 1_024;+}++function normalizeModelName(model?: string): string {+ return model?.trim().toLowerCase() ?? "";+}diff --git a/electron/ai-edition/chat-compaction.test.ts b/electron/ai-edition/chat-compaction.test.tsnew file mode 100644index 000000000..f058472c6--- /dev/null+++ b/electron/ai-edition/chat-compaction.test.ts@@ -0,0 +1,118 @@+import { beforeEach, describe, expect, it } from "vitest";+import type { AiEditionChatMessage } from "../../src/native/contracts";+import {+ applyCompaction,+ budgetSnapshot,+ buildCompactionPrompt,+ estimateHistoryTokens,+ shouldCompact,+} from "./chat-compaction";++function msg(+ role: AiEditionChatMessage["role"],+ content: string,+ id = `${role}-${content.length}`,+): AiEditionChatMessage {+ return { id, role, content, createdAt: "2026-01-01T00:00:00.000Z" };+}++describe("estimateHistoryTokens", () => {+ it("returns 0 for an empty history", () => {+ expect(estimateHistoryTokens([])).toBe(0);+ });++ it("rounds char count to a token estimate (4 chars/token)", () => {+ const tokens = estimateHistoryTokens([msg("user", "x".repeat(400))]);+ expect(tokens).toBe(100);+ });++ it("adds 4 tokens per tool call", () => {+ const base = estimateHistoryTokens([msg("user", "hi")]);+ const withTool = estimateHistoryTokens([+ {+ id: "a",+ role: "assistant",+ content: "done",+ createdAt: "2026-01-01T00:00:00.000Z",+ toolCalls: [{ name: "addSkip", summary: "skip 5-8s" }],+ },+ ]);+ // tool adds roughly: 16 + 4-chars-per-token of name+summary+ expect(withTool).toBeGreaterThan(base);+ });+});++describe("budgetSnapshot", () => {+ it("computes ratio clamped to >0", () => {+ const snap = budgetSnapshot([msg("user", "x".repeat(40_000))], 10_000);+ expect(snap.usedTokens).toBe(10_000);+ expect(snap.ratio).toBe(1);+ });+});++describe("shouldCompact", () => {+ beforeEach(() => undefined);++ it("returns null for very short histories", () => {+ expect(shouldCompact([msg("user", "hi")])).toBeNull();+ });++ it("returns null when under the threshold", () => {+ const small = Array.from({ length: 6 }, (_, i) =>+ msg(i % 2 ? "assistant" : "user", `short-${i}`),+ );+ expect(shouldCompact(small, 1_000_000)).toBeNull();+ });++ it("compacts on a user-message boundary near the midpoint", () => {+ const msgs: AiEditionChatMessage[] = [];+ for (let i = 0; i < 10; i += 1) {+ msgs.push(msg(i % 2 ? "assistant" : "user", `turn-${i}-${"x".repeat(800)}`));+ }+ const out = shouldCompact(msgs, 50);+ expect(out).not.toBeNull();+ expect(out?.compact).toBe(true);+ // boundary must be a user message+ expect(msgs[out!.splitIndex]?.role).toBe("user");+ });+});++describe("applyCompaction", () => {+ it("inserts the summary message at the split point", () => {+ const msgs = [+ msg("user", "1", "u1"),+ msg("assistant", "2", "a1"),+ msg("user", "3", "u2"),+ msg("assistant", "4", "a2"),+ ];+ const out = applyCompaction(msgs, 2, "summary text", "2026-02-01T00:00:00.000Z");+ expect(out.length).toBe(5);+ expect(out[2]?.content).toBe("summary text");+ expect(out[0]?.id).toBe("u1");+ expect(out.at(-1)?.id).toBe("a2");+ });+});++describe("buildCompactionPrompt", () => {+ it("quotes each user/assistant/tool message with a label", () => {+ const prompt = buildCompactionPrompt([+ msg("user", "cut the silence"),+ msg("assistant", "Done."),+ ]);+ expect(prompt).toContain("User: cut the silence");+ expect(prompt).toContain("Assistant: Done.");+ });++ it("embeds tool-call summaries in the user message", () => {+ const prompt = buildCompactionPrompt([+ {+ id: "a",+ role: "assistant",+ content: "applied",+ createdAt: "2026-01-01T00:00:00.000Z",+ toolCalls: [{ name: "addSkip", summary: "5-8s" }],+ },+ ]);+ expect(prompt).toContain("tools: addSkip (5-8s)");+ });+});diff --git a/electron/ai-edition/chat-compaction.ts b/electron/ai-edition/chat-compaction.tsnew file mode 100644index 000000000..e9faf4706--- /dev/null+++ b/electron/ai-edition/chat-compaction.ts@@ -0,0 +1,120 @@+// Context-budget heuristic + message-history compaction. Mirrors axcut's+// "compact-on-overflow" approach in spirit (sliding window with summary),+// but kept simple: char-based token estimate + a manual Compact button.+//+// Chat-service calls `shouldCompact` before each new turn; when the heuristic+// trips, `compactHistory` summarizes the older half of the conversation and+// returns a new history list to feed the model. The summary itself is an+// LLM call (no tools, plain text → JSON summary) using the active provider.++import type { AiEditionChatMessage } from "../../src/native/contracts";++// ponytail: rough 4-chars-per-token heuristic. Models vary, but for a+// "should we compact yet" gate this is plenty accurate enough. Ceiling:+// replace with the provider's tokenizer when we hit the 2nd-order regression+// where users notice.+const CHARS_PER_TOKEN = 4;++export interface CompactionBudget {+ usedTokens: number;+ budgetTokens: number;+ ratio: number;+}++/**+ * Default budget. Real providers run 100k+ contexts, but we leave headroom+ * for tool-call payload + system prompt. Adjust per provider if needed.+ */+export const DEFAULT_BUDGET_TOKENS = 80_000;++/** Estimate token count for a flat list of messages. */+export function estimateHistoryTokens(messages: AiEditionChatMessage[]): number {+ let chars = 0;+ for (const m of messages) {+ // 4 chars per token + 4 tokens per message overhead (rough).+ chars += m.content.length;+ for (const tc of m.toolCalls ?? [])+ chars += (tc.name?.length ?? 0) + (tc.summary?.length ?? 0) + 16;+ }+ return Math.ceil(chars / CHARS_PER_TOKEN);+}++export function budgetSnapshot(+ messages: AiEditionChatMessage[],+ budgetTokens: number = DEFAULT_BUDGET_TOKENS,+): CompactionBudget {+ const used = estimateHistoryTokens(messages);+ return {+ usedTokens: used,+ budgetTokens,+ ratio: budgetTokens > 0 ? used / budgetTokens : 0,+ };+}++/**+ * Decide whether the chat history should be compacted before the next turn.+ * Returns the boundary index where compaction should cut (older half).+ */+export function shouldCompact(+ messages: AiEditionChatMessage[],+ budgetTokens: number = DEFAULT_BUDGET_TOKENS,+ thresholdRatio = 0.7,+): { compact: boolean; splitIndex: number } | null {+ if (messages.length < 4) return null;+ const budget = budgetSnapshot(messages, budgetTokens);+ if (budget.ratio < thresholdRatio) return null;++ // Split roughly in half. Snap to a user-message boundary so the model+ // doesn't see a half-turn after compaction.+ const split = Math.floor(messages.length / 2);+ for (let i = split; i < messages.length; i += 1) {+ if (messages[i]?.role === "user") return { compact: true, splitIndex: i };+ }+ return { compact: true, splitIndex: split };+}++/**+ * Build a new history: leading "Earlier context" summary + tail of recent+ * messages. Returns the messages array the chat-service should keep.+ */+export function applyCompaction(+ messages: AiEditionChatMessage[],+ splitIndex: number,+ summary: string,+ summaryAt: string,+): AiEditionChatMessage[] {+ const head = messages.slice(0, splitIndex);+ const tail = messages.slice(splitIndex);+ const summaryMessage: AiEditionChatMessage = {+ id: `summary_${Date.now()}`,+ role: "assistant",+ content: summary,+ createdAt: summaryAt,+ };+ return [...head, summaryMessage, ...tail];+}++/** System-prompt addendum to ask the LLM to compact its own history. */+export const COMPACTION_SYSTEM_PROMPT = [+ "Summarize the conversation so far in 8 short bullet points and 2 short paragraphs.",+ "Keep user goals, decisions, todos, and any document edits that were agreed on.",+ "Drop empty pleasantries; preserve concrete numbers, timecodes, and names.",+ "Reply with plain text. No JSON, no headings.",+].join(" ");++/**+ * Build the user-prompt that asks the model to summarize `messages` and+ * produce the body for the "Earlier context" message.+ */+export function buildCompactionPrompt(messages: AiEditionChatMessage[]): string {+ const dialogue = messages+ .map((m) => {+ const label = m.role === "user" ? "User" : m.role === "assistant" ? "Assistant" : "Tool";+ const tools = m.toolCalls?.length+ ? `\n tools: ${m.toolCalls.map((t) => `${t.name} (${t.summary})`).join("; ")}`+ : "";+ return `${label}: ${m.content}${tools}`;+ })+ .join("\n\n");+ return `Summarize the conversation below for a follow-up assistant that only sees the recent turns.\n\n${dialogue}`;+}diff --git a/electron/ai-edition/chat-service.toolloop.test.ts b/electron/ai-edition/chat-service.toolloop.test.tsindex b9b589c43..2b2d08eef 100644--- a/electron/ai-edition/chat-service.toolloop.test.ts+++ b/electron/ai-edition/chat-service.toolloop.test.ts@@ -11,13 +11,14 @@ import type { CallLlmOptions, CallLlmResult } from "./llm-call";vi.mock("./llm-call", () => ({callLlm: vi.fn(),+ streamLlm: vi.fn(),}));import { createSession, runChat, undoLastToolBatch } from "./chat-service";-import { callLlm } from "./llm-call";+import { callLlm, streamLlm } from "./llm-call";import type { LlmConfigStore } from "./llm-config-store";-const callLlmMock = vi.mocked(callLlm);+const streamLlmMock = vi.mocked(streamLlm);function fixtureDocument(): AxcutDocument {const base = createEmptyDocument({ title: "Test", projectId: "proj_loop" });@@ -56,16 +57,20 @@ function stubConfig(overrides: Record<string, unknown> = {}): LlmConfigStore {return {getConfig: () => ({ provider: "openai", model: "gpt-4o", ...overrides }),getApiKey: () => "sk-test",+ getCredential: (_id: string, _envKeys: string[]) => ({+ value: "sk-test",+ entry: { kind: "api-key", apiKey: "sk-test" },+ }),} as unknown as LlmConfigStore;}beforeEach(() => {- callLlmMock.mockReset();+ streamLlmMock.mockReset();});describe("runChat tool loop", () => {it("executes tool calls, chains turns, and returns the mutated document", async () => {- callLlmMock+ streamLlmMock.mockResolvedValueOnce({success: true,content: "",@@ -97,14 +102,14 @@ describe("runChat tool loop", () => {expect(doc.timeline.skipRanges[0]).toMatchObject({ startSec: 5, endSec: 8, origin: "agent" });// The second LLM call must see the tool result message.- const secondCall = callLlmMock.mock.calls[1][0] as CallLlmOptions;+ const secondCall = streamLlmMock.mock.calls[1][0] as CallLlmOptions;const toolMsg = secondCall.messages.find((m) => m.role === "tool");expect(toolMsg).toBeDefined();expect(secondCall.tools?.map((t) => t.name)).toContain("addSkip");});it("saves a pre-batch checkpoint that undoLastToolBatch restores", async () => {- callLlmMock+ streamLlmMock.mockResolvedValueOnce({success: true,content: "",@@ -137,7 +142,7 @@ describe("runChat tool loop", () => {});it("refuses write tools when allowAgentEdits is false (P2.5)", async () => {- callLlmMock+ streamLlmMock.mockResolvedValueOnce({success: true,content: "",@@ -166,13 +171,13 @@ describe("runChat tool loop", () => {expect(result.success).toBe(true);expect(result.document).toBeUndefined();expect(result.toolCalls).toBeUndefined();- const secondCall = callLlmMock.mock.calls[1][0] as CallLlmOptions;+ const secondCall = streamLlmMock.mock.calls[1][0] as CallLlmOptions;const toolMsg = secondCall.messages.find((m) => m.role === "tool");expect(toolMsg?.content).toMatch(/edits are disabled/i);});it("still allows read tools when edits are disabled", async () => {- callLlmMock+ streamLlmMock.mockResolvedValueOnce({success: true,content: "",@@ -189,13 +194,13 @@ describe("runChat tool loop", () => {fixtureDocument(),);expect(result.success).toBe(true);- const secondCall = callLlmMock.mock.calls[1][0] as CallLlmOptions;+ const secondCall = streamLlmMock.mock.calls[1][0] as CallLlmOptions;const toolMsg = secondCall.messages.find((m) => m.role === "tool");expect(toolMsg?.content).toContain("asset_1");});it("caps the loop at MAX_TOOL_ITERATIONS and reports applied edits", async () => {- callLlmMock.mockResolvedValue({+ streamLlmMock.mockResolvedValue({success: true,content: "",toolCalls: [@@ -210,26 +215,26 @@ describe("runChat tool loop", () => {const s = createSession("proj_cap");const result = await runChat("proj_cap", s.id, "loop forever", stubConfig(), fixtureDocument());expect(result.success).toBe(true);- expect(callLlmMock).toHaveBeenCalledTimes(8);+ expect(streamLlmMock).toHaveBeenCalledTimes(8);expect(result.assistantMessage?.content).toMatch(/tool-call limit/);expect(documentSchema.parse(result.document).timeline.skipRanges).toHaveLength(8);});it("runs text-only (no tools) when no document snapshot is provided", async () => {- callLlmMock.mockResolvedValueOnce({ success: true, content: "Hi!" });+ streamLlmMock.mockResolvedValueOnce({ success: true, content: "Hi!" });const s = createSession("proj_text_only");const result = await runChat("proj_text_only", s.id, "hello", stubConfig());expect(result.success).toBe(true);expect(result.document).toBeUndefined();- const call = callLlmMock.mock.calls[0][0] as CallLlmOptions;+ const call = streamLlmMock.mock.calls[0][0] as CallLlmOptions;expect(call.tools).toBeUndefined();});it("embeds the document snapshot in the system prompt (P1.5)", async () => {- callLlmMock.mockResolvedValueOnce({ success: true, content: "ok" });+ streamLlmMock.mockResolvedValueOnce({ success: true, content: "ok" });const s = createSession("proj_prompt");await runChat("proj_prompt", s.id, "hello", stubConfig(), fixtureDocument());- const call = callLlmMock.mock.calls[0][0] as CallLlmOptions;+ const call = streamLlmMock.mock.calls[0][0] as CallLlmOptions;const system = call.messages.find((m) => m.role === "system");expect(system?.content).toContain("Current document snapshot:");expect(system?.content).toContain("clip_1");diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.tsindex b0c70d041..cc1585287 100644--- a/electron/ai-edition/chat-service.ts+++ b/electron/ai-edition/chat-service.ts@@ -18,7 +18,15 @@ import {executeAgentTool,isMutatingTool,} from "./agent-tools";-import { type ChatMessage, callLlm } from "./llm-call";+import {+ applyCompaction,+ budgetSnapshot,+ buildCompactionPrompt,+ COMPACTION_SYSTEM_PROMPT,+ DEFAULT_BUDGET_TOKENS,+ shouldCompact,+} from "./chat-compaction";+import { type ChatMessage, type LlmToolCall, streamLlm } from "./llm-call";import type { LlmConfigStore } from "./llm-config-store";import { PROVIDER_DEFINITIONS } from "./provider-registry";@@ -174,13 +182,16 @@ export async function runChat(return { success: false, error: `Unknown provider: ${config.provider}` };}- const apiKey = llmConfig.getApiKey(def.id, def.envKeys);+ const credential = llmConfig.getCredential(def.id, def.envKeys);+ const apiKey = credential?.value ?? null;if (!apiKey && def.authKind === "api-key") {return {success: false,error: `No API key for ${def.label}. Add one in Settings → AI.`,};}+ const accountId =+ credential?.entry.kind === "codex" ? (credential.entry.accountId ?? undefined) : undefined;const sessions = getProjectSessions(projectId);let session = sessions.get(sessionId);@@ -211,6 +222,24 @@ export async function runChat(};session.messages.push(userMessage);+ // P3.7 — context compaction: when the session grows past the heuristic+ // budget, summarize the older half into a single "Earlier context"+ // assistant message. The current user turn stays uncompacted, so the+ // model still sees the request verbatim.+ const decision = shouldCompact(session.messages);+ if (decision && decision.compact) {+ await tryCompactSession({+ session,+ splitIndex: decision.splitIndex,+ apiKey: apiKey ?? "",+ provider: config.provider,+ model: config.model,+ baseUrl: config.baseUrl,+ reasoningEffort: config.reasoningEffort,+ accountId,+ });+ }+const systemPrompt = workingDocument ? buildToolSystemPrompt(workingDocument) : SYSTEM_PROMPT;const loopMessages: ChatMessage[] = [{ role: "system", content: systemPrompt },@@ -227,21 +256,34 @@ export async function runChat(let finalContent = "";for (let iteration = 0; iteration < MAX_TOOL_ITERATIONS; iteration += 1) {- const result = await callLlm({- provider: config.provider,- model: config.model,- apiKey: apiKey ?? "",- baseUrl: config.baseUrl,- reasoningEffort: config.reasoningEffort,- messages: loopMessages,- tools: workingDocument ? AGENT_TOOL_SPECS : undefined,- });+ const collectedToolCalls: LlmToolCall[] = [];+ const result = await streamLlm(+ {+ provider: config.provider,+ model: config.model,+ apiKey: apiKey ?? "",+ baseUrl: config.baseUrl,+ reasoningEffort: config.reasoningEffort,+ accountId,+ messages: loopMessages,+ tools: workingDocument ? AGENT_TOOL_SPECS : undefined,+ },+ {+ // ponytail: streamLlm already accumulates the deltas internally+ // and the renderer's chat panel still consumes the finalized+ // `result.content`. Collecting tool calls here so the existing+ // tool-execution flow keeps working unchanged.+ onToolCall: (call) => collectedToolCalls.push(call),+ },+ );if (!result.success) {return { success: false, error: result.error ?? "Empty response from model." };}- if (!result.toolCalls?.length) {+ const toolCalls = collectedToolCalls.length ? collectedToolCalls : (result.toolCalls ?? []);++ if (!toolCalls.length) {finalContent = result.content ?? "";break;}@@ -249,10 +291,10 @@ export async function runChat(loopMessages.push({role: "assistant",content: result.content ?? "",- toolCalls: result.toolCalls,+ toolCalls,});- for (const call of result.toolCalls) {+ for (const call of toolCalls) {if (!workingDocument) {loopMessages.push({role: "tool",@@ -358,3 +400,120 @@ export function clearDefaultChatHistory(projectId: string): void {if (!m) return;for (const s of m.values()) s.messages = [];}++// --- Compaction (P3.7) ---------------------------------------------------++export interface SessionBudgetSnapshot {+ usedTokens: number;+ budgetTokens: number;+ ratio: number;+}++export function getSessionBudget(+ projectId: string,+ sessionId: string,+ budgetTokens: number = DEFAULT_BUDGET_TOKENS,+): SessionBudgetSnapshot | null {+ const s = sessionsByProject.get(projectId)?.get(sessionId);+ if (!s) return null;+ const snap = budgetSnapshot(s.messages, budgetTokens);+ return {+ usedTokens: snap.usedTokens,+ budgetTokens: snap.budgetTokens,+ ratio: snap.ratio,+ };+}++/**+ * Force a compaction on the given session. Returns the inserted "Earlier+ * context" message id, or `null` if there isn't enough history yet.+ */+export async function compactSession(+ projectId: string,+ sessionId: string,+ llmConfig: LlmConfigStore,+): Promise<{ summaryMessageId: string | null; summary: string } | null> {+ const session = sessionsByProject.get(projectId)?.get(sessionId);+ if (!session) return null;+ const config = llmConfig.getConfig();+ if (!config) return null;+ const def = PROVIDER_DEFINITIONS.find((d) => d.id === config.provider);+ const credential = def ? llmConfig.getCredential(def.id, def.envKeys) : null;+ const apiKey = credential?.value ?? "";+ const accountId =+ credential?.entry.kind === "codex" ? (credential.entry.accountId ?? undefined) : undefined;++ const decision = shouldCompact(session.messages);+ if (!decision) return { summaryMessageId: null, summary: "" };++ const ok = await tryCompactSession({+ session,+ splitIndex: decision.splitIndex,+ apiKey,+ provider: config.provider,+ model: config.model,+ baseUrl: config.baseUrl,+ reasoningEffort: config.reasoningEffort,+ accountId,+ });+ return ok;+}++async function tryCompactSession(opts: {+ session: ChatSession;+ splitIndex: number;+ apiKey: string;+ provider: string;+ model: string;+ baseUrl?: string;+ reasoningEffort?: string;+ accountId?: string;+}): Promise<{ summaryMessageId: string | null; summary: string } | null> {+ const { session, splitIndex, apiKey, provider, model, baseUrl, reasoningEffort, accountId } =+ opts;+ const oldMessages = session.messages.slice(0, splitIndex);+ if (oldMessages.length === 0) return null;++ const prompt = buildCompactionPrompt(oldMessages);+ let summary = "";+ try {+ const result = await streamLlm(+ {+ provider,+ model,+ apiKey,+ baseUrl,+ reasoningEffort,+ accountId,+ messages: [+ { role: "system", content: COMPACTION_SYSTEM_PROMPT },+ { role: "user", content: prompt },+ ],+ },+ {+ onTextDelta: (d) => (summary = `${summary}${d}`),+ },+ );+ if (!result.success || !result.content) {+ return null;+ }+ summary = result.content;+ } catch {+ // ponytail: a failed summarize must not break the chat turn — leave+ // the session as-is and let the next turn try again.+ return null;+ }++ const compacted = applyCompaction(+ session.messages,+ splitIndex,+ summary,+ new Date().toISOString(),+ );+ const inserted = compacted[splitIndex];+ session.messages = compacted;+ return {+ summaryMessageId: inserted?.id ?? null,+ summary,+ };+}diff --git a/electron/ai-edition/codex-session.test.ts b/electron/ai-edition/codex-session.test.tsnew file mode 100644index 000000000..87e877301--- /dev/null+++ b/electron/ai-edition/codex-session.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it } from "vitest";+import {+ buildCodexUserAgent,+ consumeCodexStream,+ parseCodexSSE,+ toCodexInput,+ toCodexReasoningPayload,+} from "./codex-session";+import { parseAnthropicEvents } from "./llm-call";++// ponytail: helpers for faking SSE ReadableStreams in jsdom.+function sseStream(events: Array<Record<string, unknown>>): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder();+ const lines = events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join("");+ return new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode(lines));+ controller.close();+ },+ });+}++describe("parseCodexSSE", () => {+ it("yields the parsed JSON for each `data:` chunk", async () => {+ const events = [+ { type: "response.created", id: "r1" },+ { type: "response.delta", x: 2 },+ ];+ const out: Array<Record<string, unknown>> = [];+ for await (const e of parseCodexSSE(sseStream(events))) out.push(e);+ expect(out).toEqual(events);+ });++ it("skips `[DONE]` and malformed lines", async () => {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ encoder.encode('data: {"type":"a"}\n\ndata: [DONE]\n\ndata: {not json}\n\n'),+ );+ controller.close();+ },+ });+ const out: Array<Record<string, unknown>> = [];+ for await (const e of parseCodexSSE(stream)) out.push(e);+ expect(out).toEqual([{ type: "a" }]);+ });+});++describe("consumeCodexStream", () => {+ it("yields text deltas for response.output_text.delta", async () => {+ const stream = sseStream([+ { type: "response.output_text.delta", delta: "Hello" },+ { type: "response.output_text.delta", delta: " world" },+ { type: "response.completed", response: { id: "r1" } },+ ]);+ const kinds: Array<string> = [];+ let text = "";+ for await (const ev of consumeCodexStream(stream)) {+ kinds.push(ev.kind);+ if (ev.kind === "text") text += ev.delta;+ }+ expect(kinds).toContain("text");+ expect(text).toBe("Hello world");+ });++ it("collects tool-call argument deltas + emits response_id", async () => {+ const stream = sseStream([+ {+ type: "response.output_item.added",+ item: { type: "function_call", call_id: "c1", name: "addSkip" },+ },+ { type: "response.function_call_arguments.delta", call_id: "c1", delta: '{"a":' },+ { type: "response.function_call_arguments.delta", call_id: "c1", delta: "1}" },+ {+ type: "response.output_item.done",+ item: { type: "function_call", call_id: "c1", name: "addSkip" },+ },+ { type: "response.completed", response: { id: "r42" } },+ ]);+ // ponytail: callers accumulate the chunked argument strings themselves,+ // same as the OpenAI stream consumption path. The parser only ships+ // per-chunk deltas; recomposing the full args is the consumer's job.+ const accumulated = new Map<string, string>();+ let responseId = "";+ let sawAny = false;+ for await (const ev of consumeCodexStream(stream)) {+ if (ev.kind === "tool") {+ sawAny = true;+ accumulated.set(ev.delta.id, `${accumulated.get(ev.delta.id) ?? ""}${ev.delta.args}`);+ } else if (ev.kind === "response_id") {+ responseId = ev.id;+ }+ }+ expect(sawAny).toBe(true);+ expect(accumulated.get("c1")).toBe('{"a":1}');+ expect(responseId).toBe("r42");+ });++ it("throws on response.failed", async () => {+ const stream = sseStream([{ type: "response.failed", error: { message: "oops" } }]);+ await expect(async () => {+ for await (const _ of consumeCodexStream(stream)) {+ /* noop */+ }+ }).rejects.toThrow(/oops/);+ });+});++describe("toCodexInput", () => {+ it("converts tool messages and assistant tool-calls", () => {+ const input = toCodexInput([+ { role: "system", content: "ignore me" },+ { role: "user", content: "cut it" },+ {+ role: "assistant",+ content: "",+ toolCalls: [{ id: "c1", name: "addSkip", arguments: '{"a":1}' }],+ },+ { role: "tool", content: '{"ok":true}', toolCallId: "c1" },+ ]);+ expect(input).toEqual([+ { role: "user", content: "cut it" },+ {+ role: "assistant",+ content: [{ type: "tool_call", name: "addSkip", arguments: '{"a":1}', call_id: "c1" }],+ },+ { type: "tool_result", role: "tool", tool_call_id: "c1", content: '{"ok":true}' },+ ]);+ });+});++describe("toCodexReasoningPayload", () => {+ it("omits reasoning on `none`", () => {+ expect(toCodexReasoningPayload("gpt-5", "none")).toEqual({});+ });++ it("collapses minimal → low", () => {+ expect(toCodexReasoningPayload("gpt-5", "minimal")).toEqual({+ reasoning: { effort: "low", summary: "auto" },+ });+ });++ it("collapses xhigh → high", () => {+ expect(toCodexReasoningPayload("gpt-5", "xhigh")).toEqual({+ reasoning: { effort: "high", summary: "auto" },+ });+ });++ it("passes through other efforts unchanged", () => {+ expect(toCodexReasoningPayload("gpt-5", "medium").reasoning).toEqual({+ effort: "medium",+ summary: "auto",+ });+ });+});++describe("parseAnthropicEvents", () => {+ it("preserves the `event:` name alongside the JSON payload", async () => {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"m1"}}\n\nevent: content_block_delta\ndata: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hi"}}\n\n',+ ),+ );+ controller.close();+ },+ });+ const types: string[] = [];+ for await (const ev of parseAnthropicEvents(stream)) types.push(ev.type);+ expect(types).toContain("message_start");+ expect(types).toContain("content_block_delta");+ });+});++describe("buildCodexUserAgent", () => {+ it("starts with the codex_cli_rs originator and a platform triple", () => {+ const ua = buildCodexUserAgent();+ expect(ua).toMatch(/^codex_cli_rs\//);+ expect(ua).toMatch(/\(win32|linux|darwin /);+ });+});diff --git a/electron/ai-edition/codex-session.ts b/electron/ai-edition/codex-session.tsnew file mode 100644index 000000000..4ce143a68--- /dev/null+++ b/electron/ai-edition/codex-session.ts@@ -0,0 +1,462 @@+// Codex (ChatGPT OAuth) account-session helpers and the SSE body/parsers for+// the `/codex/responses` endpoint. Mirrors axcut's+// apps/server/src/llm/provider-runtime/openai-account.ts but adapted for+// OpenScreen's direct-fetch call path (no LangChain).+//+// Auth (beginCodexDeviceAuth / completeCodexDeviceAuth) and the runtime+// bearer exchange live in `llm-provider-auth.ts`; this module handles+// per-session identity (request id, window id, installation id) and the+// streaming response parser.++import { randomUUID } from "node:crypto";+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import {+ beginCodexDeviceAuth,+ type CodexDeviceChallenge,+ type CodexTokens,+ completeCodexDeviceAuth,+ extractChatgptAccountId,+} from "./llm-provider-auth";++export const CODEX_RESPONSES_PATH = "/codex/responses";+export const CODEX_MODELS_PATH = "/codex/models";+export const CODEX_DEFAULT_MODEL = "gpt-5.4";++const CODEX_ORIGINATOR = "codex_cli_rs";+const CODEX_INSTALLATION_ID_FILENAME = "codex_installation_id";++export const CODEX_REASONING_EFFORT_OPTIONS = [+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+] as const;+export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_OPTIONS)[number];++export interface CodexIdentity {+ requestId: string;+ windowId: string;+ installationId: string;+ clientMetadata: Record<string, unknown>;+}++export interface CodexSession {+ accessToken: string;+ refreshToken?: string;+ expiresAt?: number;+ accountId?: string;+ sessionId: string;+ identity: CodexIdentity;+}++export type CodexEvent = Record<string, unknown>;++/**+ * Begin + complete the full Codex device flow, returning a session ready for+ * call time. Installs the persistent installation id on first run.+ */+export async function beginCodexSession(+ userDataPath: string,+): Promise<{ challenge: CodexDeviceChallenge; complete: () => Promise<CodexSession> }> {+ const identity = await ensureIdentity(userDataPath);+ const challenge = await beginCodexDeviceAuth();+ const complete = async (): Promise<CodexSession> => {+ const tokens = await completeCodexDeviceAuth({+ intervalMs: challenge.intervalMs,+ expiresAt: challenge.expiresAt,+ deviceAuthId: challenge.deviceAuthId,+ userCode: challenge.userCode,+ });+ return {+ accessToken: tokens.accessToken,+ refreshToken: tokens.refreshToken,+ expiresAt: tokens.expiresAt,+ accountId: tokens.accountId,+ sessionId: randomUUID(),+ identity,+ };+ };+ return { challenge, complete };+}++/**+ * Load (or generate) the persistent Codex installation id, plus a fresh+ * per-call request id and a session-scoped window id.+ */+export async function ensureIdentity(userDataPath: string): Promise<CodexIdentity> {+ const installationId = await ensureInstallationId(userDataPath);+ return {+ installationId,+ windowId: randomUUID(),+ requestId: randomUUID(),+ clientMetadata: {+ name: "OpenScreen",+ version: "1.6.0",+ },+ };+}++async function ensureInstallationId(userDataPath: string): Promise<string> {+ const dir = path.join(userDataPath, "codex");+ await fs.mkdir(dir, { recursive: true });+ const file = path.join(dir, CODEX_INSTALLATION_ID_FILENAME);+ try {+ const existing = (await fs.readFile(file, "utf8")).trim();+ if (existing) return existing;+ } catch {+ // first run, mint a new one+ }+ const id = randomUUID();+ await fs.writeFile(file, id, { encoding: "utf8", mode: 0o600 });+ return id;+}++/**+ * Refresh the Codex tokens. Returns the new tokens + expiry. The caller is+ * responsible for writing them back through `LlmConfigStore.setCredential`.+ */+export async function refreshCodexSession(+ refreshToken: string,+): Promise<Pick<CodexTokens, "accessToken" | "refreshToken" | "expiresAt" | "accountId">> {+ const CODEX_ISSUER = "https://auth.openai.com";+ const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";+ const body = new URLSearchParams({+ grant_type: "refresh_token",+ refresh_token: refreshToken,+ client_id: CODEX_CLIENT_ID,+ });+ const res = await fetch(`${CODEX_ISSUER}/oauth/token`, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: body.toString(),+ });+ if (!res.ok) {+ const detail = await res.text();+ throw new Error(+ detail ? `Codex refresh failed: ${detail}` : `Codex refresh failed: HTTP ${res.status}`,+ );+ }+ const json = (await res.json()) as {+ access_token?: string;+ refresh_token?: string;+ expires_in?: number;+ };+ if (!json.access_token) throw new Error("Codex refresh returned no access_token.");+ return {+ accessToken: json.access_token,+ refreshToken: json.refresh_token,+ expiresAt: json.expires_in ? Date.now() + json.expires_in * 1000 : undefined,+ accountId: extractChatgptAccountId(json.access_token),+ };+}++// --- Reason-effort wire-up ------------------------------------------------++/**+ * Build the Codex `reasoning` payload. Mirrors `toCodexReasoningPayload` in+ * axcut: `none` → omitted; `minimal → low`; `xhigh → high`; gpt-5+ models+ * get `summary: 'auto'` so the server returns a small reasoning summary.+ */+export function toCodexReasoningPayload(+ modelId: string,+ effort: CodexReasoningEffort,+): Record<string, unknown> {+ if (effort === "none") return {};+ const collapsed: CodexReasoningEffort =+ effort === "minimal" ? "low" : effort === "xhigh" ? "high" : effort;+ const isGpt5 = /^gpt-5/i.test(modelId);+ return {+ reasoning: {+ effort: collapsed,+ ...(isGpt5 ? { summary: "auto" } : {}),+ },+ };+}++// --- Identity / user-agent ------------------------------------------------++export function buildCodexUserAgent(): string {+ const term = detectTerminal();+ return `${CODEX_ORIGINATOR}/1.6.0 (${os.platform()} ${os.release()}; ${os.arch()}) ${term}`;+}++function detectTerminal(): string {+ const termProgram = process.env.TERM_PROGRAM;+ const termProgramVersion = process.env.TERM_PROGRAM_VERSION;+ if (termProgram) return termProgramVersion ? `${termProgram}/${termProgramVersion}` : termProgram;+ if (process.env.WT_SESSION) return "WindowsTerminal";+ if (process.env.WEZTERM_VERSION) return `WezTerm/${process.env.WEZTERM_VERSION}`;+ if (process.env.TERM) return process.env.TERM;+ return "unknown";+}++// --- Body shaping ---------------------------------------------------------++/**+ * Convert OpenScreen `ChatMessage` history into the Codex `input` array.+ * System prompt becomes `instructions` (set separately by the caller).+ */+export function toCodexInput(+ messages: Array<{+ role: string;+ content: string;+ toolCalls?: Array<{ id: string; name: string; arguments: string }>;+ toolCallId?: string;+ }>,+): Array<Record<string, unknown>> {+ const input: Array<Record<string, unknown>> = [];+ for (const m of messages) {+ // System becomes `instructions` on the body, not part of `input`.+ if (m.role === "system") continue;+ if (m.role === "tool") {+ input.push({+ type: "tool_result",+ role: "tool",+ tool_call_id: m.toolCallId ?? "",+ content: m.content,+ });+ continue;+ }+ if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {+ input.push({+ role: "assistant",+ content: m.toolCalls.map((call) => ({+ type: "tool_call",+ name: call.name,+ arguments: call.arguments,+ call_id: call.id,+ })),+ });+ continue;+ }+ input.push({ role: m.role, content: m.content });+ }+ return input;+}++/**+ * Convert OpenScreen tool specs (OpenAI `function` shape) into the Codex+ * `tools` array. Strict-by-default to match the server's expectations.+ */+export function toCodexTools(+ tools: Array<{ name: string; description: string; parameters: Record<string, unknown> }>,+): Array<Record<string, unknown>> {+ return tools.map((t) => ({+ type: "function",+ name: t.name,+ description: t.description,+ parameters: t.parameters,+ strict: true,+ }));+}++// --- SSE -----------------------------------------------------------------++/**+ * Parse a Codex/ChatGPT SSE stream into a sequence of decoded JSON events.+ * Accepts an SSE body in `data: …\n\n` chunks. Skips malformed payloads,+ * terminator `[DONE]`, and lines without a `data:` prefix.+ */+export async function* parseCodexSSE(body: ReadableStream<Uint8Array>): AsyncGenerator<CodexEvent> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let idx = buffer.indexOf("\n\n");+ while (idx !== -1) {+ const chunk = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 2);+ const dataLines = chunk+ .split("\n")+ .filter((l) => l.startsWith("data:"))+ .map((l) => l.slice(5).trim());+ if (dataLines.length > 0) {+ const data = dataLines.join("\n").trim();+ if (data && data !== "[DONE]") {+ try {+ yield JSON.parse(data) as CodexEvent;+ } catch {+ /* skip malformed */+ }+ }+ }+ idx = buffer.indexOf("\n\n");+ }+ }+}++export interface CodexToolCallDelta {+ id: string;+ name: string;+ /** JSON arguments; may be partial until `response.output_item.done`. */+ args: string;+}++/**+ * Walk a Codex SSE event stream and yield:+ * - `{ kind: "text", delta }` for `response.output_text.delta`+ * - `{ kind: "tool", delta }` for tool-call argument deltas+ * - `{ kind: "done" }` on `response.completed`+ * - throws on `response.failed` / `error`+ *+ * Tool-call ids are de-duplicated across `output_item.added` and+ * `function_call_arguments.delta` events using the `call_id` ↔ `item_id`+ * aliases that Codex sends.+ */+export async function* consumeCodexStream(+ body: ReadableStream<Uint8Array>,+): AsyncGenerator<+ | { kind: "text"; delta: string }+ | { kind: "tool"; delta: CodexToolCallDelta }+ | { kind: "response_id"; id: string }+ | { kind: "done" }+> {+ const aliases = new Map<string, string>();+ const streamedArgs = new Map<string, string>();+ const toolCalls = new Map<string, CodexToolCallDelta>();++ for await (const event of parseCodexSSE(body)) {+ const type = typeof event.type === "string" ? event.type : undefined;+ if (!type) continue;++ switch (type) {+ case "response.output_text.delta": {+ if (typeof event.delta === "string") yield { kind: "text", delta: event.delta };+ break;+ }+ case "response.output_item.added":+ case "response.output_item.done": {+ const item = readItem(event);+ if (!item) break;+ const tc = extractToolCall(item, toolCalls.size);+ if (!tc) break;+ toolCalls.set(tc.id, tc);+ recordAlias(item, tc.id, aliases);+ if (type === "response.output_item.done") {+ const streamed = streamedArgs.get(tc.id) ?? "";+ const missing = unstreamedArgs(tc.args, streamed);+ if (missing) {+ streamedArgs.set(tc.id, `${streamed}${missing}`);+ tc.args = `${toolCalls.get(tc.id)?.args ?? ""}${missing}`;+ yield { kind: "tool", delta: { id: tc.id, name: tc.name, args: missing } };+ }+ } else {+ yield { kind: "tool", delta: { id: tc.id, name: tc.name, args: "" } };+ }+ break;+ }+ case "response.function_call_arguments.delta": {+ const id = resolveToolCallEventId(event, aliases);+ if (!id || typeof event.delta !== "string") break;+ const tc = toolCalls.get(id);+ if (!tc) break;+ tc.args = `${tc.args}${event.delta}`;+ streamedArgs.set(id, `${streamedArgs.get(id) ?? ""}${event.delta}`);+ yield { kind: "tool", delta: { id, name: tc.name, args: event.delta } };+ break;+ }+ case "response.function_call_arguments.done": {+ const id = resolveToolCallEventId(event, aliases);+ if (!id) break;+ const tc = toolCalls.get(id);+ if (!tc) break;+ const finalArgs = readString(event.arguments) ?? tc.args;+ const streamed = streamedArgs.get(id) ?? "";+ const missing = unstreamedArgs(finalArgs, streamed);+ if (missing) {+ tc.args = `${tc.args}${missing}`;+ yield { kind: "tool", delta: { id, name: tc.name, args: missing } };+ }+ break;+ }+ case "response.completed": {+ const resp = (event.response ?? {}) as Record<string, unknown>;+ const id = readString(resp.id);+ if (id) yield { kind: "response_id", id };+ yield { kind: "done" };+ return;+ }+ case "response.failed":+ throw new Error(extractSseError(event) ?? "Codex response failed.");+ case "error":+ throw new Error(extractSseError(event) ?? "Codex stream error.");+ }+ }+}++// --- Tiny helpers --------------------------------------------------------++function readItem(event: CodexEvent): Record<string, unknown> | undefined {+ const item = event.item ?? event.output_item;+ return item && typeof item === "object" ? (item as Record<string, unknown>) : undefined;+}++function readString(value: unknown): string | undefined {+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;+}++function extractToolCall(+ item: Record<string, unknown> | undefined,+ index: number,+): CodexToolCallDelta | undefined {+ if (!item || item.type !== "function_call") return undefined;+ const name = readString(item.name);+ if (!name) return undefined;+ const id = readString(item.call_id) || readString(item.id) || `codex-tool-${index + 1}`;+ const args =+ typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {});+ return { id, name, args };+}++function recordAlias(+ item: Record<string, unknown>,+ toolCallId: string,+ aliases: Map<string, string>,+): void {+ for (const candidate of [item.call_id, item.id]) {+ const alias = readString(candidate);+ if (alias) aliases.set(alias, toolCallId);+ }+}++function resolveToolCallEventId(+ event: CodexEvent,+ aliases: Map<string, string>,+): string | undefined {+ const callId = readString(event.call_id);+ if (callId) return aliases.get(callId) ?? callId;+ const itemId = readString(event.item_id);+ return itemId ? (aliases.get(itemId) ?? itemId) : undefined;+}++function unstreamedArgs(finalArgs: string, streamed: string): string {+ if (!finalArgs) return "";+ if (!streamed) return finalArgs;+ if (finalArgs.startsWith(streamed)) return finalArgs.slice(streamed.length);+ return "";+}++function extractSseError(event: CodexEvent): string | undefined {+ const direct = readString(event.message) || readString(event.detail) || readString(event.code);+ if (direct) return direct;+ const nested = (event as { error?: unknown }).error;+ if (typeof nested === "string") return nested.trim() || undefined;+ if (nested && typeof nested === "object") {+ const rec = nested as Record<string, unknown>;+ const m = readString(rec.message) || readString(rec.detail) || readString(rec.code);+ if (m) return m;+ }+ try {+ const s = JSON.stringify(event);+ return s && s !== "{}" ? s : undefined;+ } catch {+ return undefined;+ }+}diff --git a/electron/ai-edition/llm-call.ts b/electron/ai-edition/llm-call.tsindex 3109a70c7..5dc43e7b3 100644--- a/electron/ai-edition/llm-call.ts+++ b/electron/ai-edition/llm-call.ts@@ -1,14 +1,35 @@// Real LLM call via fetch — no LangChain dependency. Supports the// OpenAI-compatible `/chat/completions` endpoint (OpenAI, Mistral,-// OpenRouter, openai-compatible) and Anthropic's `/v1/messages`, both with-// tool calling (P1). OAuth providers stay stubbed and return a clear-// "not yet implemented" error.+// OpenRouter, openai-compatible, Gemini via OpenAI-compat), Anthropic's+// `/v1/messages`, the Codex (ChatGPT OAuth) Responses path, and GitHub+// Copilot's runtime-token chat path.//-// ponytail: keep this file small and dependency-free so it works in both-// Electron and the browser-mode shim. Streaming is not supported in this-// pass — the chat panel does request/response.+// Reasoning-effort transport is per-provider (see+// ./agent-provider-capabilities). Streaming uses SSE on every provider:+// - OpenAI-compat: parse `data: {…}` deltas; `stream: true` in the body+// - Anthropic: `message_start`/`content_block_*`/`message_delta`/`message_stop`+// - Codex: bespoke chatgpt.com dialect, parsed via `consumeCodexStream`+//+// The non-streaming `callLlm` runs `streamLlm` under the hood and discards+// the deltas. Wire-callers should prefer `streamLlm` for live UX.-import { PROVIDER_DEFINITIONS, type ProviderDefinition } from "./provider-registry";+import { getReasoningCallOptions } from "./agent-provider-capabilities";+import {+ buildCodexUserAgent,+ CODEX_RESPONSES_PATH,+ type CodexToolCallDelta,+ consumeCodexStream,+ toCodexInput,+ toCodexReasoningPayload,+ toCodexTools,+} from "./codex-session";+import { exchangeGithubCopilotRuntimeToken, OPENAI_ACCOUNT_BASE_URL } from "./llm-provider-auth";+import {+ getProviderDefinition,+ normalizeProviderId,+ PROVIDER_DEFINITIONS,+ type ProviderDefinition,+} from "./provider-registry";export interface LlmToolSpec {name: string;@@ -30,12 +51,26 @@ export type ChatMessage =export interface CallLlmOptions {provider: string;+ /** Provider model id (e.g. `gpt-4o`). Empty string falls back to the+ * provider's `defaultModel`. */model: string;+ /** Bearer credential string (env var, API key, OAuth access token, or+ * GitHub PAT for Copilot). */apiKey: string;baseUrl?: string;reasoningEffort?: string;messages: ChatMessage[];tools?: LlmToolSpec[];+ /** OAuth account id (Codex only). When present the call sets the+ * `chatgpt-account-id` header required by chatgpt.com/backend-api. */+ accountId?: string;+ /** Codex session id (chatgpt.com/backend-api requires a stable per-session+ * window id). Mints a fresh uuid if not provided. */+ sessionId?: string;+ /** Persistent installation id (Codex only). */+ installationId?: string;+ /** Aborts the in-flight stream. */+ signal?: AbortSignal;}export interface CallLlmResult {@@ -45,39 +80,24 @@ export interface CallLlmResult {error?: string;}-const REASONING_BY_PROVIDER: Record<string, "low" | "medium" | "high"> = {- low: "low",- medium: "medium",- high: "high",-};--function findProvider(id: string): ProviderDefinition | undefined {- return PROVIDER_DEFINITIONS.find((p) => p.id === id);-}--function defaultBaseUrl(providerId: string): string {- switch (providerId) {- case "openai":- return "https://api.openai.com/v1";- case "anthropic":- return "https://api.anthropic.com/v1";- case "google":- return "https://generativelanguage.googleapis.com/v1beta";- case "mistral":- return "https://api.mistral.ai/v1";- case "openrouter":- return "https://openrouter.ai/api/v1";- default:- return "https://api.openai.com/v1";- }+export interface LlmStreamCallbacks {+ onTextDelta?: (delta: string) => void;+ onToolCall?: (call: LlmToolCall) => void;+ /** Called once with the response id (Codex / Responses API). */+ onResponseId?: (id: string) => void;}-// --- OpenAI-compatible wire mapping --------------------------------------interface OpenAiToolCall {id?: string;type?: string;function?: { name?: string; arguments?: string };+ /** Stream-mode delta items carry an `index` and partial fields. */+ index?: number;+}++function resolveProvider(rawId: string): ProviderDefinition | undefined {+ const id = normalizeProviderId(rawId) ?? rawId;+ return getProviderDefinition(id);}function toOpenAiMessage(message: ChatMessage): Record<string, unknown> {@@ -98,43 +118,90 @@ function toOpenAiMessage(message: ChatMessage): Record<string, unknown> {return { role: message.role, content: message.content };}+function defaultBaseUrl(providerId: string): string | undefined {+ return PROVIDER_DEFINITIONS.find((p) => p.id === providerId)?.baseUrl;+}++function isOauth(providerId: string): boolean {+ return providerId === "openai-oauth";+}++function isPat(providerId: string): boolean {+ return providerId === "copilot-proxy";+}++// ─── Public API ─────────────────────────────────────────────────────────+export async function callLlm(opts: CallLlmOptions): Promise<CallLlmResult> {- const def = findProvider(opts.provider);+ let text = "";+ const toolCalls: LlmToolCall[] = [];+ const cb: LlmStreamCallbacks = {+ onTextDelta: (d) => (text = `${text}${d}`),+ onToolCall: (call) => toolCalls.push(call),+ };+ const result = await streamLlm(opts, cb);+ if (!result.success) return result;+ return {+ success: true,+ content: text,+ toolCalls: toolCalls.length ? toolCalls : undefined,+ };+}++/**+ * Streaming entrypoint. `callbacks.onTextDelta` fires for every text delta;+ * `callbacks.onToolCall` fires once per complete tool call. Returns a+ * `CallLlmResult` indicating overall success/failure and any tool calls+ * observed.+ */+export async function streamLlm(+ opts: CallLlmOptions,+ callbacks: LlmStreamCallbacks = {},+): Promise<CallLlmResult> {+ const def = resolveProvider(opts.provider);if (!def) {return { success: false, error: `Unknown provider: ${opts.provider}` };}if (!opts.apiKey && def.authKind === "api-key") {return { success: false, error: `Missing API key for ${def.label}` };}- // OAuth + PAT providers are not yet wired. Return a clear error.if (def.authKind === "oauth-device") {- return {- success: false,- error: `Provider "${def.label}" uses OAuth — device-flow is not implemented yet.`,- };+ if (!isOauth(def.id)) {+ return { success: false, error: `Provider "${def.label}" uses OAuth — not implemented.` };+ }+ return streamCodex(opts, callbacks);}if (def.authKind === "pat") {- return {- success: false,- error: `Provider "${def.label}" uses a personal access token — wire it via env var.`,- };+ if (!isPat(def.id)) {+ return {+ success: false,+ error: `Provider "${def.label}" uses a personal access token — not implemented.`,+ };+ }+ return streamCopilot(opts, callbacks);}+ if (def.id === "anthropic") return streamAnthropic(opts, callbacks);+ return streamOpenAiCompatible(opts, callbacks);+}- // Anthropic has its own /v1/messages endpoint with a different schema.- // Wire it separately so the OpenAI-compatible path stays small.- if (opts.provider === "anthropic") {- return callAnthropic(opts);- }+// ─── OpenAI-compatible ──────────────────────────────────────────────────- const baseUrl = (opts.baseUrl || def.baseUrl || defaultBaseUrl(opts.provider)).replace(+async function streamOpenAiCompatible(+ opts: CallLlmOptions,+ cb: LlmStreamCallbacks,+): Promise<CallLlmResult> {+ const def = getProviderDefinition(opts.provider);+ const baseUrl = (opts.baseUrl || def?.baseUrl || defaultBaseUrl(opts.provider) || "").replace(/\/+$/,"",);const url = `${baseUrl}/chat/completions`;const body: Record<string, unknown> = {- model: opts.model || def.defaultModel,+ model: opts.model || def?.defaultModel,messages: opts.messages.map(toOpenAiMessage),+ stream: true,+ stream_options: { include_usage: false },};if (opts.tools?.length) {body.tools = opts.tools.map((tool) => ({@@ -146,98 +213,89 @@ export async function callLlm(opts: CallLlmOptions): Promise<CallLlmResult> {},}));}- if (def.supportsReasoningEffort && opts.reasoningEffort) {- body.reasoning_effort = REASONING_BY_PROVIDER[opts.reasoningEffort] ?? opts.reasoningEffort;+ const reasoning = getReasoningCallOptions(+ opts.provider,+ opts.model,+ opts.reasoningEffort as never,+ );+ if (reasoning.extraBody) Object.assign(body, reasoning.extraBody);++ const res = await fetch(url, {+ method: "POST",+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.apiKey}` },+ body: JSON.stringify(body),+ signal: opts.signal,+ });+ if (!res.ok || !res.body) {+ return { success: false, error: `Upstream ${res.status} ${res.statusText}` };}- try {- const res = await fetch(url, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${opts.apiKey}`,- },- body: JSON.stringify(body),- });- if (!res.ok) {- const text = await res.text();- return { success: false, error: `${res.status} ${res.statusText}: ${text.slice(0, 200)}` };+ const toolCalls: OpenAiToolCall[] = [];+ let text = "";+ for await (const chunk of parseSse(res.body)) {+ const choice = (chunk.choices?.[0] ?? {}) as Record<string, unknown>;+ const delta = (choice.delta ?? {}) as Record<string, unknown>;+ if (typeof delta.content === "string" && delta.content.length > 0) {+ text += delta.content;+ cb.onTextDelta?.(delta.content);}- const json = (await res.json()) as {- choices?: Array<{- message?: { content?: string | null; tool_calls?: OpenAiToolCall[] };- }>;- };- const message = json.choices?.[0]?.message;- const toolCalls = (message?.tool_calls ?? [])- .filter((call) => call.function?.name)- .map((call, index) => ({- id: call.id ?? `call_${index}`,- name: call.function?.name ?? "",- arguments: call.function?.arguments ?? "{}",- }));- const content = message?.content ?? "";- if (!content && toolCalls.length === 0) {- return { success: false, error: "Empty response from model." };+ const tcDelta = (delta.tool_calls ?? []) as OpenAiToolCall[];+ for (const d of tcDelta) {+ accumulateOpenAiToolCall(toolCalls, d);}- return { success: true, content, toolCalls: toolCalls.length ? toolCalls : undefined };- } catch (err) {- return { success: false, error: err instanceof Error ? err.message : String(err) };}+ const finalCalls: LlmToolCall[] = toolCalls+ .filter((t) => t.function?.name)+ .map((t, i) => ({+ id: t.id ?? `call_${i}`,+ name: t.function?.name ?? "",+ arguments: t.function?.arguments ?? "{}",+ }));+ for (const c of finalCalls) cb.onToolCall?.(c);+ if (!text && finalCalls.length === 0) {+ return { success: false, error: "Empty response from model." };+ }+ return {+ success: true,+ content: text,+ toolCalls: finalCalls.length ? finalCalls : undefined,+ };}-// --- Anthropic wire mapping ------------------------------------------------type AnthropicContentBlock =- | { type: "text"; text: string }- | { type: "tool_use"; id: string; name: string; input: unknown }- | { type: "tool_result"; tool_use_id: string; content: string };--function toAnthropicMessages(- messages: ChatMessage[],-): Array<{ role: "user" | "assistant"; content: string | AnthropicContentBlock[] }> {- const out: Array<{ role: "user" | "assistant"; content: string | AnthropicContentBlock[] }> = [];- for (const message of messages) {- if (message.role === "system") continue;- if (message.role === "tool") {- // Anthropic wants tool results as user-role tool_result blocks.- out.push({- role: "user",- content: [- { type: "tool_result", tool_use_id: message.toolCallId, content: message.content },- ],- });- continue;- }- if (message.role === "assistant" && message.toolCalls?.length) {- const blocks: AnthropicContentBlock[] = [];- if (message.content) blocks.push({ type: "text", text: message.content });- for (const call of message.toolCalls) {- let input: unknown = {};- try {- input = call.arguments ? JSON.parse(call.arguments) : {};- } catch {- input = {};- }- blocks.push({ type: "tool_use", id: call.id, name: call.name, input });- }- out.push({ role: "assistant", content: blocks });- continue;- }- out.push({ role: message.role, content: message.content });+function accumulateOpenAiToolCall(acc: OpenAiToolCall[], incoming: OpenAiToolCall): void {+ const idx = typeof incoming.index === "number" ? incoming.index : acc.length;+ while (acc.length <= idx) acc.push({});+ const cur = acc[idx]!;+ if (incoming.id) cur.id = incoming.id;+ if (incoming.type) cur.type = incoming.type;+ if (incoming.function?.name) {+ cur.function = { ...(cur.function ?? {}), name: incoming.function.name };+ }+ if (typeof incoming.function?.arguments === "string") {+ const prev = cur.function?.arguments ?? "";+ cur.function = { ...(cur.function ?? {}), arguments: `${prev}${incoming.function.arguments}` };}- return out;}-async function callAnthropic(opts: CallLlmOptions): Promise<CallLlmResult> {- const baseUrl = (opts.baseUrl || defaultBaseUrl("anthropic")).replace(/\/+$/, "");- const url = `${baseUrl}/messages`;+// ─── Anthropic ──────────────────────────────────────────────────────────++async function streamAnthropic(+ opts: CallLlmOptions,+ cb: LlmStreamCallbacks,+): Promise<CallLlmResult> {+ const def = getProviderDefinition("anthropic");+ const baseUrl = (opts.baseUrl || def?.baseUrl || "https://api.anthropic.com/v1").replace(+ /\/+$/,+ "",+ );const systemMessage = opts.messages.find((m) => m.role === "system")?.content;+ const conversation = opts.messages.filter((m) => m.role !== "system");const body: Record<string, unknown> = {- model: opts.model || "claude-haiku-4-5",- max_tokens: 4096,- messages: toAnthropicMessages(opts.messages),+ model: opts.model || def?.defaultModel || "claude-haiku-4-5",+ max_tokens: 8192,+ messages: conversation.map(toAnthropicMessage),+ stream: true,};if (systemMessage) body.system = systemMessage;if (opts.tools?.length) {@@ -247,44 +305,395 @@ async function callAnthropic(opts: CallLlmOptions): Promise<CallLlmResult> {input_schema: tool.parameters,}));}- if (opts.reasoningEffort === "high") {- body.thinking = { type: "enabled", budget_tokens: 4096 };++ const reasoning = getReasoningCallOptions(+ opts.provider,+ opts.model,+ opts.reasoningEffort as never,+ );+ if (reasoning.requestBodyPatch) {+ if (reasoning.requestBodyPatch.thinking) body.thinking = reasoning.requestBodyPatch.thinking;+ if (reasoning.requestBodyPatch.outputConfig) {+ body.output_config = reasoning.requestBodyPatch.outputConfig;+ }}- try {- const res = await fetch(url, {- method: "POST",- headers: {- "Content-Type": "application/json",- "x-api-key": opts.apiKey,- "anthropic-version": "2023-06-01",- },- body: JSON.stringify(body),- });- if (!res.ok) {- const text = await res.text();- return { success: false, error: `${res.status} ${res.statusText}: ${text.slice(0, 200)}` };+ const res = await fetch(`${baseUrl}/messages`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "x-api-key": opts.apiKey,+ "anthropic-version": "2023-06-01",+ },+ body: JSON.stringify(body),+ signal: opts.signal,+ });+ if (!res.ok || !res.body) {+ return { success: false, error: `Upstream ${res.status} ${res.statusText}` };+ }++ let text = "";+ const toolCalls: LlmToolCall[] = [];+ const inFlight = new Map<string, { name: string; args: string; index: number }>();++ for await (const event of parseAnthropicEvents(res.body)) {+ if (event.type === "content_block_start") {+ const block = (event.content_block ?? {}) as Record<string, unknown>;+ if (block.type === "tool_use") {+ const toolId = typeof block.id === "string" ? block.id : "";+ inFlight.set(toolId, {+ name: typeof block.name === "string" ? block.name : "",+ args: "",+ index: toolCalls.length,+ });+ }+ } else if (event.type === "content_block_delta") {+ const delta = (event.delta ?? {}) as Record<string, unknown>;+ if (delta.type === "text_delta" && typeof delta.text === "string") {+ text += delta.text;+ cb.onTextDelta?.(delta.text);+ } else if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {+ const toolId =+ typeof event.index === "number" ? findToolUseIdByIndex(inFlight, event.index) : undefined;+ if (toolId) {+ const entry = inFlight.get(toolId);+ if (entry) {+ entry.args += delta.partial_json;+ }+ }+ }+ } else if (event.type === "content_block_stop") {+ const idx = typeof event.index === "number" ? event.index : -1;+ for (const [toolId, entry] of inFlight) {+ if (entry.index === idx) {+ const call: LlmToolCall = { id: toolId, name: entry.name, arguments: entry.args };+ toolCalls.push(call);+ cb.onToolCall?.(call);+ inFlight.delete(toolId);+ }+ }}- const json = (await res.json()) as {- content?: Array<{ type: string; text?: string; id?: string; name?: string; input?: unknown }>;+ }++ if (!text && toolCalls.length === 0) {+ return { success: false, error: "Empty response from Anthropic." };+ }+ return {+ success: true,+ content: text,+ toolCalls: toolCalls.length ? toolCalls : undefined,+ };+}++function findToolUseIdByIndex(+ inFlight: Map<string, { index: number }>,+ idx: number,+): string | undefined {+ for (const [id, entry] of inFlight) if (entry.index === idx) return id;+ return undefined;+}++function toAnthropicMessage(message: ChatMessage): Record<string, unknown> {+ if (message.role === "tool") {+ return {+ role: "user",+ content: [+ {+ type: "tool_result",+ tool_use_id: message.toolCallId,+ content: message.content,+ },+ ],};- const blocks = json.content ?? [];- const text = blocks- .filter((b) => b.type === "text" && b.text)- .map((b) => b.text)- .join("\n");- const toolCalls = blocks- .filter((b) => b.type === "tool_use" && b.name)- .map((b, index) => ({- id: b.id ?? `toolu_${index}`,- name: b.name ?? "",- arguments: JSON.stringify(b.input ?? {}),- }));- if (!text && toolCalls.length === 0) {- return { success: false, error: "Empty response from Anthropic." };+ }+ if (message.role === "assistant" && message.toolCalls?.length) {+ const blocks: unknown[] = [];+ if (message.content) blocks.push({ type: "text", text: message.content });+ for (const call of message.toolCalls) {+ let input: unknown = {};+ try {+ input = call.arguments ? JSON.parse(call.arguments) : {};+ } catch {+ input = {};+ }+ blocks.push({ type: "tool_use", id: call.id, name: call.name, input });+ }+ return { role: "assistant", content: blocks };+ }+ return { role: message.role, content: message.content };+}++// ─── Codex ──────────────────────────────────────────────────────────────++async function streamCodex(opts: CallLlmOptions, cb: LlmStreamCallbacks): Promise<CallLlmResult> {+ const def = getProviderDefinition("openai-oauth");+ const model = opts.model || def?.defaultModel || "gpt-5.4";+ const baseUrl = (opts.baseUrl || OPENAI_ACCOUNT_BASE_URL).replace(/\/+$/, "");+ const url = `${baseUrl}${CODEX_RESPONSES_PATH}`;++ const headers = buildCodexHeaders(opts, model);+ const body = buildCodexBody(opts, model);++ const res = await fetch(url, {+ method: "POST",+ headers,+ body: JSON.stringify(body),+ signal: opts.signal,+ });+ if (!res.ok || !res.body) {+ const text = await res.text().catch(() => "");+ return {+ success: false,+ error: text+ ? `${res.status} ${res.statusText}: ${text.slice(0, 200)}`+ : `Upstream ${res.status}`,+ };+ }++ let text = "";+ const toolCalls: LlmToolCall[] = [];+ const seen = new Set<string>();+ try {+ for await (const event of consumeCodexStream(res.body)) {+ if (event.kind === "text") {+ text += event.delta;+ cb.onTextDelta?.(event.delta);+ } else if (event.kind === "tool") {+ const tc: CodexToolCallDelta = event.delta;+ if (!seen.has(tc.id)) {+ seen.add(tc.id);+ toolCalls.push({ id: tc.id, name: tc.name, arguments: "" });+ }+ const slot = toolCalls.find((c) => c.id === tc.id)!;+ slot.name = tc.name || slot.name;+ slot.arguments = `${slot.arguments}${tc.args}`;+ } else if (event.kind === "response_id") {+ cb.onResponseId?.(event.id);+ } else if (event.kind === "done") {+ break;+ }}- return { success: true, content: text, toolCalls: toolCalls.length ? toolCalls : undefined };} catch (err) {return { success: false, error: err instanceof Error ? err.message : String(err) };}++ for (const c of toolCalls) cb.onToolCall?.(c);+ if (!text && toolCalls.length === 0) {+ return { success: false, error: "Empty response from Codex." };+ }+ return {+ success: true,+ content: text,+ toolCalls: toolCalls.length ? toolCalls : undefined,+ };+}++function buildCodexHeaders(opts: CallLlmOptions, _model: string): Record<string, string> {+ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ Authorization: `Bearer ${opts.apiKey}`,+ Accept: "text/event-stream",+ originator: "codex_cli_rs",+ "OpenAI-Beta": "responses=experimental",+ "User-Agent": opts.sessionId+ ? `${buildCodexUserAgent()} session/${opts.sessionId}`+ : buildCodexUserAgent(),+ "x-client-request-id": cryptoRandomUuid(),+ "x-codex-window-id": opts.sessionId ?? cryptoRandomUuid(),+ ...(opts.installationId ? { "x-codex-installation-id": opts.installationId } : {}),+ };+ if (opts.accountId) headers["chatgpt-account-id"] = opts.accountId;+ if (opts.sessionId) headers["session_id"] = opts.sessionId;+ return headers;+}++function buildCodexBody(opts: CallLlmOptions, model: string): Record<string, unknown> {+ const conversation = opts.messages.filter((m) => m.role !== "system");+ const system = opts.messages.find((m) => m.role === "system")?.content;++ const reasoningPayload = toCodexReasoningPayload(+ model,+ ((opts.reasoningEffort as never) ?? "medium") as never,+ );++ const body: Record<string, unknown> = {+ model,+ store: false,+ stream: true,+ input: toCodexInput(conversation),+ include: ["reasoning.encrypted_content"],+ parallel_tool_calls: true,+ tool_choice: "auto",+ ...(reasoningPayload ?? {}),+ ...(opts.sessionId ? { session_id: opts.sessionId } : {}),+ };+ if (system) body.instructions = system;+ if (opts.tools?.length) body.tools = toCodexTools(opts.tools);+ return body;+}++// ponytail: minimalist UUID — keeps the Codex identity headers non-uniform without pulling crypto.randomUUID into renderer.+function cryptoRandomUuid(): string {+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();+ // Math.random fallback is acceptable here; the field is just a request id.+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {+ const r = (Math.random() * 16) | 0;+ const v = c === "x" ? r : (r & 0x3) | 0x8;+ return v.toString(16);+ });+}++// ─── Copilot ────────────────────────────────────────────────────────────++async function streamCopilot(opts: CallLlmOptions, cb: LlmStreamCallbacks): Promise<CallLlmResult> {+ const def = getProviderDefinition("copilot-proxy");+ let runtime: { token: string; baseUrl: string };+ try {+ runtime = await exchangeGithubCopilotRuntimeToken(opts.apiKey);+ } catch (err) {+ return { success: false, error: err instanceof Error ? err.message : String(err) };+ }++ const baseUrl = (opts.baseUrl || runtime.baseUrl || def?.baseUrl || "").replace(/\/+$/, "");+ const body: Record<string, unknown> = {+ model: opts.model || def?.defaultModel,+ messages: opts.messages.map(toOpenAiMessage),+ stream: true,+ };+ if (opts.tools?.length) {+ body.tools = opts.tools.map((tool) => ({+ type: "function",+ function: {+ name: tool.name,+ description: tool.description,+ parameters: tool.parameters,+ },+ }));+ }+ const reasoning = getReasoningCallOptions(+ "copilot-proxy",+ opts.model,+ opts.reasoningEffort as never,+ );+ if (reasoning.extraBody) Object.assign(body, reasoning.extraBody);++ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ Authorization: `Bearer ${runtime.token}`,+ Accept: "text/event-stream",+ "User-Agent": "GitHubCopilotChat/0.26.7",+ "Editor-Version": "vscode/1.96.2",+ "Editor-Plugin-Version": "copilot-chat/0.26.7",+ "Openai-Intent": "copilot-gpt-chat-completions",+ };+ if (opts.reasoningEffort && opts.reasoningEffort !== "none") {+ headers["X-Initiator"] = "user";+ }++ const res = await fetch(`${baseUrl}/chat/completions`, {+ method: "POST",+ headers,+ body: JSON.stringify(body),+ signal: opts.signal,+ });+ if (!res.ok || !res.body) {+ return { success: false, error: `Upstream ${res.status} ${res.statusText}` };+ }++ let text = "";+ const toolCalls: OpenAiToolCall[] = [];+ for await (const chunk of parseSse(res.body)) {+ const choice = (chunk.choices?.[0] ?? {}) as Record<string, unknown>;+ const delta = (choice.delta ?? {}) as Record<string, unknown>;+ if (typeof delta.content === "string" && delta.content.length > 0) {+ text += delta.content;+ cb.onTextDelta?.(delta.content);+ }+ for (const d of (delta.tool_calls ?? []) as OpenAiToolCall[])+ accumulateOpenAiToolCall(toolCalls, d);+ }+ const finalCalls: LlmToolCall[] = toolCalls+ .filter((t) => t.function?.name)+ .map((t, i) => ({+ id: t.id ?? `call_${i}`,+ name: t.function?.name ?? "",+ arguments: t.function?.arguments ?? "{}",+ }));+ for (const c of finalCalls) cb.onToolCall?.(c);+ if (!text && finalCalls.length === 0) {+ return { success: false, error: "Empty response from Copilot." };+ }+ return {+ success: true,+ content: text,+ toolCalls: finalCalls.length ? finalCalls : undefined,+ };+}++// ─── Generic SSE / Anthropic event parser ────────────────────────────────++async function* parseSse(+ body: ReadableStream<Uint8Array>,+): AsyncGenerator<{ choices?: Array<Record<string, unknown>>; [k: string]: unknown }> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let idx = buffer.indexOf("\n\n");+ while (idx !== -1) {+ const chunk = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 2);+ const data = chunk+ .split("\n")+ .filter((l) => l.startsWith("data:"))+ .map((l) => l.slice(5).trim())+ .join("\n")+ .trim();+ if (data && data !== "[DONE]") {+ try {+ yield JSON.parse(data) as Record<string, unknown>;+ } catch {+ /* skip malformed */+ }+ }+ idx = buffer.indexOf("\n\n");+ }+ }+}++export async function* parseAnthropicEvents(+ body: ReadableStream<Uint8Array>,+): AsyncGenerator<{ type: string; [k: string]: unknown }> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let idx = buffer.indexOf("\n\n");+ while (idx !== -1) {+ const chunk = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 2);+ const eventLine = chunk.split("\n").find((l) => l.startsWith("event:"));+ const dataLine = chunk+ .split("\n")+ .filter((l) => l.startsWith("data:"))+ .map((l) => l.slice(5).trim())+ .join("\n");+ const eventName = eventLine ? eventLine.slice(6).trim() : "";+ if (dataLine) {+ try {+ const parsed = JSON.parse(dataLine) as Record<string, unknown>;+ yield { ...parsed, type: eventName || parsed.type || "message" } as never;+ } catch {+ /* skip */+ }+ }+ idx = buffer.indexOf("\n\n");+ }+ }}diff --git a/electron/ai-edition/llm-config-store.ts b/electron/ai-edition/llm-config-store.tsindex 287a1afed..3c4fdcbc3 100644--- a/electron/ai-edition/llm-config-store.ts+++ b/electron/ai-edition/llm-config-store.ts@@ -1,9 +1,11 @@// LLM credential + config storage using Electron's safeStorage (OS keychain).// Per locked decision 4: no plain JSON for credentials.//-// ponytail: the config (provider, model, baseUrl, reasoningEffort) lives in-// a plain JSON file; the API keys live in safeStorage-encrypted bytes. Env-// vars override stored keys (same precedence as axcut).+// The shape of the encrypted credentials blob changed from+// `{ [providerId]: string }` to a typed entry per provider so OAuth+// sessions (refresh tokens, account ids, expiries) can ride along with+// plain API keys. Existing single-string rows (pre-OAuth) keep working:+// the loader coerces them to `{ kind: "api-key", apiKey }`.import { readFileSync } from "node:fs";import fs from "node:fs/promises";@@ -20,10 +22,41 @@ export interface LlmConfig {allowAgentEdits?: boolean;}-export interface LlmCredentials {- [providerId: string]: string;+export type LlmCredentialKind = "api-key" | "codex" | "github-device" | "github-pat";++export interface ApiKeyCredential {+ kind: "api-key";+ apiKey: string;+}++export interface CodexCredential {+ kind: "codex";+ apiKey: string; // access token+ refreshToken?: string;+ accountId?: string;+ expiresAt?: number;+}++export interface GithubDeviceCredential {+ kind: "github-device";+ apiKey: string; // github pat/secondary token+ accountLogin?: string;+ expiresAt?: number;}+export interface GithubPatCredential {+ kind: "github-pat";+ apiKey: string; // user-pasted GitHub PAT+}++export type LlmCredential =+ | ApiKeyCredential+ | CodexCredential+ | GithubDeviceCredential+ | GithubPatCredential;++export type LlmCredentials = { [providerId: string]: LlmCredential | string };+export class LlmConfigStore {private readonly configPath: string;private readonly credentialsPath: string;@@ -47,7 +80,7 @@ export class LlmConfigStore {const encrypted = readFileSync(this.credentialsPath);if (safeStorage.isEncryptionAvailable()) {const decrypted = safeStorage.decryptString(encrypted);- this.credentials = JSON.parse(decrypted);+ this.credentials = JSON.parse(decrypted) as LlmCredentials;}} catch {this.credentials = {};@@ -67,24 +100,72 @@ export class LlmConfigStore {await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), "utf8");}- getApiKey(providerId: string, envKeys: string[]): string | null {+ /**+ * Resolves the effective credential for a provider, normalizing older+ * string-only rows to a typed entry. Returns `null` when no credential+ * is available (env vars are the caller's responsibility).+ */+ getCredential(+ providerId: string,+ envKeys: string[] = [],+ ): { value: string; entry: LlmCredential } | null {for (const envKey of envKeys) {const envValue = process.env[envKey];- if (envValue) return envValue;+ if (envValue) {+ const entry: ApiKeyCredential = { kind: "api-key", apiKey: envValue };+ return { value: envValue, entry };+ }+ }+ const stored = this.credentials[providerId];+ if (!stored) return null;+ if (typeof stored === "string") {+ return { value: stored, entry: { kind: "api-key", apiKey: stored } };+ }+ if (+ stored.kind === "api-key" ||+ stored.kind === "codex" ||+ stored.kind === "github-device" ||+ stored.kind === "github-pat"+ ) {+ return { value: stored.apiKey, entry: stored };}- return this.credentials[providerId] ?? null;+ return null;+ }++ /** Back-compat helper used by the chat routing path. Returns just the+ * usable bearer string (any env var OR stored entry). */+ getApiKey(providerId: string, envKeys: string[] = []): string | null {+ return this.getCredential(providerId, envKeys)?.value ?? null;}- async setApiKey(providerId: string, apiKey: string): Promise<void> {- this.credentials[providerId] = apiKey;+ /**+ * Write a typed credential entry for the given provider. Used by both+ * the API-key form (kind = "api-key") and device-flow completion+ * (kind = "codex" / "github-device"). Pass an empty `apiKey` to clear.+ */+ async setCredential(providerId: string, entry: LlmCredential): Promise<void> {+ if (!entry.apiKey) {+ delete this.credentials[providerId];+ } else {+ this.credentials[providerId] = entry;+ }await this.saveCredentials();}- async removeApiKey(providerId: string): Promise<void> {+ async removeCredential(providerId: string): Promise<void> {delete this.credentials[providerId];await this.saveCredentials();}+ /**+ * Convenience: clear every credential and forget the active provider+ * from `LlmConfig` (caller's job). Used by `llmDisconnect` in the IPC service.+ */+ async clearAll(): Promise<void> {+ this.credentials = {};+ await this.saveCredentials();+ }+private async saveCredentials(): Promise<void> {if (!safeStorage.isEncryptionAvailable()) {throw new Error("safeStorage is not available on this platform.");diff --git a/electron/ai-edition/llm-provider-auth.test.ts b/electron/ai-edition/llm-provider-auth.test.tsnew file mode 100644index 000000000..bb5e25b6b--- /dev/null+++ b/electron/ai-edition/llm-provider-auth.test.ts@@ -0,0 +1,276 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ beginCodexDeviceAuth,+ beginGithubDeviceAuth,+ completeCodexDeviceAuth,+ completeGithubDeviceAuth,+ exchangeGithubCopilotRuntimeToken,+ listGithubCopilotModels,+ listOpenAiAccountModels,+} from "./llm-provider-auth";++const ORIGINAL_FETCH = globalThis.fetch;++function mockFetchSequence(+ responses: Array<{ ok: boolean; status?: number; body: unknown; delayMs?: number }>,+) {+ const queue = [...responses];+ vi.spyOn(globalThis, "fetch").mockImplementation(async () => {+ const next = queue.shift();+ if (!next) throw new Error("mock fetch: no response queued");+ const init = next.delayMs ? await new Promise<void>((r) => setTimeout(r, next.delayMs)) : null;+ void init;+ const status = next.status ?? (next.ok ? 200 : 500);+ return new Response(JSON.stringify(next.body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+ });+}++afterEach(() => {+ vi.restoreAllMocks();+ globalThis.fetch = ORIGINAL_FETCH;+});++describe("beginCodexDeviceAuth", () => {+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ });++ it("POSTs to the Codex usercode endpoint and returns a normalized challenge", async () => {+ mockFetchSequence([+ {+ ok: true,+ body: {+ device_auth_id: "codex-id-abc",+ user_code: "ABCD-EFGH",+ interval: "7",+ expires_in: 900,+ },+ },+ ]);++ const challenge = await beginCodexDeviceAuth();++ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ const [url, init] = (globalThis.fetch as unknown as { mock: { calls: [unknown, unknown][] } })+ .mock.calls[0]!;+ expect(url).toBe("https://auth.openai.com/api/accounts/deviceauth/usercode");+ expect(init).toMatchObject({ method: "POST" });++ expect(challenge.userCode).toBe("ABCD-EFGH");+ expect(challenge.deviceAuthId).toBe("codex-id-abc");+ expect(challenge.verificationUri).toBe("https://auth.openai.com/codex/device");+ expect(challenge.intervalMs).toBe(7000);+ expect(challenge.expiresAt).toBeGreaterThan(Date.now() + 100_000);+ });+});++describe("completeCodexDeviceAuth", () => {+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ });++ it("exchanges the device code for tokens via OAuth token endpoint", async () => {+ mockFetchSequence([+ {+ ok: true,+ body: { authorization_code: "auth-code-1", code_verifier: "verifier-1" },+ },+ {+ ok: true,+ body: {+ access_token: "eyJhbGciOiJIUzI1NiJ9.payload.signature",+ refresh_token: "rt-1",+ expires_in: 3600,+ },+ },+ ]);++ const tokens = await completeCodexDeviceAuth({+ deviceAuthId: "codex-id",+ userCode: "USER",+ intervalMs: 10,+ expiresAt: Date.now() + 60_000,+ });++ expect(tokens.accessToken).toMatch(/^eyJ/);+ expect(tokens.refreshToken).toBe("rt-1");+ expect(tokens.expiresAt).toBeGreaterThan(Date.now());+ });++ it("throws when the device code expires", async () => {+ mockFetchSequence([{ ok: false, status: 403, body: { error: "expired_token" } }]);++ await expect(+ completeCodexDeviceAuth({+ deviceAuthId: "id",+ userCode: "code",+ intervalMs: 1,+ expiresAt: Date.now() - 1,+ }),+ ).rejects.toThrow(/expired/);+ });+});++describe("beginGithubDeviceAuth", () => {+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ });++ it("POSTs to GitHub /login/device/code with client_id and read:user scope", async () => {+ mockFetchSequence([+ {+ ok: true,+ body: {+ device_code: "gh-device-1",+ user_code: "GH-USER",+ verification_uri: "https://github.com/login/device",+ interval: 5,+ expires_in: 900,+ },+ },+ ]);++ const challenge = await beginGithubDeviceAuth();++ const [url, init] = (globalThis.fetch as unknown as { mock: { calls: [unknown, unknown][] } })+ .mock.calls[0]!;+ expect(url).toBe("https://github.com/login/device/code");+ expect(init).toMatchObject({ method: "POST" });++ const fetchBody = (init as RequestInit).body as URLSearchParams;+ expect(fetchBody.get("client_id")).toBe("Iv1.b507a08c87ecfe98");+ expect(fetchBody.get("scope")).toBe("read:user");++ expect(challenge.userCode).toBe("GH-USER");+ expect(challenge.deviceCode).toBe("gh-device-1");+ });++ it("falls back to the GitHub login URL when the server omits verification_uri", async () => {+ mockFetchSequence([+ {+ ok: true,+ body: {+ device_code: "d-2",+ user_code: "X",+ interval: 5,+ expires_in: 900,+ },+ },+ ]);++ const challenge = await beginGithubDeviceAuth();+ expect(challenge.verificationUri).toBe("https://github.com/login/device");+ });+});++describe("completeGithubDeviceAuth", () => {+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ });++ it("returns the access token on the first poll", async () => {+ mockFetchSequence([{ ok: true, body: { access_token: "ghp_token_1" } }]);++ const token = await completeGithubDeviceAuth({+ deviceCode: "d-1",+ userCode: "U",+ intervalMs: 1,+ expiresAt: Date.now() + 60_000,+ });+ expect(token).toBe("ghp_token_1");+ });++ it("throws an error for non-pending failures", async () => {+ mockFetchSequence([+ { ok: true, body: { error: "access_denied", error_description: "User rejected" } },+ ]);++ await expect(+ completeGithubDeviceAuth({+ deviceCode: "d-3",+ userCode: "U",+ intervalMs: 1,+ expiresAt: Date.now() + 60_000,+ }),+ ).rejects.toThrow(/User rejected/);+ });+});++describe("exchangeGithubCopilotRuntimeToken", () => {+ it("exchanges the long-lived GitHub PAT for the short-lived Copilot bearer", async () => {+ mockFetchSequence([+ {+ ok: true,+ body: {+ token: "tid=copilot;exp=2026",+ expires_at: Math.floor(Date.now() / 1000) + 1800,+ },+ },+ ]);++ const out = await exchangeGithubCopilotRuntimeToken("ghp_x");+ expect(out.token).toMatch(/^tid=copilot;exp=/);+ expect(out.expiresAt).toBeGreaterThan(Date.now());+ expect(out.baseUrl).toBe("https://api.individual.githubcopilot.com");+ });+});++describe("listOpenAiAccountModels", () => {+ const jwtForAccount = (accountId: string): string => {+ const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");+ const payload = Buffer.from(+ JSON.stringify({+ "https://api.openai.com/auth": { chatgpt_account_id: accountId },+ }),+ ).toString("base64url");+ return `${header}.${payload}.signature`;+ };++ it("returns the slug list visible to the account, sorted by priority", async () => {+ mockFetchSequence([+ {+ ok: true,+ body: {+ models: [+ { slug: "gpt-5.4", visibility: "list", priority: 10 },+ { slug: "gpt-4o", visibility: "list", priority: 1 },+ { slug: "secret", visibility: "private" },+ { slug: "internal", visibility: "hidden" },+ ],+ },+ },+ ]);++ const models = await listOpenAiAccountModels(jwtForAccount("acc-1"));+ expect(models).toEqual(["gpt-4o", "gpt-5.4"]);+ });+});++describe("listGithubCopilotModels", () => {+ it("exchanges the PAT, lists the Copilot catalog, and sorts alphabetically", async () => {+ // 1) Copilot token exchange+ // 2) GET {baseUrl}/models+ mockFetchSequence([+ {+ ok: true,+ body: {+ token: "copilot-bearer",+ expires_at: Math.floor(Date.now() / 1000) + 1800,+ },+ },+ {+ ok: true,+ body: {+ data: [{ id: "gpt-4o" }, { id: "claude-3.5-sonnet" }, { id: "gpt-3.5-turbo" }],+ },+ },+ ]);++ const models = await listGithubCopilotModels("ghp_x");+ expect(models).toEqual(["claude-3.5-sonnet", "gpt-3.5-turbo", "gpt-4o"]);+ });+});diff --git a/electron/ai-edition/llm-provider-auth.ts b/electron/ai-edition/llm-provider-auth.tsnew file mode 100644index 000000000..49e41ed9e--- /dev/null+++ b/electron/ai-edition/llm-provider-auth.ts@@ -0,0 +1,453 @@+// Device-flow + GitHub Copilot runtime-token helpers for the AI provider+// feature. Ported from axcut (apps/server/src/llm/provider-runtime/openai-account.ts,+// copilot-account.ts, and the inline functions in services/llm-config-service.ts).+//+// Credentials returned by `complete*` flows land in the same+// `safeStorage` blob as API keys via `LlmConfigStore`. No plain-text auth+// files on disk.+//+// Endpoints are not proxied through OpenScreen itself — the Electron+// main process has direct internet access via `app.requestSingleInstanceLock`.++export interface CodexDeviceChallenge {+ verificationUri: string;+ verificationUriComplete?: string;+ userCode: string;+ deviceAuthId: string;+ intervalMs: number;+ expiresAt: number;+}++export interface GithubDeviceChallenge {+ verificationUri: string;+ userCode: string;+ deviceCode: string;+ intervalMs: number;+ expiresAt: number;+}++export interface CodexTokens {+ accessToken: string;+ refreshToken?: string;+ idToken?: string;+ expiresAt?: number;+ accountId?: string;+}++export interface GithubCopilotRuntimeToken {+ token: string;+ expiresAt: number;+ baseUrl: string;+}++const CODEX_ISSUER = "https://auth.openai.com";+const CODEX_TOKEN_ENDPOINT = `${CODEX_ISSUER}/oauth/token`;+const CODEX_DEVICE_AUTHORIZATION_ENDPOINT = `${CODEX_ISSUER}/api/accounts/deviceauth/usercode`;+const CODEX_DEVICE_TOKEN_ENDPOINT = `${CODEX_ISSUER}/api/accounts/deviceauth/token`;+const CODEX_DEVICE_REDIRECT_URI = `${CODEX_ISSUER}/deviceauth/callback`;+const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";+const CODEX_DEVICE_POLLING_SAFETY_MARGIN_MS = 3_000;+export const OPENAI_ACCOUNT_BASE_URL = "https://chatgpt.com/backend-api";+const CODEX_MODELS_PATH = "/codex/models";+const GITHUB_DEVICE_CODE_ENDPOINT = "https://github.com/login/device/code";+const GITHUB_DEVICE_TOKEN_ENDPOINT = "https://github.com/login/oauth/access_token";+const GITHUB_DEVICE_CLIENT_ID = "Iv1.b507a08c87ecfe98";+const GITHUB_DEVICE_SCOPE = "read:user";+const GITHUB_DEVICE_POLLING_SAFETY_MARGIN_MS = 3_000;+const COPILOT_TOKEN_ENDPOINT = "https://api.github.com/copilot_internal/v2/token";+const GITHUB_COPILOT_USER_AGENT = "GitHubCopilotChat/0.26.7";+const GITHUB_COPILOT_EDITOR_VERSION = "vscode/1.96.2";+const GITHUB_COPILOT_PLUGIN_VERSION = "copilot-chat/0.26.7";++/**+ * Begin the Codex (ChatGPT) device flow. Returns the user code and the+ * polling parameters needed by {@link completeCodexDeviceAuth}.+ */+export async function beginCodexDeviceAuth(): Promise<CodexDeviceChallenge> {+ const response = await fetch(CODEX_DEVICE_AUTHORIZATION_ENDPOINT, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ client_id: CODEX_CLIENT_ID }),+ });++ if (!response.ok) {+ const detail = await safeErrorDetail(response);+ throw new Error(+ detail+ ? `OpenAI device login failed: ${detail}`+ : `OpenAI device login failed: HTTP ${response.status}`,+ );+ }++ const payload = (await response.json()) as {+ device_auth_id?: string;+ user_code?: string;+ interval?: string;+ expires_in?: number;+ };++ if (!payload.device_auth_id || !payload.user_code) {+ throw new Error("OpenAI device login returned an incomplete challenge.");+ }++ const intervalSeconds = Number.parseInt(payload.interval ?? "5", 10);+ const intervalMs = Math.max(Number.isFinite(intervalSeconds) ? intervalSeconds : 5, 1) * 1000;++ return {+ verificationUri: `${CODEX_ISSUER}/codex/device`,+ userCode: payload.user_code,+ deviceAuthId: payload.device_auth_id,+ intervalMs,+ expiresAt: Date.now() + (payload.expires_in ?? 600) * 1000,+ };+}++/**+ * Poll the Codex device-token endpoint until we get an authorization code,+ * exchange it at the OAuth token endpoint, and return the access + refresh+ * tokens. The caller persists them via `LlmConfigStore.setCredential`.+ */+export async function completeCodexDeviceAuth(+ challenge: Omit<CodexDeviceChallenge, "verificationUri" | "verificationUriComplete">,+): Promise<CodexTokens> {+ const intervalMs = Math.max(1000, challenge.intervalMs);++ while (Date.now() < challenge.expiresAt) {+ const response = await fetch(CODEX_DEVICE_TOKEN_ENDPOINT, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ device_auth_id: challenge.deviceAuthId,+ user_code: challenge.userCode,+ }),+ });++ if (response.ok) {+ const deviceToken = (await response.json()) as {+ authorization_code?: string;+ code_verifier?: string;+ };++ if (!deviceToken.authorization_code || !deviceToken.code_verifier) {+ throw new Error("OpenAI device login returned an incomplete authorization result.");+ }++ const body = new URLSearchParams();+ body.set("grant_type", "authorization_code");+ body.set("code", deviceToken.authorization_code);+ body.set("redirect_uri", CODEX_DEVICE_REDIRECT_URI);+ body.set("client_id", CODEX_CLIENT_ID);+ body.set("code_verifier", deviceToken.code_verifier);++ const tokenResponse = await fetch(CODEX_TOKEN_ENDPOINT, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: body.toString(),+ });++ if (!tokenResponse.ok) {+ const detail = await safeErrorDetail(tokenResponse);+ throw new Error(+ detail+ ? `OpenAI token exchange failed: ${detail}`+ : `OpenAI token exchange failed: HTTP ${tokenResponse.status}`,+ );+ }++ const tokens = (await tokenResponse.json()) as {+ access_token?: string;+ refresh_token?: string;+ id_token?: string;+ expires_in?: number;+ };++ if (!tokens.access_token) {+ throw new Error("OpenAI device login returned no access_token.");+ }++ const expiresAt = tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined;++ return {+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token,+ idToken: tokens.id_token,+ expiresAt,+ accountId: extractChatgptAccountId(tokens.access_token, tokens.id_token),+ };+ }++ if (response.status !== 403 && response.status !== 404) {+ const detail = await safeErrorDetail(response);+ throw new Error(detail || `OpenAI device flow failed: HTTP ${response.status}`);+ }++ await delay(intervalMs + CODEX_DEVICE_POLLING_SAFETY_MARGIN_MS);+ }++ throw new Error("OpenAI device code expired. Retry setup.");+}++/**+ * Begin the GitHub Device Flow. Same shape as {@link beginCodexDeviceAuth}+ * but the next step is {@link completeGithubDeviceAuth}, which returns+ * a Copilot-personal-access-token-style string stored as the user's+ * GitHub PAT against the `copilot-proxy` provider.+ */+export async function beginGithubDeviceAuth(): Promise<GithubDeviceChallenge> {+ const response = await fetch(GITHUB_DEVICE_CODE_ENDPOINT, {+ method: "POST",+ headers: {+ Accept: "application/json",+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({ client_id: GITHUB_DEVICE_CLIENT_ID, scope: GITHUB_DEVICE_SCOPE }),+ });++ if (!response.ok) {+ throw new Error(`GitHub device code failed: HTTP ${response.status}`);+ }++ const payload = (await response.json()) as Record<string, unknown>;+ const verificationUri =+ typeof payload.verification_uri === "string"+ ? payload.verification_uri+ : "https://github.com/login/device";+ const userCode = typeof payload.user_code === "string" ? payload.user_code : "";+ const deviceCode = typeof payload.device_code === "string" ? payload.device_code : "";+ const intervalSeconds = Number(payload.interval ?? 5);+ const expiresInSeconds = Number(payload.expires_in ?? 900);++ if (!userCode || !deviceCode) {+ throw new Error("GitHub device code returned an incomplete challenge.");+ }++ return {+ verificationUri,+ userCode,+ deviceCode,+ intervalMs: Math.max(1000, Number.isFinite(intervalSeconds) ? intervalSeconds * 1000 : 5_000),+ expiresAt: Date.now() + (Number.isFinite(expiresInSeconds) ? expiresInSeconds : 900) * 1000,+ };+}++/**+ * Poll the GitHub access-token endpoint and return the PAT. Axcut's+ * `copilot-account.ts` is a thin wrapper around the same `completeGitHubDeviceAuth`,+ * which is what we expose here.+ */+export async function completeGithubDeviceAuth(+ challenge: Omit<GithubDeviceChallenge, "verificationUri">,+): Promise<string> {+ while (Date.now() < challenge.expiresAt) {+ const response = await fetch(GITHUB_DEVICE_TOKEN_ENDPOINT, {+ method: "POST",+ headers: {+ Accept: "application/json",+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({+ client_id: GITHUB_DEVICE_CLIENT_ID,+ device_code: challenge.deviceCode,+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",+ }),+ });++ const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>;+ const accessToken = typeof payload.access_token === "string" ? payload.access_token : "";+ if (accessToken) {+ return accessToken;+ }++ const error = typeof payload.error === "string" ? payload.error : "";+ if (error && error !== "authorization_pending" && error !== "slow_down") {+ const description =+ typeof payload.error_description === "string" ? payload.error_description : error;+ throw new Error(description);+ }++ await delay(challenge.intervalMs + GITHUB_DEVICE_POLLING_SAFETY_MARGIN_MS);+ }++ throw new Error("GitHub device login expired.");+}++/**+ * Exchange a long-lived GitHub PAT (or OAuth-derived token) for the+ * short-lived Copilot API bearer used to call the models endpoint.+ * Caller is responsible for caching this; we do not persist the+ * Copilot runtime token here.+ */+export async function exchangeGithubCopilotRuntimeToken(+ githubToken: string,+): Promise<GithubCopilotRuntimeToken> {+ const response = await fetch(COPILOT_TOKEN_ENDPOINT, {+ method: "GET",+ headers: {+ Accept: "application/json",+ Authorization: `Bearer ${githubToken}`,+ "User-Agent": "GitHubCopilotChat/0.26.7",+ },+ });++ if (!response.ok) {+ throw new Error(`Copilot token exchange failed: HTTP ${response.status}`);+ }++ const payload = (await response.json()) as {+ token?: string;+ expires_at?: number;+ expires_in?: number;+ };+ if (!payload.token) {+ throw new Error("Copilot token exchange returned no token.");+ }++ const expiresAt =+ typeof payload.expires_at === "number"+ ? payload.expires_at * 1000+ : Date.now() + (typeof payload.expires_in === "number" ? payload.expires_in : 300) * 1000;++ return {+ token: payload.token,+ expiresAt,+ baseUrl: deriveCopilotApiBaseUrl(payload.token) ?? "https://api.individual.githubcopilot.com",+ };+}++function deriveCopilotApiBaseUrl(token: string): string | undefined {+ try {+ const [, payload] = token.split(".");+ if (!payload) return undefined;+ const json = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as {+ endpoints?: { api?: string };+ };+ const api = json.endpoints?.api;+ return typeof api === "string" ? api : undefined;+ } catch {+ return undefined;+ }+}++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++/**+ * Fetch the model list for an already-authenticated ChatGPT (Codex) account.+ * Returns the slug list visible to the account, sorted by ascending priority.+ * On any error, returns an empty list (the caller should fall back to the+ * default model in the form).+ */+export async function listOpenAiAccountModels(accessToken: string): Promise<string[]> {+ const headers: Record<string, string> = {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ };+ try {+ const accountId = extractChatgptAccountId(accessToken);+ if (accountId) headers["chatgpt-account-id"] = accountId;+ } catch {+ // best effort+ }++ const response = await fetch(+ `${OPENAI_ACCOUNT_BASE_URL}${CODEX_MODELS_PATH}?client_version=1.0.0`,+ {+ headers,+ },+ );++ if (!response.ok) {+ throw new Error(`Codex model discovery failed: HTTP ${response.status}`);+ }++ const data = (await response.json()) as {+ models?: Array<{+ slug?: string;+ visibility?: string;+ supported_in_api?: boolean;+ priority?: number;+ }>;+ };++ return (data.models ?? [])+ .filter((model) => typeof model.slug === "string" && model.slug!.trim().length > 0)+ .filter((model) => (model.visibility ?? "list") === "list")+ .sort(+ (left, right) =>+ (left.priority ?? Number.MAX_SAFE_INTEGER) - (right.priority ?? Number.MAX_SAFE_INTEGER),+ )+ .map((model) => model.slug!.trim());+}++/**+ * Fetch the model list for an already-authenticated GitHub Copilot account.+ * Exchanges the stored PAT for a short-lived Copilot API bearer, then calls+ * `{baseUrl}/models`. The result is sorted alphabetically for stable rendering.+ */+export async function listGithubCopilotModels(githubToken: string): Promise<string[]> {+ const runtime = await exchangeGithubCopilotRuntimeToken(githubToken);+ const response = await fetch(`${runtime.baseUrl}/models`, {+ headers: {+ Authorization: `Bearer ${runtime.token}`,+ Accept: "application/json",+ "User-Agent": GITHUB_COPILOT_USER_AGENT,+ "Editor-Version": GITHUB_COPILOT_EDITOR_VERSION,+ "Editor-Plugin-Version": GITHUB_COPILOT_PLUGIN_VERSION,+ },+ });++ if (!response.ok) {+ throw new Error(`Copilot model discovery failed: HTTP ${response.status}`);+ }++ const payload = (await response.json()) as { data?: Array<{ id?: string }> };+ return (payload.data ?? [])+ .map((entry) => entry.id?.trim() ?? "")+ .filter((id) => id.length > 0)+ .sort((left, right) => left.localeCompare(right));+}++async function safeErrorDetail(response: Response): Promise<string | undefined> {+ try {+ const data = (await response.json()) as {+ error?: string;+ error_description?: string;+ message?: string;+ };+ return data.error_description ?? data.message ?? data.error;+ } catch {+ try {+ return (await response.text()).trim() || undefined;+ } catch {+ return undefined;+ }+ }+}++/**+ * Pull the `chatgpt_account_id` claim from a ChatGPT JWT (access token or+ * id token). Returns undefined if the claim is missing — model discovery+ * then omits the `chatgpt-account-id` header.+ */+export function extractChatgptAccountId(accessToken: string, idToken?: string): string | undefined {+ for (const token of [accessToken, idToken ?? ""]) {+ if (!token) continue;+ const segments = token.split(".");+ if (segments.length !== 3) continue;+ try {+ const json = Buffer.from(segments[1]!, "base64").toString("utf8");+ const payload = JSON.parse(json) as Record<string, unknown>;+ const claim = payload["https://api.openai.com/auth"];+ if (claim && typeof claim === "object") {+ const accountId = (claim as Record<string, unknown>).chatgpt_account_id;+ if (typeof accountId === "string" && accountId) {+ return accountId;+ }+ }+ } catch {+ // fall through and try next token+ }+ }+ return undefined;+}diff --git a/electron/ai-edition/provider-registry.ts b/electron/ai-edition/provider-registry.tsindex b9f458f08..4e8a59eec 100644--- a/electron/ai-edition/provider-registry.ts+++ b/electron/ai-edition/provider-registry.ts@@ -1,9 +1,10 @@// Provider definitions for the AI features layer. Static data — no runtime// deps. Mirrors axcut's apps/server/src/llm/provider-registry.ts.//-// ponytail: the full provider set (10 providers in axcut). Each entry carries-// enough metadata for the ProviderSettingsDialog to render without hitting the-// network. Actual model creation (create-chat-model) needs @langchain/* deps.+// Each entry carries enough metadata for the ProviderSettingsDialog to render+// without hitting the network. Default model + base URL reflect axcut's+// current defaults (Gemini uses the OpenAI-compatible /v1beta/openai base so+// it shares the OpenAI wire path).export interface ProviderDefinition {id: string;@@ -11,6 +12,12 @@ export interface ProviderDefinition {defaultModel: string;authKind: "api-key" | "oauth-device" | "pat";supportsReasoningEffort: boolean;+ /** True when this provider always requires the user to enter a base URL+ * (e.g. openai-compatible). False when the default is implicit. */+ requiresBaseUrl?: boolean;+ /** Free-text guidance shown beneath the form when a user picks this+ * provider — mirrors axcut's `setupHint`. */+ setupHint?: string;envKeys: string[];baseUrl?: string;}@@ -22,7 +29,8 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [defaultModel: "claude-haiku-4-5",authKind: "api-key",supportsReasoningEffort: true,- envKeys: ["ANTHROPIC_API_KEY"],+ envKeys: ["ANTHROPIC_LLM_API_KEY", "ANTHROPIC_API_KEY"],+ setupHint: "Use ANTHROPIC_API_KEY or paste a Claude API key.",},{id: "openai",@@ -30,15 +38,28 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [defaultModel: "gpt-4o",authKind: "api-key",supportsReasoningEffort: true,- envKeys: ["OPENAI_API_KEY"],+ baseUrl: "https://api.openai.com/v1",+ envKeys: ["OPENAI_LLM_API_KEY", "OPENAI_API_KEY"],+ setupHint: "Use OPENAI_API_KEY or paste an OpenAI API key.",},{id: "google",label: "Gemini API",- defaultModel: "gemini-2.5-flash",+ defaultModel: "gemini-3-flash-preview",+ // Gemini is wired through the OpenAI-compatible base so it shares the+ // same code path as OpenAI/OpenRouter. (`.../v1beta` is Google's+ // native Gemini endpoint and uses a different wire format.)+ baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",authKind: "api-key",supportsReasoningEffort: true,- envKeys: ["GEMINI_API_KEY", "GOOGLE_API_KEY"],+ envKeys: [+ "GOOGLE_GENERATIVE_AI_API_KEY",+ "GEMINI_API_KEY",+ "GOOGLE_API_KEY",+ "GEMINI_LLM_API_KEY",+ "GOOGLE_LLM_API_KEY",+ ],+ setupHint: "Use GOOGLE_GENERATIVE_AI_API_KEY, GEMINI_API_KEY, or paste a Gemini API key.",},{id: "mistral",@@ -46,42 +67,149 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [defaultModel: "mistral-large-latest",authKind: "api-key",supportsReasoningEffort: false,- envKeys: ["MISTRAL_API_KEY"],+ baseUrl: "https://api.mistral.ai/v1",+ envKeys: ["MISTRAL_LLM_API_KEY", "MISTRAL_API_KEY"],+ setupHint: "Use MISTRAL_API_KEY or paste a Mistral API key.",},{id: "openrouter",- label: "OpenRouter",+ label: "OpenRouter API",defaultModel: "anthropic/claude-3.5-sonnet",authKind: "api-key",supportsReasoningEffort: true,- envKeys: ["OPENROUTER_API_KEY"],baseUrl: "https://openrouter.ai/api/v1",- },- {- id: "openai-compatible",- label: "OpenAI-compatible endpoint",- defaultModel: "",- authKind: "api-key",- supportsReasoningEffort: false,- envKeys: ["OPENAI_COMPATIBLE_API_KEY"],+ envKeys: ["OPENROUTER_LLM_API_KEY", "OPENROUTER_API_KEY"],+ setupHint: "Use OPENROUTER_API_KEY or paste an OpenRouter API key.",},{id: "openai-oauth",label: "ChatGPT (OAuth)",- defaultModel: "gpt-4o",+ defaultModel: "gpt-5.4",authKind: "oauth-device",supportsReasoningEffort: true,envKeys: [],+ baseUrl: "https://chatgpt.com/backend-api",+ setupHint: "Connect a ChatGPT account with the device login flow.",},{id: "copilot-proxy",label: "GitHub Copilot",- defaultModel: "gpt-4o",+ defaultModel: "gpt-4.1",authKind: "pat",supportsReasoningEffort: true,- envKeys: ["GITHUB_TOKEN", "GH_TOKEN"],+ envKeys: ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"],+ baseUrl: "https://api.individual.githubcopilot.com",+ setupHint: "Use a GitHub Copilot token or connect with the device login flow.",+ },+ {+ id: "minimax",+ label: "MiniMax API",+ defaultModel: "MiniMax-M2.7",+ authKind: "api-key",+ supportsReasoningEffort: true,+ baseUrl: "https://api.minimax.io/anthropic",+ envKeys: ["MINIMAX_API_KEY"],+ setupHint: "Use MINIMAX_API_KEY or paste a MiniMax API key.",+ },+ {+ id: "minimax-token-plan",+ label: "MiniMax Token Plan",+ defaultModel: "MiniMax-M2.7",+ authKind: "api-key",+ supportsReasoningEffort: true,+ baseUrl: "https://api.minimax.io/anthropic",+ envKeys: ["MINIMAX_TOKEN_PLAN_API_KEY"],+ setupHint: "Use MINIMAX_TOKEN_PLAN_API_KEY or paste a MiniMax token-plan API key.",+ },+ {+ id: "openai-compatible",+ label: "OpenAI Compatible",+ defaultModel: "",+ authKind: "api-key",+ requiresBaseUrl: true,+ supportsReasoningEffort: false,+ envKeys: ["OPENAI_COMPATIBLE_API_KEY"],+ setupHint: "Use a custom OpenAI-compatible base URL.",},];-export const REASONING_EFFORT_OPTIONS = ["none", "minimal", "low", "medium", "high"] as const;+export const REASONING_EFFORT_OPTIONS = [+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+] as const;export type ReasoningEffort = (typeof REASONING_EFFORT_OPTIONS)[number];++/**+ * Coerce free-form provider strings (including historical aliases and the+ * legacy `yagr` ids) to a known registry entry. Mirrors axcut's+ * `normalizeProviderId`.+ */+export function normalizeProviderId(provider?: string): string | undefined {+ const normalized = provider?.trim().toLowerCase();+ if (!normalized) return undefined;+ if (normalized === "claude") return "anthropic";+ if (normalized === "anthropic-proxy") return "anthropic";+ if (normalized === "gemini") return "google";+ const def = PROVIDER_DEFINITIONS.find((p) => p.id === normalized);+ return def?.id;+}++export function getProviderDefinition(id: string): ProviderDefinition | undefined {+ return PROVIDER_DEFINITIONS.find((p) => p.id === id);+}++/**+ * ponytail: minimal-effort aliases collapse to `low` for strategies that+ * don't expose `minimal`; `xhigh` collapses to `high`. Mirrors axcut's+ * `normalizeReasoningEffortForCapability`. Use after picking a strategy.+ */+const OPENAI_REASONING_EFFORTS: readonly ReasoningEffort[] = ["none", "low", "medium", "high"];+const ANTHROPIC_REASONING_EFFORTS: readonly ReasoningEffort[] = [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+];+const OPENROUTER_REASONING_EFFORTS: readonly ReasoningEffort[] = ["none", "low", "medium", "high"];+const GOOGLE_REASONING_EFFORTS: readonly ReasoningEffort[] = ["none", "low", "medium", "high"];++export function normalizeReasoningEffort(+ effort: ReasoningEffort | undefined,+ strategy:+ | "openai-responses"+ | "anthropic-thinking"+ | "openrouter-reasoning"+ | "google-thinking"+ | "custom-openai-account"+ | "none",+): ReasoningEffort | undefined {+ if (strategy === "none") return undefined;+ if (!effort) return "medium";+ if (effort === "minimal") {+ return [+ "openai-responses",+ "anthropic-thinking",+ "openrouter-reasoning",+ "google-thinking",+ ].includes(strategy)+ ? "low"+ : "medium";+ }+ if (effort === "xhigh") {+ return strategy === "anthropic-thinking" ? "xhigh" : "high";+ }+ const supported =+ strategy === "openai-responses"+ ? OPENAI_REASONING_EFFORTS+ : strategy === "anthropic-thinking"+ ? ANTHROPIC_REASONING_EFFORTS+ : strategy === "openrouter-reasoning"+ ? OPENROUTER_REASONING_EFFORTS+ : GOOGLE_REASONING_EFFORTS;+ return supported.includes(effort) ? effort : "medium";+}diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.tsindex 2afaac7bb..7a80c638c 100644--- a/electron/ipc/nativeBridge.ts+++ b/electron/ipc/nativeBridge.ts@@ -335,6 +335,33 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {requestId,await aiEditionService.llmRemoveApiKey(request.payload.providerId),);+ case "llm.beginDeviceAuth":+ return createSuccessResponse(+ requestId,+ await aiEditionService.llmBeginDeviceAuth(+ request.payload.providerId,+ request.payload.model,+ ),+ );+ case "llm.completeDeviceAuth":+ return createSuccessResponse(+ requestId,+ await aiEditionService.llmCompleteDeviceAuth(+ request.payload.providerId,+ request.payload.challenge,+ request.payload.model,+ ),+ );+ case "llm.disconnect":+ return createSuccessResponse(+ requestId,+ await aiEditionService.llmDisconnect(request.payload.providerId),+ );+ case "llm.listProviderModels":+ return createSuccessResponse(+ requestId,+ await aiEditionService.llmListProviderModels(request.payload.providerId),+ );case "chat.run":return createSuccessResponse(requestId,@@ -409,6 +436,19 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {request.payload.sessionId,),);+ case "chat.budget":+ return createSuccessResponse(+ requestId,+ aiEditionService.chatBudget(request.payload.projectId, request.payload.sessionId),+ );+ case "chat.compact":+ return createSuccessResponse(+ requestId,+ await aiEditionService.chatCompact(+ request.payload.projectId,+ request.payload.sessionId,+ ),+ );default:return createErrorResponse(requestId,diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.tsindex b08f6d4dd..46494acbb 100644--- a/electron/native-bridge/services/aiEditionService.ts+++ b/electron/native-bridge/services/aiEditionService.ts@@ -1,17 +1,31 @@import { documentSchema } from "../../../src/lib/ai-edition/schema";import type {AiEditionAssetResult,+ AiEditionChatBudget,+ AiEditionChatCompactResult,AiEditionChatMessage,AiEditionChatResult,AiEditionChatSession,AiEditionChatSessionSummary,+ AiEditionDeviceChallenge,+ AiEditionDeviceCompletionResult,AiEditionDocumentResult,AiEditionLlmConfig,+ AiEditionLlmDisconnectResult,AiEditionLlmSnapshot,AiEditionProjectSummary,} from "../../../src/native/contracts";+import { compactSession, getSessionBudget } from "../../ai-edition/chat-service";import type { DocumentService } from "../../ai-edition/document-service";-import type { LlmConfigStore } from "../../ai-edition/llm-config-store";+import type { LlmConfigStore, LlmCredential } from "../../ai-edition/llm-config-store";+import {+ beginCodexDeviceAuth,+ beginGithubDeviceAuth,+ completeCodexDeviceAuth,+ completeGithubDeviceAuth,+ listGithubCopilotModels,+ listOpenAiAccountModels,+} from "../../ai-edition/llm-provider-auth";import { PROVIDER_DEFINITIONS } from "../../ai-edition/provider-registry";export interface AiEditionServiceOptions {@@ -107,10 +121,18 @@ export class AiEditionService {async llmGetSnapshot(): Promise<AiEditionLlmSnapshot> {const config = this.options.llmConfig.getConfig();+ const credentialSummary: AiEditionLlmSnapshot["credentialSummary"] = [];const connectedProviders: string[] = [];for (const def of PROVIDER_DEFINITIONS) {- const key = this.options.llmConfig.getApiKey(def.id, def.envKeys);- if (key) connectedProviders.push(def.id);+ const resolved = this.options.llmConfig.getCredential(def.id, def.envKeys);+ const connected = Boolean(resolved);+ if (connected) connectedProviders.push(def.id);+ credentialSummary.push({+ providerId: def.id,+ connected,+ authKind: def.authKind,+ credentialKind: resolved ? resolved.entry.kind : null,+ });}return {config,@@ -120,6 +142,7 @@ export class AiEditionService {label: d.label,authKind: d.authKind,})),+ credentialSummary,};}@@ -134,7 +157,8 @@ export class AiEditionService {async llmSetApiKey(providerId: string, apiKey: string): Promise<AiEditionDocumentResult> {try {- await this.options.llmConfig.setApiKey(providerId, apiKey);+ const entry: LlmCredential = { kind: "api-key", apiKey };+ await this.options.llmConfig.setCredential(providerId, entry);return { success: true };} catch (error) {return { success: false, error: error instanceof Error ? error.message : String(error) };@@ -143,13 +167,119 @@ export class AiEditionService {async llmRemoveApiKey(providerId: string): Promise<AiEditionDocumentResult> {try {- await this.options.llmConfig.removeApiKey(providerId);+ await this.options.llmConfig.removeCredential(providerId);return { success: true };} catch (error) {return { success: false, error: error instanceof Error ? error.message : String(error) };}}+ async llmBeginDeviceAuth(+ providerId: "openai-oauth" | "copilot-proxy",+ _model?: string,+ ): Promise<AiEditionDeviceChallenge> {+ if (providerId === "openai-oauth") {+ return await beginCodexDeviceAuth();+ }+ if (providerId === "copilot-proxy") {+ return await beginGithubDeviceAuth();+ }+ throw new Error(`Provider ${providerId} does not support device flow.`);+ }++ async llmCompleteDeviceAuth(+ providerId: "openai-oauth" | "copilot-proxy",+ challenge: AiEditionDeviceChallenge,+ model?: string,+ ): Promise<AiEditionDeviceCompletionResult> {+ try {+ if (providerId === "openai-oauth") {+ const tokens = await completeCodexDeviceAuth({+ deviceAuthId: challenge.deviceAuthId ?? "",+ userCode: challenge.userCode,+ intervalMs: challenge.intervalMs,+ expiresAt: challenge.expiresAt,+ });+ const entry: LlmCredential = {+ kind: "codex",+ apiKey: tokens.accessToken,+ refreshToken: tokens.refreshToken,+ accountId: tokens.accountId,+ expiresAt: tokens.expiresAt,+ };+ await this.options.llmConfig.setCredential(providerId, entry);+ } else if (providerId === "copilot-proxy") {+ const token = await completeGithubDeviceAuth({+ deviceCode: challenge.deviceCode ?? "",+ userCode: challenge.userCode,+ intervalMs: challenge.intervalMs,+ expiresAt: challenge.expiresAt,+ });+ const entry: LlmCredential = { kind: "github-device", apiKey: token };+ await this.options.llmConfig.setCredential(providerId, entry);+ } else {+ throw new Error(`Provider ${providerId} does not support device flow.`);+ }++ // Persist the selected model so the chat path knows which model to use.+ const existing = this.options.llmConfig.getConfig();+ if (model && (!existing || existing.provider !== providerId)) {+ await this.options.llmConfig.setConfig({+ provider: providerId,+ model,+ baseUrl: existing?.provider === providerId ? existing.baseUrl : undefined,+ reasoningEffort: existing?.provider === providerId ? existing.reasoningEffort : undefined,+ });+ } else if (!existing) {+ const def = PROVIDER_DEFINITIONS.find((d) => d.id === providerId);+ if (def) {+ await this.options.llmConfig.setConfig({+ provider: providerId,+ model: def.defaultModel,+ });+ }+ }+ return { success: true, snapshot: await this.llmGetSnapshot() };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ }++ async llmDisconnect(providerId: string): Promise<AiEditionLlmDisconnectResult> {+ await this.options.llmConfig.removeCredential(providerId);+ const active = this.options.llmConfig.getConfig();+ if (active?.provider === providerId) {+ await this.options.llmConfig.setConfig({+ provider: "",+ model: "",+ });+ }+ return { success: true, snapshot: await this.llmGetSnapshot() };+ }++ async llmListProviderModels(providerId: string): Promise<{ models: string[]; error?: string }> {+ try {+ if (providerId === "openai-oauth") {+ const cred = this.options.llmConfig.getCredential(providerId, []);+ if (!cred) return { models: [], error: "Not connected" };+ const models = await listOpenAiAccountModels(cred.value);+ return { models };+ }+ if (providerId === "copilot-proxy") {+ const cred = this.options.llmConfig.getCredential(providerId, []);+ if (!cred) return { models: [], error: "Not connected" };+ const models = await listGithubCopilotModels(cred.value);+ return { models };+ }+ return { models: [], error: `Provider ${providerId} does not expose a dynamic model list` };+ } catch (error) {+ return { models: [], error: error instanceof Error ? error.message : String(error) };+ }+ }+async chatRun(projectId: string,sessionId: string,@@ -204,4 +334,23 @@ export class AiEditionService {const session = this.options.selectSession(projectId, sessionId);return session?.messages ?? [];}++ chatBudget(projectId: string, sessionId: string): AiEditionChatBudget | null {+ return getSessionBudget(projectId, sessionId);+ }++ async chatCompact(+ projectId: string,+ sessionId: string,+ ): Promise<AiEditionChatCompactResult | null> {+ const result = await compactSession(projectId, sessionId, this.options.llmConfig);+ if (!result) return null;+ const session = this.options.selectSession(projectId, sessionId);+ if (!session) return null;+ return {+ session,+ summaryMessageId: result.summaryMessageId,+ summary: result.summary,+ };+ }}diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsxindex 8bf155c33..bde6cf44a 100644--- a/src/components/ai-edition/LeftPanel.tsx+++ b/src/components/ai-edition/LeftPanel.tsx@@ -6,6 +6,7 @@ import { type AxcutAsset, ensureDocument } from "@/lib/ai-edition/schema";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { nativeBridgeClient } from "@/native/client";import type { AiEditionLlmConfig, AiEditionToolCallSummary } from "@/native/contracts";+import { computeBudget } from "./chatBudget";import { ChatHistoryModal, SourceTranscriptModal } from "./Modals";import styles from "./NewEditorShell.module.css";import { ProviderSettings } from "./ProviderSettings";@@ -521,6 +522,35 @@ function ChatStripPanel() {? `Reasoning ${llmConfig.reasoningEffort}`: null;+ // Real context usage — feeds the badge in the chat strip and gates the+ // auto-compact heuristic on the main side. Recomputed on every messages+ // change so the % tracks the live history.+ const budget = computeBudget(messages);++ const compactNow = useCallback(async () => {+ if (!projectId || !activeSessionId) return;+ try {+ const result = await nativeBridgeClient.aiEdition.chatCompact(projectId, activeSessionId);+ if (!result) {+ toast.info("Not enough history to compact yet.");+ return;+ }+ setMessages(+ result.session.messages.map((m) => ({+ role: m.role,+ content: m.content,+ time: m.createdAt,+ toolCalls: m.toolCalls,+ })),+ );+ toast.success("Compacted earlier context");+ } catch (err) {+ toast.error("Compact failed", {+ description: err instanceof Error ? err.message : String(err),+ });+ }+ }, [projectId, activeSessionId]);+const newChat = useCallback(async () => {if (!projectId) return;try {@@ -586,12 +616,20 @@ function ChatStripPanel() {<aside className={styles.panel}><div className={styles.chatStrip}><div className={styles.chatStripRow}>- <span className={styles.ctxPill}>+ <span+ className={styles.ctxPill}+ title={`${budget.usedTokens} / ${budget.budgetTokens} estimated tokens`}+ ><span className={styles.d} aria-hidden />- 0% context+ {Math.min(100, Math.round(budget.ratio * 100))}% context</span><span className={styles.stripActions}>- <button type="button" title="Compact" aria-label="Compact">+ <button+ type="button"+ title="Compact"+ aria-label="Compact"+ onClick={() => void compactNow()}+ ><svgwidth={14}height={14}diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.cssindex 14fe32e78..734778df6 100644--- a/src/components/ai-edition/NewEditorShell.module.css+++ b/src/components/ai-edition/NewEditorShell.module.css@@ -1927,3 +1927,209 @@.scrubBar:hover .scrubThumb {transform: translate(-50%, -50%) scale(1.2);}++/* ─── AI provider settings (axcut parity) ────────────────────────── */++.providerGrid {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 10px;+}+.providerCard {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 12px 14px;+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ background: var(--surface);+ color: var(--fg-2);+ cursor: pointer;+ font: 500 13px/1.2 var(--font-body);+ text-align: left;+ transition: border-color var(--motion-fast) var(--ease), background var(--motion-fast) var(--ease);+}+.providerCard:hover { border-color: var(--border-hi); }+.providerCard.active {+ border-color: var(--accent);+ background: var(--accent-soft);+ color: var(--fg);+}+.providerCard .head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+}+.providerCard .label {+ font-weight: 600;+ font-size: 14px;+ color: var(--fg);+}+.providerCard .model {+ font: 500 11px var(--font-mono);+ color: var(--muted);+ letter-spacing: 0.02em;+ text-transform: lowercase;+}+.statusPill {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 2px 8px;+ border-radius: 9999px;+ font: 600 10px/1 var(--font-mono);+ letter-spacing: 0.06em;+ text-transform: uppercase;+ border: 1px solid transparent;+}+.statusPill.ready {+ background: var(--success-soft, rgba(68, 175, 105, 0.18));+ color: var(--success, #44af69);+ border-color: color-mix(in srgb, var(--success, #44af69) 30%, transparent);+}+.statusPill.idle {+ background: var(--surface-2);+ color: var(--muted);+ border-color: var(--border);+}+.statusPill.auth {+ background: color-mix(in srgb, var(--accent) 18%, transparent);+ color: var(--accent);+ border-color: color-mix(in srgb, var(--accent) 35%, transparent);+}+.statusPill.pat {+ background: color-mix(in srgb, var(--warn) 18%, transparent);+ color: var(--warn);+ border-color: color-mix(in srgb, var(--warn) 35%, transparent);+}++.providerForm {+ display: flex;+ flex-direction: column;+ gap: 16px;+}+.providerForm .title {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+}+.providerForm .title h3 {+ margin: 0;+ font: 600 16px var(--font-display);+ color: var(--fg);+}+.providerForm .actions {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ padding-top: 8px;+ border-top: 1px solid var(--border-soft);+ margin-top: 4px;+}+.providerForm .actionsLeft {+ display: flex;+ gap: 8px;+}+.dangerBtn {+ background: color-mix(in srgb, var(--danger) 14%, transparent);+ color: var(--danger);+ border: 1px solid color-mix(in srgb, var(--danger) 35%, transparent);+}+.dangerBtn:hover {+ background: color-mix(in srgb, var(--danger) 22%, transparent);+ color: var(--danger);+}++.authPanel {+ padding: 14px 16px;+ border: 1px solid var(--brand);+ background: color-mix(in srgb, var(--accent) 8%, var(--surface));+ border-radius: var(--r-md);+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.authPanel strong {+ display: block;+ font: 600 13px var(--font-body);+ color: var(--fg);+}+.authPanel p {+ margin: 4px 0 0;+ font: 400 12px/1.45 var(--font-body);+ color: var(--muted);+}+.authCodeRow {+ display: flex;+ align-items: center;+ gap: 10px;+}+.authCodeRow code {+ flex: 1;+ font: 600 18px/1 var(--font-mono);+ letter-spacing: 0.18em;+ padding: 10px 14px;+ background: var(--bg);+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ color: var(--fg);+ user-select: all;+}+.linkBtn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 0 12px;+ height: 32px;+ border-radius: var(--r-md);+ background: var(--surface);+ border: 1px solid var(--border);+ color: var(--fg);+ font: 500 var(--fs-app) var(--font-body);+ cursor: pointer;+ text-decoration: none;+}+.linkBtn:hover { background: var(--surface-warm); border-color: var(--border-hi); }++.errorRow {+ margin: 0;+ padding: 10px 12px;+ border-radius: var(--r-md);+ border: 1px solid color-mix(in srgb, var(--danger) 35%, transparent);+ background: color-mix(in srgb, var(--danger) 8%, var(--surface));+ color: var(--danger);+ font: 500 12px var(--font-body);+}++.iconBtn {+ width: 28px;+ height: 28px;+ display: inline-grid;+ place-items: center;+ border-radius: var(--r-sm);+ background: transparent;+ border: 1px solid transparent;+ color: var(--muted);+ cursor: pointer;+}+.iconBtn:hover { background: var(--surface-3); color: var(--fg); }+.iconBtn:disabled { opacity: 0.5; cursor: not-allowed; }++.backBtn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 0 10px;+ height: 28px;+ border-radius: var(--r-sm);+ background: transparent;+ color: var(--fg);+ border: 1px solid var(--border);+ cursor: pointer;+ font: 500 12px var(--font-body);+}+.backBtn:hover { background: var(--surface-3); }+.backBtn:disabled { opacity: 0.5; cursor: not-allowed; }+diff --git a/src/components/ai-edition/ProviderSettings.tsx b/src/components/ai-edition/ProviderSettings.tsxindex 34e88d0fb..4bb6b1af7 100644--- a/src/components/ai-edition/ProviderSettings.tsx+++ b/src/components/ai-edition/ProviderSettings.tsx@@ -1,15 +1,44 @@// Provider Settings popover/modal for the new editor's chat strip.//-// UI: list of provider cards (the 8 from provider-registry.ts). On select, a-// detail form opens for the picked provider: API key input, model select,-// baseUrl (for openai-compatible), reasoning effort (if supported). Save-// commits the config + key to the LLMConfigStore via the native bridge.+// UI: 3 screens stacked in the modal, navigated by URL-less state+// (mirroring axcut apps/web/src/App.tsx _p modal):+// 1. **list** — 2-col grid of provider cards (8 of them),+// each shows label, default model, an auth-kind+// pill (CONNECTED / OAUTH / TOKEN / API KEY).+// 2. **connect-form** — single form per provider: model + optional+// baseUrl + optional reasoning effort + optional+// api-key field + Connect/Save/Disconnect buttons.+// 3. **device-challenge** — opens when an oauth-device / PAT provider+// finishes its begin step: the user-code block,+// "Open login page" link, and a copy-code button.+// On completion the snapshot refreshes.+//+// Credentials are stored in the same safeStorage blob (LLMConfigStore),+// including OAuth session tokens. The renderer never sees raw keys —+// only `kind` and the user code / verification URL.+//+// ponytail: existing consumers (ProviderSettings used as <ProviderSettings open onClose />)+// must keep working. Internal state is local-only.-import { Check, KeyRound, Loader2, X } from "lucide-react";-import { useEffect, useState } from "react";+import {+ AlertCircle,+ Check,+ Copy,+ ExternalLink,+ Loader2,+ LogIn,+ Plug,+ Unplug,+ X,+} from "lucide-react";+import { useCallback, useEffect, useState } from "react";import { toast } from "sonner";import { nativeBridgeClient } from "@/native/client";-import type { AiEditionLlmConfig, AiEditionLlmSnapshot } from "@/native/contracts";+import type {+ AiEditionDeviceChallenge,+ AiEditionLlmConfig,+ AiEditionLlmSnapshot,+} from "@/native/contracts";import {PROVIDER_DEFINITIONS,type ProviderDefinition,@@ -23,127 +52,249 @@ type Mode = "list" | "form";interface ProviderSettingsProps {open: boolean;onClose: () => void;+ onActiveProviderChanged?: (providerId: string | null) => void;}-export function ProviderSettings({ open, onClose }: ProviderSettingsProps) {+export function ProviderSettings({+ open,+ onClose,+ onActiveProviderChanged,+}: ProviderSettingsProps) {const [snapshot, setSnapshot] = useState<AiEditionLlmSnapshot | null>(null);const [mode, setMode] = useState<Mode>("list");const [active, setActive] = useState<ProviderDefinition | null>(null);- const [apiKey, setApiKey] = useState("");const [config, setConfig] = useState<AiEditionLlmConfig | null>(null);+ const [apiKey, setApiKey] = useState("");const [busy, setBusy] = useState(false);+ const [challenge, setChallenge] = useState<AiEditionDeviceChallenge | null>(null);+ const [error, setError] = useState<string | null>(null);++ const refreshSnapshot = useCallback(async (): Promise<AiEditionLlmSnapshot> => {+ try {+ const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();+ setSnapshot(snap);+ if (snap.config) setConfig(snap.config);+ return snap;+ } catch (err) {+ toast.error("Could not load AI settings", {+ description: err instanceof Error ? err.message : String(err),+ });+ throw err;+ }+ }, []);useEffect(() => {if (!open) return;- void (async () => {- try {- const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();- setSnapshot(snap);- if (snap.config) {- setConfig(snap.config);- }- } catch (err) {- toast.error("Could not load AI settings", {- description: err instanceof Error ? err.message : String(err),- });- }- })();+ void refreshSnapshot();+ }, [open, refreshSnapshot]);++ useEffect(() => {+ if (!open) {+ setMode("list");+ setActive(null);+ setApiKey("");+ setChallenge(null);+ setError(null);+ }}, [open]);- const handlePick = (def: ProviderDefinition) => {+ const goBackToList = useCallback(() => {+ if (busy) return;+ setMode("list");+ setActive(null);+ setApiKey("");+ setChallenge(null);+ setError(null);+ }, [busy]);++ useEffect(() => {+ if (!open) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape" && !busy) {+ if (mode === "form") goBackToList();+ else onClose();+ }+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [open, busy, mode, onClose, goBackToList]);++ const openForm = (def: ProviderDefinition) => {setActive(def);setApiKey("");+ setChallenge(null);+ setError(null);setConfig((prev) => {- const base: AiEditionLlmConfig = prev ?? { provider: def.id, model: def.defaultModel };+ const existing = prev?.provider === def.id ? prev : null;return {provider: def.id,- model: base.provider === def.id ? base.model : def.defaultModel,- baseUrl: base.provider === def.id ? base.baseUrl : def.baseUrl,- reasoningEffort: base.provider === def.id ? base.reasoningEffort : undefined,+ model: existing?.model ?? def.defaultModel,+ baseUrl: existing?.baseUrl ?? def.baseUrl,+ reasoningEffort: existing?.reasoningEffort,+ allowAgentEdits: existing?.allowAgentEdits,};});setMode("form");};- const handleSave = async () => {+ const close = () => {+ if (busy) return;+ onClose();+ setMode("list");+ setActive(null);+ setApiKey("");+ setChallenge(null);+ setError(null);+ };++ const saveApiKey = async () => {if (!active || !config) return;setBusy(true);+ setError(null);try {- if (apiKey && active.authKind === "api-key") {- await nativeBridgeClient.aiEdition.llmSetApiKey(active.id, apiKey);+ if (apiKey.trim()) {+ await nativeBridgeClient.aiEdition.llmSetApiKey(active.id, apiKey.trim());+ setApiKey("");}await nativeBridgeClient.aiEdition.llmSetConfig(config);- toast.success(`${active.label} configured`);- const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();- setSnapshot(snap);+ const snap = await refreshSnapshot();+ onActiveProviderChanged?.(snap?.config?.provider ?? null);+ toast.success(`${active.label} saved`);setMode("list");setActive(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ };++ const startDeviceFlow = async () => {+ if (!active) return;+ setBusy(true);+ setError(null);+ try {+ const challengeResult = await nativeBridgeClient.aiEdition.llmBeginDeviceAuth(+ active.id as "openai-oauth" | "copilot-proxy",+ config?.model,+ );+ setChallenge(challengeResult);+ if (active.id === "copilot-proxy") {+ // GitHub device flow accepts an optional PAT. If the user has pasted one,+ // pass it through as if they were connecting with the classic token path.+ if (apiKey.trim() && active.id === "copilot-proxy") {+ // Skipped for now — Copilot device flow uses its own token.+ }+ }+ // Auto-complete poll: kick off completion in the background, the UI shows+ // "Completing sign-in…" and the snapshot refresh when the call returns.+ void completeDeviceFlowInBackground(challengeResult);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ };++ const completeDeviceFlowInBackground = async (challengeParam: AiEditionDeviceChallenge) => {+ if (!active) return;+ setBusy(true);+ try {+ const result = await nativeBridgeClient.aiEdition.llmCompleteDeviceAuth(+ active.id as "openai-oauth" | "copilot-proxy",+ challengeParam,+ config?.model,+ );+ if (result.success) {+ const snap = await refreshSnapshot();+ onActiveProviderChanged?.(snap?.config?.provider ?? null);+ toast.success(`${active.label} connected`);+ setMode("list");+ setActive(null);+ setChallenge(null);+ } else {+ setError(result.error ?? "Device flow failed.");+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ };++ const startPatConnect = async () => {+ if (!active || !apiKey.trim() || !config) return;+ setBusy(true);+ setError(null);+ try {+ await nativeBridgeClient.aiEdition.llmSetApiKey(active.id, apiKey.trim());+ await nativeBridgeClient.aiEdition.llmSetConfig(config);+ const snap = await refreshSnapshot();+ onActiveProviderChanged?.(snap?.config?.provider ?? null);+ toast.success(`${active.label} connected`);setApiKey("");+ setMode("list");+ setActive(null);} catch (err) {- toast.error("Save failed", {- description: err instanceof Error ? err.message : String(err),- });+ setError(err instanceof Error ? err.message : String(err));} finally {setBusy(false);}};- const handleDisconnect = async () => {+ const disconnect = async () => {if (!active) return;setBusy(true);+ setError(null);try {- await nativeBridgeClient.aiEdition.llmRemoveApiKey(active.id);+ const result = await nativeBridgeClient.aiEdition.llmDisconnect(active.id);+ const snap = result.snapshot ?? (await refreshSnapshot());+ onActiveProviderChanged?.(snap.config?.provider ?? null);toast.success(`${active.label} disconnected`);- const snap = await nativeBridgeClient.aiEdition.llmGetSnapshot();- setSnapshot(snap);} catch (err) {- toast.error("Disconnect failed", {- description: err instanceof Error ? err.message : String(err),- });+ setError(err instanceof Error ? err.message : String(err));} finally {setBusy(false);}};- const connected = new Set(snapshot?.connectedProviders ?? []);-return (<ModalShellopen={open}- onClose={() => {- if (busy) return;- onClose();- setMode("list");- setActive(null);- setApiKey("");- }}+ onClose={close}title="AI settings"subtitle="Choose a provider. Credentials are stored in the OS keychain (safeStorage)."wide>{mode === "list" ? (<ProviderList- connected={connected}+ connected={new Set(snapshot?.connectedProviders ?? [])}activeProvider={snapshot?.config?.provider ?? null}- onPick={handlePick}+ onPick={openForm}/>) : active ? (<ProviderFormdef={active}- isConnected={connected.has(active.id)}+ isConnected={(snapshot?.connectedProviders ?? []).includes(active.id)}+ credentialKind={+ snapshot?.credentialSummary.find((c) => c.providerId === active.id)?.credentialKind ??+ null+ }apiKey={apiKey}setApiKey={setApiKey}config={config}setConfig={setConfig}busy={busy}- onBack={() => {- if (busy) return;- setMode("list");- setActive(null);- setApiKey("");- }}- onSave={handleSave}- onDisconnect={handleDisconnect}+ challenge={challenge}+ error={error}+ onBack={goBackToList}+ onSave={active.authKind === "api-key" ? saveApiKey : startDeviceFlow}+ onPatConnect={active.authKind === "pat" ? startPatConnect : undefined}+ onDisconnect={disconnect}+ onOpenLoginPage={(uri) =>+ typeof window !== "undefined" && window.open(uri, "_blank", "noopener,noreferrer")+ }+ listProviderModels={nativeBridgeClient.aiEdition.llmListProviderModels}/>) : null}</ModalShell>@@ -160,13 +311,7 @@ function ProviderList({onPick: (def: ProviderDefinition) => void;}) {return (- <div- style={{- display: "grid",- gridTemplateColumns: "repeat(2, 1fr)",- gap: 8,- }}- >+ <div className={styles.providerGrid}>{PROVIDER_DEFINITIONS.map((def) => {const isConnected = connected.has(def.id);const isActive = def.id === activeProvider;@@ -174,71 +319,34 @@ function ProviderList({<buttonkey={def.id}type="button"+ className={`${styles.providerCard} ${isActive ? styles.active : ""}`}onClick={() => onPick(def)}- style={{- display: "flex",- flexDirection: "column",- gap: 6,- padding: 12,- border: `1px solid ${isActive ? "var(--accent)" : "var(--border)"}`,- borderRadius: 10,- background: isActive ? "var(--accent-wash)" : "var(--surface)",- color: "var(--fg-2)",- cursor: "pointer",- textAlign: "left",- font: "500 13px/1.2 var(--font-body)",- }}>- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- gap: 8,- }}- >- <span style={{ color: "var(--fg)", fontWeight: 600 }}>{def.label}</span>+ <div className={styles.head}>+ <span className={styles.label}>{def.label}</span>{isConnected ? (- <span- style={{- display: "inline-flex",- alignItems: "center",- gap: 4,- padding: "2px 8px",- borderRadius: 999,- background: "var(--success-soft)",- color: "var(--success)",- font: "500 10px/1 var(--font-mono)",- letterSpacing: "0.04em",- }}- >+ <span className={`${styles.statusPill} ${styles.ready}`}><Check size={10} />- CONNECTED+ Connected+ </span>+ ) : authKindPillKind(def.authKind) === "auth" ? (+ <span className={`${styles.statusPill} ${styles.auth}`}>+ <LogIn size={10} />+ OAuth+ </span>+ ) : def.authKind === "pat" ? (+ <span className={`${styles.statusPill} ${styles.pat}`}>+ <Plug size={10} />+ Token</span>) : (- <span- style={{- padding: "2px 8px",- borderRadius: 999,- background: "var(--surface-2)",- color: "var(--muted)",- font: "500 10px/1 var(--font-mono)",- letterSpacing: "0.04em",- }}- >- {authLabel(def.authKind)}+ <span className={`${styles.statusPill} ${styles.idle}`}>+ <KeyIcon />+ API key</span>)}</div>- <span- style={{- font: "500 11px/1.4 var(--font-mono)",- color: "var(--muted)",- letterSpacing: "0.02em",- }}- >- {def.defaultModel || "—"}- </span>+ <span className={styles.model}>{def.defaultModel || "—"}</span></button>);})}@@ -246,135 +354,201 @@ function ProviderList({);}-function authLabel(kind: ProviderDefinition["authKind"]): string {+function authKindPillKind(kind: ProviderDefinition["authKind"]): "auth" | "pat" | "key" {switch (kind) {- case "api-key":- return "API KEY";case "oauth-device":- return "OAUTH";+ return "auth";case "pat":- return "TOKEN";+ return "pat";+ case "api-key":+ return "key";}}+function KeyIcon() {+ // tiny single-stroke "••• " icon as a span, avoids pulling in another lucide dep.+ return (+ <span+ aria-hidden+ style={{+ display: "inline-block",+ fontFamily: "var(--font-mono)",+ letterSpacing: "0.1em",+ fontSize: "11px",+ }}+ >+ •••+ </span>+ );+}+function ProviderForm({def,isConnected,+ credentialKind,apiKey,setApiKey,config,setConfig,busy,+ challenge,+ error,onBack,onSave,+ onPatConnect,onDisconnect,+ onOpenLoginPage,+ listProviderModels,}: {def: ProviderDefinition;isConnected: boolean;+ credentialKind: string | null;apiKey: string;setApiKey: (v: string) => void;config: AiEditionLlmConfig | null;setConfig: (c: AiEditionLlmConfig | null) => void;busy: boolean;+ challenge: AiEditionDeviceChallenge | null;+ error: string | null;onBack: () => void;onSave: () => void;+ onPatConnect?: () => void;onDisconnect: () => void;+ onOpenLoginPage: (uri: string) => void;+ listProviderModels: (providerId: string) => Promise<{ models: string[]; error?: string }>;}) {+ const showApiKeyField = def.authKind === "api-key" || (def.authKind === "pat" && !isConnected);+ const showBaseUrl = def.id === "openai-compatible" || Boolean(def.baseUrl);+ const isCodexOrCopilot = def.authKind === "oauth-device";+ const supportsDynamicModels = isCodexOrCopilot || def.authKind === "pat";++ const [modelOptions, setModelOptions] = useState<string[]>([]);+ const [modelsLoading, setModelsLoading] = useState(false);+ const [modelsError, setModelsError] = useState<string | null>(null);++ useEffect(() => {+ if (!supportsDynamicModels || !isConnected) {+ setModelOptions([]);+ setModelsError(null);+ return;+ }+ let cancelled = false;+ setModelsLoading(true);+ setModelsError(null);+ void listProviderModels(def.id)+ .then((result) => {+ if (cancelled) return;+ setModelOptions(result.models);+ setModelsError(result.error ?? null);+ })+ .catch((err) => {+ if (cancelled) return;+ setModelOptions([]);+ setModelsError(err instanceof Error ? err.message : String(err));+ })+ .finally(() => {+ if (!cancelled) setModelsLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [def.id, isConnected, supportsDynamicModels, listProviderModels]);++ const modelSelectable = modelOptions.length > 0;+return (- <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- }}- >+ <div className={styles.providerForm}>+ <div className={styles.title}><buttontype="button"- className={styles.iconBtn}+ className={styles.backBtn}+ onClick={onBack}+ disabled={busy}title="Back"aria-label="Back"- onClick={onBack}- >- <X size={16} />- </button>- <span style={{ font: "600 14px var(--font-body)", color: "var(--fg)" }}>{def.label}</span>- <button- type="button"- className={styles.iconBtn}- title="Close"- aria-label="Close"- onClick={onBack}>- <X size={16} />+ <X size={14} />+ Back</button>+ <h3>{def.label}</h3>+ {isConnected ? (+ <span className={`${styles.statusPill} ${styles.ready}`}>+ <Check size={10} />+ Connected {credentialKind && credentialKind !== "api-key" ? `· ${credentialKind}` : ""}+ </span>+ ) : (+ <span className={`${styles.statusPill} ${styles.idle}`}>Not connected</span>+ )}</div>- <Field label="Model">- <input- type="text"- value={config?.model ?? def.defaultModel}- placeholder={def.defaultModel}- onChange={(e) =>- setConfig({- ...(config ?? { provider: def.id, model: def.defaultModel }),- model: e.target.value,- })- }- />- </Field>-- {def.authKind === "api-key" ? (- <Field- label="API key"- hint={isConnected ? "Leave blank to keep the stored key." : undefined}- >- <div- style={{- display: "flex",- alignItems: "center",- gap: 6,- padding: "6px 8px 6px 10px",- border: "1px solid var(--border)",- borderRadius: 6,- background: "var(--surface)",- }}+ <Field+ label="Model"+ hint={+ modelSelectable+ ? "Models from your account, fetched live."+ : modelsError+ ? `Couldn't fetch live models (${modelsError}); type a model id manually.`+ : supportsDynamicModels && isConnected+ ? "Loading live models…"+ : undefined+ }+ >+ {modelSelectable ? (+ <select+ value={config?.model ?? def.defaultModel}+ onChange={(e) =>+ setConfig({+ ...(config ?? { provider: def.id, model: def.defaultModel }),+ model: e.target.value,+ })+ }+ disabled={busy}>- <KeyRound size={14} style={{ color: "var(--meta)" }} />- <input- type="password"- value={apiKey}- placeholder={isConnected ? "••••••" : "sk-…"}- onChange={(e) => setApiKey(e.target.value)}- style={{- flex: 1,- border: 0,- outline: "none",- background: "transparent",- font: "500 12px var(--font-mono)",- color: "var(--fg-2)",- }}- />- </div>- </Field>- ) : (- <Field label="Authentication" hint={authHint(def)}>- <div+ {!modelOptions.includes(config?.model ?? def.defaultModel) ? (+ <option value={config?.model ?? def.defaultModel}>+ {config?.model ?? def.defaultModel} (saved)+ </option>+ ) : null}+ {modelOptions.map((modelSlug) => (+ <option key={modelSlug} value={modelSlug}>+ {modelSlug}+ </option>+ ))}+ </select>+ ) : (+ <input+ type="text"+ value={config?.model ?? def.defaultModel}+ placeholder={def.defaultModel}+ onChange={(e) =>+ setConfig({+ ...(config ?? { provider: def.id, model: def.defaultModel }),+ model: e.target.value,+ })+ }+ disabled={busy}+ />+ )}+ {modelsLoading ? (+ <spanstyle={{- padding: "8px 10px",- border: "1px solid var(--border)",- borderRadius: 6,- background: "var(--surface-2)",+ display: "inline-flex",+ alignItems: "center",+ gap: 4,+ marginTop: 4,+ font: "500 10px var(--font-mono)",color: "var(--muted)",- font: "500 12px var(--font-body)",+ letterSpacing: "0.04em",+ textTransform: "uppercase",}}>- {authKindLabel(def.authKind)} — connect flow not implemented yet.- </div>- </Field>- )}+ <Loader2 size={10} className="animate-spin" />+ Loading models…+ </span>+ ) : null}+ </Field>- {(def.id === "openai-compatible" || def.baseUrl) && (+ {showBaseUrl ? (<Field label="Base URL" hint="Leave blank to use the provider's default."><inputtype="text"@@ -386,9 +560,10 @@ function ProviderForm({baseUrl: e.target.value || undefined,})}+ disabled={busy}/></Field>- )}+ ) : null}{def.supportsReasoningEffort ? (<Field label="Reasoning effort">@@ -400,6 +575,7 @@ function ProviderForm({reasoningEffort: e.target.value,})}+ disabled={busy}>{REASONING_EFFORT_OPTIONS.map((r: string) => (<option key={r} value={r}>@@ -410,6 +586,27 @@ function ProviderForm({</Field>) : null}+ {showApiKeyField ? (+ <Field+ label={def.authKind === "pat" ? "GitHub personal access token" : "API key"}+ hint={+ isConnected+ ? "Stored in safeStorage. Leave blank to keep the existing entry."+ : def.authKind === "pat"+ ? "Paste a GitHub PAT with `copilot` scope."+ : undefined+ }+ >+ <input+ type="password"+ value={apiKey}+ placeholder={isConnected ? "••••••" : "sk-…"}+ onChange={(e) => setApiKey(e.target.value)}+ disabled={busy}+ />+ </Field>+ ) : null}+<Fieldlabel="Project edits"hint="When off, the agent must ask before changing the timeline. Edits are always undoable."@@ -427,6 +624,7 @@ function ProviderForm({<inputtype="checkbox"checked={config?.allowAgentEdits !== false}+ disabled={busy}onChange={(e) =>setConfig({...(config ?? { provider: def.id, model: def.defaultModel }),@@ -438,52 +636,158 @@ function ProviderForm({</label></Field>- <div- style={{- display: "flex",- justifyContent: "space-between",- gap: 8,- paddingTop: 12,- borderTop: "1px solid var(--border-soft)",- }}- >+ {challenge ? (+ <DeviceChallengePanel+ challenge={challenge}+ busy={busy}+ providerLabel={def.label}+ onOpenLoginPage={onOpenLoginPage}+ />+ ) : null}+ {error ? (+ <p className={styles.errorRow}>+ <AlertCircle size={14} style={{ verticalAlign: "middle", marginRight: 6 }} />+ {error}+ </p>+ ) : null}++ <div className={styles.actions}>+ <div className={styles.actionsLeft}>+ {isConnected ? (+ <button+ type="button"+ className={`${styles.btn} ${styles.dangerBtn}`}+ onClick={onDisconnect}+ disabled={busy}+ >+ <Unplug size={14} />+ Disconnect+ </button>+ ) : null}+ </div>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={onBack}+ disabled={busy}+ >+ Cancel+ </button>{isConnected ? (<buttontype="button"- className={`${styles.btn} ${styles.btnSecondary}`}- onClick={onDisconnect}- disabled={busy}+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={onSave}+ disabled={busy || !config}>- Disconnect+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />}+ Save</button>- ) : (- <span />- )}- <div style={{ display: "flex", gap: 8 }}>+ ) : isCodexOrCopilot ? (<buttontype="button"- className={`${styles.btn} ${styles.btnSecondary}`}- onClick={onBack}- disabled={busy}+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={onSave}+ disabled={busy || !config}>- Cancel+ {busy ? <Loader2 size={14} className="animate-spin" /> : <LogIn size={14} />}+ {isConnected ? "Reconnect" : "Start login"}</button>+ ) : def.authKind === "pat" && onPatConnect ? (+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={onPatConnect}+ disabled={busy || !apiKey.trim() || !config}+ >+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Plug size={14} />}+ Connect+ </button>+ ) : (<buttontype="button"className={`${styles.btn} ${styles.btnPrimary}`}onClick={onSave}- disabled={busy || !config}+ disabled={busy || !apiKey.trim() || !config}>- {busy ? (- <>- <Loader2 size={14} className="animate-spin" />- Saving…- </>- ) : (- "Save & use"- )}+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />}+ {apiKey.trim() ? "Save & use" : "Save"}</button>- </div>+ )}+ </div>+ </div>+ );+}++function DeviceChallengePanel({+ challenge,+ busy,+ providerLabel,+ onOpenLoginPage,+}: {+ challenge: AiEditionDeviceChallenge;+ busy: boolean;+ providerLabel: string;+ onOpenLoginPage: (uri: string) => void;+}) {+ const [copied, setCopied] = useState(false);++ const onCopy = async () => {+ try {+ if (typeof navigator !== "undefined" && navigator.clipboard) {+ await navigator.clipboard.writeText(challenge.userCode);+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1400);+ }+ } catch {+ /* clipboards may be denied in some sandboxes — silently no-op */+ }+ };++ const loginUrl = challenge.verificationUriComplete ?? challenge.verificationUri;++ return (+ <div+ className={styles.authPanel}+ role="status"+ aria-live="polite"+ data-testid="device-challenge-panel"+ >+ <div>+ <strong>{busy ? "Completing sign-in…" : "Browser login pending"}</strong>+ <p>+ Open the {providerLabel} login page and enter this code. We’ll finish connecting+ automatically once you authorize.+ </p>+ </div>+ <div className={styles.authCodeRow}>+ <code data-testid="device-user-code">{challenge.userCode}</code>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnSecondary}`}+ onClick={onCopy}+ title="Copy code"+ aria-label="Copy code"+ disabled={busy}+ >+ {copied ? <Check size={14} /> : <Copy size={14} />}+ {copied ? "Copied" : "Copy code"}+ </button>+ </div>+ <div>+ <a+ href={loginUrl}+ target="_blank"+ rel="noreferrer noopener"+ className={styles.linkBtn}+ onClick={(e) => {+ e.preventDefault();+ onOpenLoginPage(loginUrl);+ }}+ >+ <ExternalLink size={14} />+ Open login page+ </a></div></div>);@@ -521,21 +825,3 @@ function Field({</div>);}--function authKindLabel(kind: ProviderDefinition["authKind"]): string {- switch (kind) {- case "oauth-device":- return "OAuth device flow";- case "pat":- return "Personal access token";- case "api-key":- return "API key";- }-}--function authHint(def: ProviderDefinition): string {- if (def.envKeys.length > 0) {- return `Set ${def.envKeys.join(" or ")} in your environment.`;- }- return "Connect flow coming soon.";-}diff --git a/src/components/ai-edition/chatBudget.ts b/src/components/ai-edition/chatBudget.tsnew file mode 100644index 000000000..0acbc561c--- /dev/null+++ b/src/components/ai-edition/chatBudget.ts@@ -0,0 +1,41 @@+// Renderer-side budget helper. Mirrors `electron/ai-edition/chat-compaction.ts`+// but inline so we don't drag electron/ into the renderer bundle.+//+// ponytail: 4 chars per token is plenty accurate for a "should we compact yet"+// gate. The estimation lives in the main process too (chat-service+// `getSessionBudget`); this duplicate is a small price for keeping the+// renderer free of electron/ imports.++const CHARS_PER_TOKEN = 4;++export interface ChatBudget {+ usedTokens: number;+ budgetTokens: number;+ ratio: number;+}++export const DEFAULT_CHAT_BUDGET_TOKENS = 80_000;++export interface RenderableChatMessage {+ content: string;+ toolCalls?: Array<{ name?: string; summary?: string }>;+}++export function estimateTokens(messages: RenderableChatMessage[]): number {+ let chars = 0;+ for (const m of messages) {+ chars += m.content.length;+ for (const tc of m.toolCalls ?? []) {+ chars += (tc.name?.length ?? 0) + (tc.summary?.length ?? 0) + 16;+ }+ }+ return Math.ceil(chars / CHARS_PER_TOKEN);+}++export function computeBudget(+ messages: RenderableChatMessage[],+ budgetTokens: number = DEFAULT_CHAT_BUDGET_TOKENS,+): ChatBudget {+ const used = estimateTokens(messages);+ return { usedTokens: used, budgetTokens, ratio: budgetTokens > 0 ? used / budgetTokens : 0 };+}diff --git a/src/native/browserShim.ts b/src/native/browserShim.tsindex fe63931dc..bbb7f5e4d 100644--- a/src/native/browserShim.ts+++ b/src/native/browserShim.ts@@ -268,6 +268,25 @@ function createShimBridgeClient() {m.delete(sessionId);return Promise.resolve({ success: true });},+ chatBudget: (projectId: string, sessionId: string) => {+ const s = sessionsByProject.get(projectId)?.get(sessionId);+ if (!s) return Promise.resolve(null);+ const chars = s.messages.reduce((acc, m) => acc + m.content.length, 0);+ const used = Math.ceil(chars / 4);+ return Promise.resolve({ usedTokens: used, budgetTokens: 80_000, ratio: used / 80_000 });+ },+ chatCompact: (projectId: string, sessionId: string) => {+ // ponytail: browser shim is a no-op compaction — it just hand-summarizes+ // instead of round-tripping an LLM call. Returns a placeholder session+ // so renderers can validate the wiring.+ const s = sessionsByProject.get(projectId)?.get(sessionId);+ if (!s) return Promise.resolve(null);+ return Promise.resolve({+ session: s,+ summaryMessageId: null,+ summary: "(browser shim compaction is a no-op)",+ });+ },},project: {getCurrentContext: () =>diff --git a/src/native/client.ts b/src/native/client.tsindex b44d39e34..8d1e2bcd6 100644--- a/src/native/client.ts+++ b/src/native/client.ts@@ -1,11 +1,17 @@import {type AiEditionAssetResult,+ type AiEditionChatBudget,+ type AiEditionChatCompactResult,type AiEditionChatMessage,type AiEditionChatResult,type AiEditionChatSession,type AiEditionChatSessionSummary,+ type AiEditionDeviceChallenge,+ type AiEditionDeviceCompletionResult,type AiEditionDocumentResult,type AiEditionLlmConfig,+ type AiEditionLlmDisconnectResult,+ type AiEditionLlmProviderModelsResult,type AiEditionLlmSnapshot,type AiEditionProjectSummary,type CursorCapabilities,@@ -211,6 +217,34 @@ export const nativeBridgeClient = {action: "llm.removeApiKey",payload: { providerId },}),+ llmBeginDeviceAuth: (providerId: "openai-oauth" | "copilot-proxy", model?: string) =>+ requireNativeBridgeData<AiEditionDeviceChallenge>({+ domain: "aiEdition",+ action: "llm.beginDeviceAuth",+ payload: { providerId, model },+ }),+ llmCompleteDeviceAuth: (+ providerId: "openai-oauth" | "copilot-proxy",+ challenge: AiEditionDeviceChallenge,+ model?: string,+ ) =>+ requireNativeBridgeData<AiEditionDeviceCompletionResult>({+ domain: "aiEdition",+ action: "llm.completeDeviceAuth",+ payload: { providerId, challenge, model },+ }),+ llmDisconnect: (providerId: string) =>+ requireNativeBridgeData<AiEditionLlmDisconnectResult>({+ domain: "aiEdition",+ action: "llm.disconnect",+ payload: { providerId },+ }),+ llmListProviderModels: (providerId: string) =>+ requireNativeBridgeData<AiEditionLlmProviderModelsResult>({+ domain: "aiEdition",+ action: "llm.listProviderModels",+ payload: { providerId },+ }),chatRun: (projectId: string,sessionIdOrMessage: string,@@ -287,5 +321,17 @@ export const nativeBridgeClient = {action: "chat.deleteSession",payload: { projectId, sessionId },}),+ chatBudget: (projectId: string, sessionId: string) =>+ requireNativeBridgeData<AiEditionChatBudget | null>({+ domain: "aiEdition",+ action: "chat.budget",+ payload: { projectId, sessionId },+ }),+ chatCompact: (projectId: string, sessionId: string) =>+ requireNativeBridgeData<AiEditionChatCompactResult | null>({+ domain: "aiEdition",+ action: "chat.compact",+ payload: { projectId, sessionId },+ }),},};diff --git a/src/native/contracts.ts b/src/native/contracts.tsindex 8b65d99f6..99e66beb4 100644--- a/src/native/contracts.ts+++ b/src/native/contracts.ts@@ -122,10 +122,45 @@ export interface AiEditionLlmConfig {allowAgentEdits?: boolean;}+export type AiEditionLlmCredentialKind = "api-key" | "codex" | "github-device" | "github-pat";+export interface AiEditionLlmSnapshot {config: AiEditionLlmConfig | null;connectedProviders: string[];availableProviders: Array<{ id: string; label: string; authKind: string }>;+ /** Per-provider credential metadata so the UI can show `Connect via OAuth` vs `Connect via API key`. */+ credentialSummary: Array<{+ providerId: string;+ connected: boolean;+ authKind: string;+ credentialKind: AiEditionLlmCredentialKind | null;+ }>;+}++export interface AiEditionDeviceChallenge {+ verificationUri: string;+ verificationUriComplete?: string;+ userCode: string;+ deviceCode?: string;+ deviceAuthId?: string;+ intervalMs: number;+ expiresAt: number;+}++export interface AiEditionDeviceCompletionResult {+ success: boolean;+ snapshot?: AiEditionLlmSnapshot;+ error?: string;+}++export interface AiEditionLlmDisconnectResult {+ success: boolean;+ snapshot: AiEditionLlmSnapshot;+}++export interface AiEditionLlmProviderModelsResult {+ models: string[];+ error?: string;}/** One executed agent tool call, rendered as a compact "applied: …" line in@@ -168,6 +203,18 @@ export interface AiEditionChatSession {messages: AiEditionChatMessage[];}+export interface AiEditionChatBudget {+ usedTokens: number;+ budgetTokens: number;+ ratio: number;+}++export interface AiEditionChatCompactResult {+ session: AiEditionChatSession;+ summaryMessageId: string | null;+ summary: string;+}+export type NativeBridgeErrorCode =| "INVALID_REQUEST"| "UNSUPPORTED_ACTION"@@ -370,6 +417,38 @@ export type NativeBridgeRequest =payload: { providerId: string };requestId?: string;}+ | {+ domain: "aiEdition";+ action: "llm.beginDeviceAuth";+ payload: {+ providerId: "openai-oauth" | "copilot-proxy";+ /** Optional model — recorded into the config when the device flow completes. */+ model?: string;+ };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "llm.completeDeviceAuth";+ payload: {+ providerId: "openai-oauth" | "copilot-proxy";+ challenge: AiEditionDeviceChallenge;+ model?: string;+ };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "llm.disconnect";+ payload: { providerId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "llm.listProviderModels";+ payload: { providerId: string };+ requestId?: string;+ }| {domain: "aiEdition";action: "chat.run";@@ -436,6 +515,18 @@ export type NativeBridgeRequest =action: "chat.deleteSession";payload: { projectId: string; sessionId: string };requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.budget";+ payload: { projectId: string; sessionId: string };+ requestId?: string;+ }+ | {+ domain: "aiEdition";+ action: "chat.compact";+ payload: { projectId: string; sessionId: string };+ requestId?: string;};export type NativeBridgeEventName =