Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

refactor(llm): one provider stack, and a real Copilot token swap

Etienne Lescotb47d6981444b
diff --git a/electron/ai-edition/agent-provider-capabilities.test.ts b/electron/ai-edition/agent-provider-capabilities.test.ts
deleted file mode 100644
index b422f8210..000000000
--- a/electron/ai-edition/agent-provider-capabilities.test.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-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.ts
deleted file mode 100644
index b3b1996ae..000000000
--- a/electron/ai-edition/agent-provider-capabilities.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-// 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"
- | "minimax-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's thinking block is binary — `{type: "adaptive"}` (on) or
- // `{type: "disabled"}` (off, ignored on M2.x which is always-on) — not
- // the OpenAI `reasoning.effort` field, and no budget_tokens tiers like
- // native Anthropic.
- return {
- supported: true,
- strategy: "minimax-thinking",
- efforts: ANTHROPIC_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 "minimax-thinking":
- return {
- strategy: cap.strategy,
- effort,
- requestBodyPatch: { thinking: { type: "adaptive" } },
- };
- 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/caption-translate.ts b/electron/ai-edition/caption-translate.ts
index 03eeb05f8..81f3639eb 100644
--- a/electron/ai-edition/caption-translate.ts
+++ b/electron/ai-edition/caption-translate.ts
@@ -11,7 +11,9 @@
// be re-keyed exactly; anything it fails to return is simply left untranslated
// and shows the original text, which is the honest fallback for a partial run.
-import { streamLlm } from "./llm-call";
+import { HumanMessage, SystemMessage } from "@langchain/core/messages";
+import { createOpenScreenChatModel } from "./deep-agent/chat-model";
+import { extractDelta } from "./deep-agent/service";
/** One transcript segment to translate. */
export interface CaptionTranslateSegment {
@@ -134,33 +136,29 @@ export async function translateCaptionSegments(
const batch = segments.slice(i, i + batchSize);
let reply = "";
try {
- const result = await streamLlm(
- {
- provider: options.provider,
- model: options.model,
- apiKey: options.apiKey,
- baseUrl: options.baseUrl,
- reasoningEffort: options.reasoningEffort,
- accountId: options.accountId,
- signal: options.signal,
- messages: [
- { role: "system", content: SYSTEM_PROMPT },
- {
- role: "user",
- content: buildUserPrompt(batch, options.targetLanguage, options.sourceLanguage),
- },
- ],
- },
- { onTextDelta: (delta) => (reply = `${reply}${delta}`) },
+ const model = await createOpenScreenChatModel({
+ provider: options.provider,
+ model: options.model,
+ apiKey: options.apiKey,
+ baseUrl: options.baseUrl,
+ reasoningEffort: options.reasoningEffort,
+ accountId: options.accountId,
+ });
+ const result = await model.invoke(
+ [
+ new SystemMessage(SYSTEM_PROMPT),
+ new HumanMessage(buildUserPrompt(batch, options.targetLanguage, options.sourceLanguage)),
+ ],
+ { signal: options.signal },
);
- if (!result.success) {
+ reply = extractDelta(result.content);
+ if (!reply) {
return {
success: false,
segments: out,
- error: result.error ?? "The model did not return a translation.",
+ error: "The model did not return a translation.",
};
}
- reply = result.content ?? reply;
} catch (error) {
return {
success: false,
diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts
index 7c290c273..25b53f5c7 100644
--- a/electron/ai-edition/chat-service.ts
+++ b/electron/ai-edition/chat-service.ts
@@ -6,6 +6,7 @@
// ChatEventSink.
import { randomUUID } from "node:crypto";
+import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import {
type AxcutTimelineOperation,
applyTimelineOperation,
@@ -29,7 +30,6 @@ import {
shouldCompact,
} from "./chat-compaction";
import type { DocumentService } from "./document-service";
-import { streamLlm } from "./llm-call";
import type { LlmConfigStore } from "./llm-config-store";
import { PROVIDER_DEFINITIONS } from "./provider-registry";
@@ -695,27 +695,24 @@ async function tryCompactSession(opts: {
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) {
+ const { createOpenScreenChatModel } = await import("./deep-agent/chat-model");
+ const { extractDelta } = await import("./deep-agent/service");
+ const chatModel = await createOpenScreenChatModel({
+ provider,
+ model,
+ apiKey,
+ baseUrl,
+ reasoningEffort,
+ accountId,
+ });
+ const result = await chatModel.invoke([
+ new SystemMessage(COMPACTION_SYSTEM_PROMPT),
+ new HumanMessage(prompt),
+ ]);
+ summary = extractDelta(result.content);
+ if (!summary) {
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.
diff --git a/electron/ai-edition/codex-session.test.ts b/electron/ai-edition/codex-session.test.ts
deleted file mode 100644
index c8ea2b5a3..000000000
--- a/electron/ai-edition/codex-session.test.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-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: "addTrim" },
- },
- { 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: "addTrim" },
- },
- { 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: "addTrim", 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: "addTrim", 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.ts
deleted file mode 100644
index 4ce143a68..000000000
--- a/electron/ai-edition/codex-session.ts
+++ /dev/null
@@ -1,462 +0,0 @@
-// 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/deep-agent/chat-model.ts b/electron/ai-edition/deep-agent/chat-model.ts
index eb900e8a3..d62d0d754 100644
--- a/electron/ai-edition/deep-agent/chat-model.ts
+++ b/electron/ai-edition/deep-agent/chat-model.ts
@@ -8,6 +8,12 @@ import { ChatAnthropic } from "@langchain/anthropic";
import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { ChatMistralAI } from "@langchain/mistralai";
import { ChatOpenAI } from "@langchain/openai";
+import {
+ exchangeGithubCopilotRuntimeToken,
+ GITHUB_COPILOT_EDITOR_VERSION,
+ GITHUB_COPILOT_PLUGIN_VERSION,
+ GITHUB_COPILOT_USER_AGENT,
+} from "../llm-provider-auth";
import {
buildLangChainReasoningOptions,
shouldDisableModelStreamingForToolCalling,
@@ -116,14 +122,22 @@ async function createLocalProviderChatModel(
},
});
case "copilot-proxy": {
- // ponytail: GitHub Copilot runs through its own runtime-token swap;
- // for v1 we just hit the public Copilot base URL with the PAT. The
- // runtime-token refresh from axcut can land as a follow-up.
+ // Copilot does not accept the PAT directly: it is exchanged for a
+ // short-lived runtime token, which also names the base URL to use.
+ // The editor-identifying headers are part of the contract — the
+ // endpoint rejects requests without them.
+ const runtime = await exchangeGithubCopilotRuntimeToken(config.apiKey ?? "");
return new ChatOpenAI({
- apiKey: config.apiKey,
+ apiKey: runtime.token,
model: config.model,
configuration: {
- baseURL: config.baseUrl || "https://api.individual.githubcopilot.com",
+ baseURL: config.baseUrl || runtime.baseUrl || "https://api.individual.githubcopilot.com",
+ defaultHeaders: {
+ "User-Agent": GITHUB_COPILOT_USER_AGENT,
+ "Editor-Version": GITHUB_COPILOT_EDITOR_VERSION,
+ "Editor-Plugin-Version": GITHUB_COPILOT_PLUGIN_VERSION,
+ "Openai-Intent": "copilot-gpt-chat-completions",
+ },
},
});
}
diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts
index b2af0a5b6..5f0f99b85 100644
--- a/electron/ai-edition/deep-agent/service.ts
+++ b/electron/ai-edition/deep-agent/service.ts
@@ -297,7 +297,9 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeRes
}
}
-function extractDelta(content: unknown): string {
+/** Flattens LangChain MessageContent (a string, or an array of text and
+ * non-text parts) down to plain text. */
+export function extractDelta(content: unknown): string {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
let total = "";
diff --git a/electron/ai-edition/llm-call.ts b/electron/ai-edition/llm-call.ts
deleted file mode 100644
index 459487d37..000000000
--- a/electron/ai-edition/llm-call.ts
+++ /dev/null
@@ -1,736 +0,0 @@
-// Real LLM call via fetch — no LangChain dependency. Supports the
-// OpenAI-compatible `/chat/completions` endpoint (OpenAI, Mistral,
-// 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.
-//
-// 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 { 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;
- description: string;
- parameters: Record<string, unknown>;
-}
-
-export interface LlmToolCall {
- id: string;
- name: string;
- /** Raw JSON string of the arguments, exactly as the provider returned it. */
- arguments: string;
-}
-
-export type ChatMessage =
- | { role: "system" | "user"; content: string }
- | { role: "assistant"; content: string; toolCalls?: LlmToolCall[] }
- | { role: "tool"; content: string; toolCallId: string };
-
-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 {
- success: boolean;
- content?: string;
- toolCalls?: LlmToolCall[];
- error?: string;
-}
-
-export interface LlmStreamCallbacks {
- onTextDelta?: (delta: string) => void;
- onToolCall?: (call: LlmToolCall) => void;
- /** Called once with the response id (Codex / Responses API). */
- onResponseId?: (id: string) => void;
-}
-
-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> {
- if (message.role === "tool") {
- return { role: "tool", tool_call_id: message.toolCallId, content: message.content };
- }
- if (message.role === "assistant" && message.toolCalls?.length) {
- return {
- role: "assistant",
- content: message.content || null,
- tool_calls: message.toolCalls.map((call) => ({
- id: call.id,
- type: "function",
- function: { name: call.name, arguments: call.arguments },
- })),
- };
- }
- 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> {
- 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}` };
- }
- if (def.authKind === "oauth-device") {
- if (!isOauth(def.id)) {
- return { success: false, error: `Provider "${def.label}" uses OAuth — not implemented.` };
- }
- return streamCodex(opts, callbacks);
- }
- if (def.authKind === "pat") {
- if (!isPat(def.id)) {
- return {
- success: false,
- error: `Provider "${def.label}" uses a personal access token — not implemented.`,
- };
- }
- return streamCopilot(opts, callbacks);
- }
- if (def.wireProtocol === "anthropic") return streamAnthropic(opts, callbacks);
- return streamOpenAiCompatible(opts, callbacks);
-}
-
-// ─── OpenAI-compatible ──────────────────────────────────────────────────
-
-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,
- messages: opts.messages.map(toOpenAiMessage),
- stream: true,
- stream_options: { include_usage: false },
- };
- 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(
- 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) {
- // ponytail: include a sample of the upstream body so callers can see
- // whether MiniMax (or any other anthropic-shaped provider) is
- // returning a non-streaming error JSON even when stream:true was sent.
- let bodySample = "";
- if (res.body) {
- try {
- bodySample = (await new Response(res.body).text()).slice(0, 1024);
- } catch {
- /* ignore */
- }
- }
- const suffix = bodySample ? ` body=${bodySample}` : "";
- return { success: false, error: `Upstream ${res.status} ${res.statusText}${suffix}` };
- }
-
- 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 tcDelta = (delta.tool_calls ?? []) as OpenAiToolCall[];
- for (const d of tcDelta) {
- 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 model." };
- }
- return {
- success: true,
- content: text,
- toolCalls: finalCalls.length ? finalCalls : undefined,
- };
-}
-
-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}` };
- }
-}
-
-// ─── Anthropic ──────────────────────────────────────────────────────────
-
-async function streamAnthropic(
- opts: CallLlmOptions,
- cb: LlmStreamCallbacks,
-): Promise<CallLlmResult> {
- const def = getProviderDefinition(opts.provider) ?? getProviderDefinition("anthropic");
- const baseUrl = (opts.baseUrl || def?.baseUrl || "https://api.anthropic.com").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 || def?.defaultModel || "claude-haiku-4-5",
- max_tokens: 8192,
- messages: conversation.map(toAnthropicMessage),
- stream: true,
- };
- if (systemMessage) body.system = systemMessage;
- if (opts.tools?.length) {
- body.tools = opts.tools.map((tool) => ({
- name: tool.name,
- description: tool.description,
- input_schema: tool.parameters,
- }));
- }
-
- 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;
- }
- }
- if (reasoning.extraBody) Object.assign(body, reasoning.extraBody);
-
- const res = await fetch(`${baseUrl}/v1/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) {
- // ponytail: include a sample of the upstream body so callers can see
- // whether MiniMax (or any other anthropic-shaped provider) is
- // returning a non-streaming error JSON even when stream:true was sent.
- let bodySample = "";
- if (res.body) {
- try {
- bodySample = (await new Response(res.body).text()).slice(0, 1024);
- } catch {
- /* ignore */
- }
- }
- const suffix = bodySample ? ` body=${bodySample}` : "";
- return { success: false, error: `Upstream ${res.status} ${res.statusText}${suffix}` };
- }
-
- let text = "";
- const toolCalls: LlmToolCall[] = [];
- const inFlight = new Map<string, { name: string; args: string; index: number }>();
- const eventTypes = new Set<string>();
- let lastEventSample: Record<string, unknown> | undefined;
-
- for await (const event of parseAnthropicEvents(res.body)) {
- eventTypes.add(event.type);
- lastEventSample = event as Record<string, unknown>;
- 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);
- }
- }
- }
- }
-
- if (!text && toolCalls.length === 0) {
- // ponytail: include the event types that arrived + a sample of the
- // last one so the caller can tell whether the SSE stream was
- // genuinely empty, used a different event vocabulary, or carried
- // a non-text payload (e.g. thinking blocks, refusals).
- const types = Array.from(eventTypes).join(",");
- const lastSample = lastEventSample
- ? JSON.stringify(lastEventSample).slice(0, 1024)
- : "(no events parsed)";
- return {
- success: false,
- error: `Empty response from Anthropic. events=[${types}] last=${lastSample}`,
- };
- }
- 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,
- },
- ],
- };
- }
- 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;
- }
- }
- } 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-provider-auth.ts b/electron/ai-edition/llm-provider-auth.ts
index 5cf30698b..b9d1e0952 100644
--- a/electron/ai-edition/llm-provider-auth.ts
+++ b/electron/ai-edition/llm-provider-auth.ts
@@ -55,9 +55,9 @@ 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";
+export const GITHUB_COPILOT_USER_AGENT = "GitHubCopilotChat/0.26.7";
+export const GITHUB_COPILOT_EDITOR_VERSION = "vscode/1.96.2";
+export const GITHUB_COPILOT_PLUGIN_VERSION = "copilot-chat/0.26.7";
/**
* Begin the Codex (ChatGPT) device flow. Returns the user code and the
diff --git a/electron/ai-edition/provider-registry.ts b/electron/ai-edition/provider-registry.ts
index 262e9d712..c8fb047e2 100644
--- a/electron/ai-edition/provider-registry.ts
+++ b/electron/ai-edition/provider-registry.ts
@@ -116,9 +116,8 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
// ponytail: docs (platform.minimax.io) tell you to set ANTHROPIC_BASE_URL
// to https://api.minimax.io/anthropic, with the real `/messages` path
// at /anthropic/v1/messages — same convention as api.anthropic.com.
- // Every consumer of this baseUrl (the raw-fetch path in llm-call.ts
- // and the @anthropic-ai/sdk-backed ChatAnthropic in chat-model.ts)
- // appends `/v1/messages` itself, so this must NOT include `/v1`.
+ // The @anthropic-ai/sdk-backed ChatAnthropic in chat-model.ts appends
+ // `/v1/messages` itself, so this must NOT include `/v1`.
baseUrl: "https://api.minimax.io/anthropic",
envKeys: ["MINIMAX_API_KEY"],
setupHint: "Use MINIMAX_API_KEY or paste a MiniMax API key.",