graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
chatgpt-new: the ChatGPT plan through OpenAI's sign-in for open-source apps
justrach60bb397807c9
diff --git a/docs/adr/0221-chatgpt-new-sign-in.md b/docs/adr/0221-chatgpt-new-sign-in.mdnew file mode 100644index 00000000..3a3b223c--- /dev/null+++ b/docs/adr/0221-chatgpt-new-sign-in.md@@ -0,0 +1,104 @@+# 0221. The ChatGPT plan's new sign-in is an opt-in `chatgpt-new` provider; Codex stays the primary route++Status: accepted 2026-09-30++## Context++OpenAI documents a sign-in for open-source apps that run on the user's own+machine ([Sign in with ChatGPT for open-source apps](https://developers.openai.com/siwc/token-sharing-open-source)).+The user registers the app in their ChatGPT account, and its OAuth access token+pays for Responses API requests from their ChatGPT plan. The `codex` provider+signs in through the Codex CLI's client and calls the ChatGPT backend; this flow+gives Graff its own registration and uses the public+`https://api.openai.com/v1/responses`.++The route accepts less than the metered API. Probed with a plan token:++- HTTP requests must set `store: false` and `stream: true`.+ `previous_response_id`, `max_output_tokens`, `truncation`, `metadata`,+ system-role messages, `prompt_cache_options` and `prompt_cache_breakpoint`+ are rejected.+- The Responses WebSocket (`wss://api.openai.com/v1/responses`, bearer only)+ serves every listed model. On the socket `previous_response_id` chains with+ `store: false`, so a follow-up carries only its new items; a+ `generate: false` prewarm returns a chainable id; GPT-6 models accept+ `response.steer` with string or item input, end the original `incomplete`+ with reason `steered`, and stream a successor.+- `/responses/compact`, `/responses/input_tokens`, chat completions,+ embeddings, images, audio and files are not authorized. `GET /v1/models`+ works but hides newer models unless `client_version` is sent.+- Function, custom, namespaced and async tools, hosted `web_search`,+ structured outputs, reasoning summaries and in-stream `context_management`+ compaction work, and compaction items replay: a later turn answered from+ the blob alone. Other hosted tools are rejected. `service_tier: "priority"`+ is accepted and ignored.+- Prompt-cache reads are intermittent (a repeated prefix sometimes reads back+ a few thousand tokens); writes are never reported.+- Plan limits arrive as `subscription_sharing_usage_limit_exceeded` or+ `subscription_sharing_usage_unavailable`, on a 429 or mid-stream as+ `response.failed`. An expired access token is a 401 with+ `{"detail":{"error_code":"invalid_token"}}`.++## Decision++- **Codex first.** Codex stays the primary ChatGPT route: `chatgpt` still+ names its login (`/login chatgpt`, `graff login`), `codex` precedes+ `chatgpt-new` in the provider table so a bare model name and the startup+ default resolve to Codex when both are signed in, and graff never moves a+ session between the two routes on its own.+ The new route waits, fully working, for the change on OpenAI's side that+ forces the new method; switching then means pointing the `chatgpt` login+ alias and the ChatGPT defaults at `chatgpt-new`.+- **A separate `chatgpt-new` provider** (`ProviderSpec.login =+ .chatgpt_browser`, `sub_login`), not a login on `openai` or `codex`: its model+ rows carry 272k windows (`contextFor` clamps it like codex), it bills+ flat-rate, and its request shape differs from the metered API's.+- **`graff login chatgpt-new`** (or `chat-gpt-new`). The first sign-in registers with+ `client_id=dynamic_agent_client` and `agent_name_hint=Graff`; later sign-ins+ reuse the issued client id with `id_token_hint` and `login_hint`. PKCE S256,+ an OIDC nonce, `resource=https://api.openai.com/v1`, a loopback callback on+ `127.0.0.1` (port 1455, then 1456–1459), and one `ext_agent_host_id`+ (`urn:uuid:`, version 4) per machine.+- **Nothing is saved before the ID token verifies**: RS256 against the+ published JWKS, then issuer, audience (the issued client id), expiry and+ nonce. Plan usage needs the `chatgpt.tokens.use.direct` scope; a sign-in+ without it is saved but never used for requests.+- **One record per machine** in `<home>/.openai/credentials/graff-oauth.json`+ (0600, atomic), with the host id beside it. Refresh sends `resource` and the+ issued client id, near expiry or after a 401, under the existing refresh+ mutex, and never before `earliest_refresh_at`: OpenAI answers an early+ refresh with `invalid_grant`, which would otherwise read as a dead token.+ `graff logout chatgpt-new` revokes the refresh token and keeps the client id and+ host id.+- **Request shape**: no prompt-cache options or anchor (those stay keyed to+ `openai`), `reasoning.summary: "auto"`, in-stream compaction+ (`manualRoute` returns `.in_stream`), no hosted tool search, async+ `webfetch` on GPT-6 models, and RLM `llm_query` sends a streamed body and+ reads its SSE text.+- **Transport**: live turns use the Responses WebSocket like codex, chaining+ `previous_response_id` on the held socket, steering GPT-6 turns, and+ prewarming when `GRAFF_WS_PREWARM` is set. One-shot and quiet turns stay on+ HTTP, which never sends `previous_response_id`; a socket failure falls back+ to it. A chat turn closes the socket it opened.+- **Errors**: plan-usage codes fail fast, on a 429 or mid-stream, with a link+ to ChatGPT's usage settings. They are never retried as a flake and never+ fall back to another credential. `invalid_token` is an auth error: one+ refresh and retry, then the error says to sign in again.+- **Compaction**: the in-stream blob carries the prompts it pruned, so a+ history holding a blob counts as conversation state and is saved.+- **The callback page** follows codegraff.com's design, embeds its images so it+ makes no network request while the code is in the address bar, clears the+ code from the URL, and answers after the exchange so it shows the real+ outcome.+- `GRAFF_BROWSER` chooses the browser every graff sign-in opens.++## Cost++Tokens are per machine: another machine signs in again and reuses the+registration. Two ChatGPT routes coexist until the switch, so the picker+lists both. Hosted use (the gateway, hosted sandboxes) is out of scope;+OpenAI requires a separate agreement for it. The live account catalog is a+follow-up, so the offline model rows can lag a rollout. HTTP requests re-send+the whole input and caching is intermittent, so one-shot runs pay the most;+live turns chain on the socket instead. A refresh before+`earliest_refresh_at` spends the refresh token, so that gate must hold.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 15b3eca8..b4997f7b 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -247,6 +247,7 @@ record only when you need the evidence or the edge cases.| [0218](0218-background-jobs-survive-a-crash.md) | A finite root job started in the background writes its output to `.graff/job-output/<id>/` with an exit receipt from its own shell, so it outlives a crashed graff. Loading the session re-attaches this session's unreported jobs under their old ids, reports what ended while graff was down, and sweeps other sessions' stale captures. Foreground commands, servers, subagent jobs and Windows keep pipes. || [0219](0219-claude-5-5-era-request-contract.md) | Claude Opus 5.5, Sonnet 5.5 and Fable 5.1 are never forced to a tool, get `drop_block` thinking binding (with its beta header), take `/effort` as `output_config.effort` (left off at graff's default), and get 64K/128K `max_tokens`. Claude errors take the same retry-without ladder as other providers; a refusal ends the turn outside history. Default model `claude-opus-5-5`, ladder opus-5-5 → sonnet-5-5. || [0220](0220-claude-prompt-cache-forks-and-pricing.md) | On the Anthropic API, compaction's note and summary fork the conversation while its cache is warm. They use the same tools, system prompt and history, with the instruction appended, so they read the history instead of rewriting it. Otherwise the old shape runs without breakpoints. A turn-opening request keeps the TTL of the last gap inside a turn. 1-hour writes bill at 2x. 5.5-era models get graff's effort as shown; titles and recaps run at low. A second breakpoint marks where the previous request wrote. |+| [0221](0221-chatgpt-new-sign-in.md) | The ChatGPT plan's sign-in for open-source apps is its own opt-in `chatgpt-new` provider (dynamic registration, per-machine host id, RS256-verified ID token, the public Responses endpoint and WebSocket, billed flat-rate); Codex stays the primary ChatGPT route until OpenAI requires the new method. |## When to write onediff --git a/examples/edge-worker/src/remote.ts b/examples/edge-worker/src/remote.tsindex 47f4d6d5..3a161b1a 100644--- a/examples/edge-worker/src/remote.ts+++ b/examples/edge-worker/src/remote.ts@@ -11,7 +11,7 @@ export const HARNESS_VERSION = "0.13";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "claude-fable-5" | "claude-fable-5-1" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-opus-5-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "claude-sonnet-5-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemini-3-flash-preview" | "gemini-3.1-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3.5-flash" | "gemini-3.5-flash-lite" | "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash" | "gemma-4-26b-a4b-it" | "gemma-4-31b" | "gemma-4-31b-it" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5.3-flash" | "glm-5v-turbo" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-6-astra" | "gpt-6-luna" | "gpt-6-sol" | "gpt-6.1-sol" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-4.7" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k3" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "mimo-v2.6-flash" | "mimo-v2.6-pro" | "mimo-v2.6-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "muse-spark-1.2" | "muse-spark-1.2-contributor" | "openai/gpt-oss-120b" | (string & {});export type ToolName = "shell" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "agent_message" | "subagent_resume" | "learn_candidate" | "peer_message" | "workspace" | "imagegen" | "rlm";-export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";+export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex" | "chatgpt-new";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).* `seq` is a monotonic, gap-free, 1-based per-session id the bridge forwardsdiff --git a/lean-proofs/Graff/Provider.lean b/lean-proofs/Graff/Provider.leanindex 642c6b48..bab957c5 100644--- a/lean-proofs/Graff/Provider.lean+++ b/lean-proofs/Graff/Provider.lean@@ -1,7 +1,7 @@/-Provider table kernel.- Twenty-two baked rows. Each row is data: an id plus the axes `Kind`,+ Twenty-four baked rows. Each row is data: an id plus the axes `Kind`,`Auth`, login, catalog, and two bools. The program does not branch perbrand. Adding a vendor is one constructor here and one line in`provider.zig`; the Zig fixture test is the ratchet.@@ -24,6 +24,7 @@ inductive Login where| kimiDevice| xaiDevice| zaiCli+ | chatgptBrowserderiving DecidableEq, Repr, BEqinductive Catalog where@@ -68,6 +69,7 @@ def specs : List Row :=, { id := "mlx", kind := .openai, auth := .bearer }, { id := "lmstudio", kind := .openai, auth := .bearer }, { id := "codex", kind := .responses, auth := .bearer, login := .codexDevice, catalog := .codex, subLogin := true }+ , { id := "chatgpt-new", kind := .responses, auth := .bearer, login := .chatgptBrowser, subLogin := true }]def ids : List String := specs.map (·.id)@@ -86,8 +88,8 @@ def xApiKeyCount : Nat := countWhere (fun r => r.auth == .xApiKey) specsdef providerRows : Nat := specs.length-theorem provider_cube : providerRows = 23 := by native_decide-theorem responses_vendors : responsesCount = 2 := by native_decide+theorem provider_cube : providerRows = 24 := by native_decide+theorem responses_vendors : responsesCount = 3 := by native_decidetheorem one_x_api_key : xApiKeyCount = 1 := by native_decidetheorem unique_ids : unique ids = true := by native_decidediff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex f1cc450a..6a870df7 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -15,7 +15,7 @@ from typing import Iterator, List, Literal, Optional, TypedDict, UnionMODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "claude-fable-5", "claude-fable-5-1", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-opus-5-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "claude-sonnet-5-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemma-4-26b-a4b-it", "gemma-4-31b", "gemma-4-31b-it", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5.3-flash", "glm-5v-turbo", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-6-luna", "gpt-6-sol", "gpt-6.1-sol", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-4.7", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-k2.7-code", "kimi-k3", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "mimo-v2.6-flash", "mimo-v2.6-pro", "mimo-v2.6-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "muse-spark-1.2", "muse-spark-1.2-contributor", "openai/gpt-oss-120b"]TOOLS = ["shell", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "render_html", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "agent_message", "subagent_resume", "learn_candidate", "peer_message", "workspace", "imagegen", "rlm"]-PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "google", "minimax", "xiaomi", "kilo", "groq", "cerebras", "mistral", "kimi", "moonshot", "xai", "zai", "meta", "vercel", "openrouter", "fugu", "fireworks", "mlx", "lmstudio", "codex"]+PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "google", "minimax", "xiaomi", "kilo", "groq", "cerebras", "mistral", "kimi", "moonshot", "xai", "zai", "meta", "vercel", "openrouter", "fugu", "fireworks", "mlx", "lmstudio", "codex", "chatgpt-new"]class ImageUrlInput(TypedDict):diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex 35675ee9..cfcc20ca 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -13,7 +13,7 @@ export const HARNESS_VERSION = "0.13";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "claude-fable-5" | "claude-fable-5-1" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-opus-5-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "claude-sonnet-5-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemini-3-flash-preview" | "gemini-3.1-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3.5-flash" | "gemini-3.5-flash-lite" | "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash" | "gemma-4-26b-a4b-it" | "gemma-4-31b" | "gemma-4-31b-it" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5.3-flash" | "glm-5v-turbo" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-6-astra" | "gpt-6-luna" | "gpt-6-sol" | "gpt-6.1-sol" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-4.7" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k3" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "mimo-v2.6-flash" | "mimo-v2.6-pro" | "mimo-v2.6-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "muse-spark-1.2" | "muse-spark-1.2-contributor" | "openai/gpt-oss-120b" | (string & {});export type ToolName = "shell" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "agent_message" | "subagent_resume" | "learn_candidate" | "peer_message" | "workspace" | "imagegen" | "rlm";-export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";+export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex" | "chatgpt-new";/** Events streamed by `harness --json` (one JSON object per stdout line), each* discriminated by `type` — the analogue of codegraff's AgentEvent stream.diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex 47f4d6d5..3a161b1a 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -11,7 +11,7 @@ export const HARNESS_VERSION = "0.13";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "claude-fable-5" | "claude-fable-5-1" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-opus-5-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "claude-sonnet-5-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemini-3-flash-preview" | "gemini-3.1-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3.5-flash" | "gemini-3.5-flash-lite" | "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash" | "gemma-4-26b-a4b-it" | "gemma-4-31b" | "gemma-4-31b-it" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5.3-flash" | "glm-5v-turbo" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-6-astra" | "gpt-6-luna" | "gpt-6-sol" | "gpt-6.1-sol" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-4.7" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k3" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "mimo-v2.6-flash" | "mimo-v2.6-pro" | "mimo-v2.6-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "muse-spark-1.2" | "muse-spark-1.2-contributor" | "openai/gpt-oss-120b" | (string & {});export type ToolName = "shell" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "agent_message" | "subagent_resume" | "learn_candidate" | "peer_message" | "workspace" | "imagegen" | "rlm";-export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";+export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex" | "chatgpt-new";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).* `seq` is a monotonic, gap-free, 1-based per-session id the bridge forwardsdiff --git a/spec/conformance.py b/spec/conformance.pyindex 235a1f2b..90a9fd0a 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -317,10 +317,10 @@ def check_provider() -> int:ids = [r["id"] for r in PROVIDER_SPECS]if len(ids) != len(set(ids)):raise Counterexample("provider-unique", None, f"ids={ids}")- if len(PROVIDER_SPECS) != 23:- raise Counterexample("provider-count", None, f"n={len(PROVIDER_SPECS)} want=23")+ if len(PROVIDER_SPECS) != 24:+ raise Counterexample("provider-count", None, f"n={len(PROVIDER_SPECS)} want=24")responses = [r for r in PROVIDER_SPECS if r["kind"] == "responses"]- if [r["id"] for r in responses] != ["openai", "codex"]:+ if [r["id"] for r in responses] != ["openai", "codex", "chatgpt-new"]:raise Counterexample("responses-vendors", None, f"{responses}")x_key = [r for r in PROVIDER_SPECS if r["auth"] == "x_api_key"]if [r["id"] for r in x_key] != ["anthropic"]:diff --git a/spec/kernels/providers.json b/spec/kernels/providers.jsonindex 3260b9a4..0766b477 100644--- a/spec/kernels/providers.json+++ b/spec/kernels/providers.json@@ -208,6 +208,15 @@"catalog": "codex","sub_login": true,"takes_effort": false+ },+ {+ "id": "chatgpt-new",+ "kind": "responses",+ "auth": "bearer",+ "login": "chatgpt_browser",+ "catalog": "baked",+ "sub_login": true,+ "takes_effort": false}]}diff --git a/spec/ref/provider.py b/spec/ref/provider.pyindex 363d43dc..93595859 100644--- a/spec/ref/provider.py+++ b/spec/ref/provider.py@@ -6,7 +6,7 @@ from typing import LiteralKind = Literal["anthropic", "openai", "responses", "interactions"]Auth = Literal["x_api_key", "bearer", "goog_api_key"]-Login = Literal["api_key", "codegraff_device", "codex_device", "kimi_device", "xai_device", "zai_cli"]+Login = Literal["api_key", "codegraff_device", "codex_device", "kimi_device", "xai_device", "zai_cli", "chatgpt_browser"]Catalog = Literal["baked", "codex", "kimi", "openai", "anthropic"]@@ -54,6 +54,7 @@ SPECS: list[dict] = [row("mlx", "openai", "bearer"),row("lmstudio", "openai", "bearer"),row("codex", "responses", "bearer", login="codex_device", catalog="codex", sub_login=True),+ row("chatgpt-new", "responses", "bearer", login="chatgpt_browser", sub_login=True),]diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zigindex 3fec847a..4dcb04a8 100644--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@ -92,7 +92,7 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too// complete with only reasoning items and zero output text.try s.write(if ((self.compaction_request or self.server_compaction_request) and !@import("effort_route.zig").mimoRoute(self.provider.id, self.provider.model)) "low" else @import("effort_route.zig").wireEffort(self.provider.id, self.provider.model, @tagName(self.reasoning)));// summary:auto streams reasoning_summary_text.delta (reasoningDelta already parses it); without it silent reasoning emits NO frames — the stall watchdog cannot tell thinking from a dead socket.- if (is_codex) {+ if (is_codex or std.mem.eql(u8, self.provider.id, "chatgpt-new")) {try s.objectField("summary");try s.write("auto");}diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zigindex febd7f89..957fcef9 100644--- a/src/agent_server_compact.zig+++ b/src/agent_server_compact.zig@@ -130,7 +130,8 @@ pub fn manualRoute(p: Provider) ManualRoute {if (p.kind != .responses) return .local;if (std.mem.eql(u8, p.id, "openai")) return .standalone;if (std.mem.eql(u8, p.id, "codegraff") and @import("provider_codegraff.zig").openaiGptFamily(p.model)) return .standalone;- if (std.mem.eql(u8, p.id, "codex")) return .in_stream;+ // The ChatGPT plan route refuses /responses/compact (ADR 0221).+ if (std.mem.eql(u8, p.id, "codex") or std.mem.eql(u8, p.id, "chatgpt-new")) return .in_stream;return .local;}diff --git a/src/args.zig b/src/args.zigindex 11e02ed6..1fe15a42 100644--- a/src/args.zig+++ b/src/args.zig@@ -44,6 +44,7 @@ pub const Flags = struct {kimi_login: bool = false,xai_login: bool = false,zai_login: bool = false,+ chatgpt_login: bool = false,help_flag: bool = false,version_flag: bool = false,print_flag: bool = false,@@ -265,12 +266,13 @@ pub fn parse(init: std.process.Init) !Flags {if (flags.positionals.items.len > 1 and std.mem.eql(u8, flags.positionals.items[1], "kimi")) flags.kimi_login = true;if (flags.positionals.items.len > 1 and std.mem.eql(u8, flags.positionals.items[1], "xai")) flags.xai_login = true;if (flags.positionals.items.len > 1 and @import("oauth_zai.zig").isLoginName(flags.positionals.items[1])) flags.zai_login = true;+ if (flags.positionals.items.len > 1 and @import("oauth_chatgpt.zig").isLoginName(flags.positionals.items[1])) flags.chatgpt_login = true;}// One-shot print mode: `harness -p "prompt"` or a bare positional prompt// (`harness "say hi"`). Subcommands (login/key) are not prompts.flags.is_subcommand = flags.positionals.items.len > 0 and- (std.mem.eql(u8, flags.positionals.items[0], "login") or std.mem.eql(u8, flags.positionals.items[0], "key") or std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn") or+ (std.mem.eql(u8, flags.positionals.items[0], "login") or std.mem.eql(u8, flags.positionals.items[0], "logout") or std.mem.eql(u8, flags.positionals.items[0], "key") or std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn") orstd.mem.eql(u8, flags.positionals.items[0], "serve") or std.mem.eql(u8, flags.positionals.items[0], "update") or std.mem.eql(u8, flags.positionals.items[0], "title") or std.mem.eql(u8, flags.positionals.items[0], "repl") or std.mem.eql(u8, flags.positionals.items[0], "tui") orstd.mem.eql(u8, flags.positionals.items[0], "worktree") or std.mem.eql(u8, flags.positionals.items[0], "sandboxes") or std.mem.eql(u8, flags.positionals.items[0], "cube") or std.mem.eql(u8, flags.positionals.items[0], "models") orstd.mem.eql(u8, flags.positionals.items[0], "remote-control") or std.mem.eql(u8, flags.positionals.items[0], "remote") or @import("acp.zig").isAcpSubcommand(flags.positionals.items[0])); // `acp` also arms ACP's stdout discipline (json_mode) — see acp.isAcpSubcommanddiff --git a/src/commands_model.zig b/src/commands_model.zigindex 8c310217..dded546e 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -370,10 +370,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;}}- // codex is the OpenAI/ChatGPT login; accept the natural aliases.+ // codex is the OpenAI/ChatGPT login; accept the natural aliases. The+ // plan's new sign-in for open-source apps is opt-in (ADR 0221).if (std.mem.eql(u8, target, "oai") or std.mem.eql(u8, target, "openai") orstd.mem.eql(u8, target, "chatgpt") or std.mem.eql(u8, target, "gpt"))target = "codex";+ if (@import("oauth_chatgpt.zig").isLoginName(target)) target = "chatgpt-new";if (std.mem.eql(u8, target, "graff")) target = "codegraff";if (std.mem.eql(u8, target, "grok")) target = "xai";if (@import("oauth_zai.zig").isLoginName(target)) target = "zai";@@ -410,6 +412,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;};+ } else if (std.mem.eql(u8, target, "chatgpt-new")) {+ @import("oauth_chatgpt.zig").login(root.io, root.gpa, arena, home) catch |err| {+ try out.print("\xe2\x9c\x97 chatgpt-new login failed: {t}\n", .{err});+ try out.flush();+ return true;+ };} else {// A pure API-key provider, or something unrecognized.if (provider_mod.specFor(target) != null) {@@ -417,7 +425,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;}- try out.print("can't log into '{s}' \xe2\x80\x94 try /login codegraff | codex | kimi | xai | zai (others: /key <provider> <key>)\n", .{target});+ try out.print("can't log into '{s}' \xe2\x80\x94 try /login codegraff | codex | chatgpt-new | kimi | xai | zai (others: /key <provider> <key>)\n", .{target});try out.flush();return true;}diff --git a/src/credential_failover.zig b/src/credential_failover.zigindex 0a73d3d5..559f73ac 100644--- a/src/credential_failover.zig+++ b/src/credential_failover.zig@@ -96,6 +96,7 @@ pub fn preferPlan(.kimi_device => oauth.loadKimiOAuth(io, gpa, arena, home, false, null),.xai_device => oauth.loadXaiOAuth(io, gpa, arena, home, false, null),.zai_cli => oauth.loadZaiOAuth(io, gpa, arena, home, false, null),+ .chatgpt_browser => @import("oauth_chatgpt.zig").loadChatgptOAuth(io, gpa, arena, home, false, null),else => null,} orelse return;if (value.*) |metered| park(spec.id, metered, source.*);diff --git a/src/main.zig b/src/main.zigindex 56c6e40f..fb0bc13a 100644--- a/src/main.zig+++ b/src/main.zig@@ -562,7 +562,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("usage_trace.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig"), @import("acp_permission.zig"), @import("acp_usage.zig") };_ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig"), @import("pr_review_input.zig"), @import("pr_claim_review.zig"), @import("tui_paste_transfer.zig") };_ = .{ @import("session_catalog.zig"), @import("session_prompt.zig"), @import("session_discovery.zig") };- _ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig") }; // per-model guidance (Astra, GPT-5.6)+ _ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig"), @import("oauth_chatgpt.zig") }; // per-model guidance (Astra, GPT-5.6); ChatGPT plan sign-in_ = .{ @import("agent_empty_completion.zig"), @import("agent_model_loop.zig"), @import("publication_policy_tests.zig"), @import("jobs_completion_tests.zig") };_ = .{ @import("provider_routing_tests.zig"), @import("history_wire.zig"), @import("readline_paste_number_tests.zig"), @import("test_hooks.zig"), @import("peer_wake_loop.zig") };_ = .{ @import("list_dir_nearmiss.zig"), @import("tool_preview_tests.zig") };diff --git a/src/oauth.zig b/src/oauth.zigindex f6dd9298..e3eb75e0 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -353,9 +353,13 @@ pub fn refreshOAuthKey(io: Io, gpa: Allocator, arena: Allocator, home: []const uconst is_kimi = std.mem.eql(u8, provider_id, "kimi");const is_xai = std.mem.eql(u8, provider_id, "xai");const is_codex = std.mem.eql(u8, provider_id, "codex");- if (!is_kimi and !is_xai and !is_codex) return null;+ const is_chatgpt = std.mem.eql(u8, provider_id, "chatgpt-new");+ if (!is_kimi and !is_xai and !is_codex and !is_chatgpt) return null;oauth_refresh_mutex.lockUncancelable(io);defer oauth_refresh_mutex.unlock(io);+ // The ChatGPT plan's new sign-in keeps one record per machine (ADR 0221),+ // so the login vault never syncs it.+ if (is_chatgpt) return .{ .key = @import("oauth_chatgpt.zig").loadChatgptOAuth(io, gpa, arena, home, force, stale) orelse return null };// Vault sync (harness ADR 0005): adopt a newer login, wait while another// device refreshes, or refresh under the lease and publish the result.const live = @import("vault_live.zig").before(io, gpa, arena, home, provider_id, force, oauth_refresh_margin_s);diff --git a/src/oauth_chatgpt.zig b/src/oauth_chatgpt.zignew file mode 100644index 00000000..a6ed1fae--- /dev/null+++ b/src/oauth_chatgpt.zig@@ -0,0 +1,461 @@+//! ChatGPT plan through OpenAI's sign-in for open-source apps (ADR 0221).+//!+//! The first sign-in registers Graff in the person's ChatGPT account+//! (`client_id=dynamic_agent_client` plus `agent_name_hint`); later sign-ins+//! reuse the issued `oaiapp_…` id and skip consent. Browser PKCE with an OIDC+//! nonce, a loopback callback on 127.0.0.1, and one stable+//! `ext_agent_host_id` per machine. The record lives in+//! <home>/.openai/credentials/graff-oauth.json (0600); requests go to the+//! public Responses endpoint with the access token as the bearer.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const util = @import("util.zig");+const strFieldObj = util.strFieldObj;+const helpers = @import("oauth_helpers.zig");+const credential_store = @import("credential_store.zig");+const jwt = @import("oauth_chatgpt_jwt.zig");+const page = @import("oauth_chatgpt_page.zig");++const authorize_url = jwt.issuer ++ "/api/accounts/authorize";+const token_url = jwt.issuer ++ "/api/accounts/oauth/token";+const revoke_url = jwt.issuer ++ "/api/accounts/oauth/revoke";+pub const resource = "https://api.openai.com/v1";+const scopes = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";+pub const plan_scope = "chatgpt.tokens.use.direct";+pub const dynamic_client = "dynamic_agent_client";+pub const agent_name = "Graff";+pub const oauth_dir = ".openai";+pub const manage_usage_url = "https://chatgpt.com/settings/usage";+/// Appended to a plan-usage failure so the person knows where to look.+pub const usage_hint = "ChatGPT plan usage limit; manage usage at " ++ manage_usage_url;+const refresh_margin_s: i64 = 300;+const callback_ports = [_]u16{ 1455, 1456, 1457, 1458, 1459 };++pub fn isLoginName(name: []const u8) bool {+ return std.mem.eql(u8, name, "chatgpt-new") or std.mem.eql(u8, name, "chat-gpt-new");+}++pub fn recordPath(arena: Allocator, home: []const u8) []const u8 {+ return credential_store.oauthPath(arena, home, oauth_dir);+}++fn hostPath(arena: Allocator, home: []const u8) []const u8 {+ const dir = std.fs.path.dirname(recordPath(arena, home)) orelse return "";+ return std.fmt.allocPrint(arena, "{s}/graff-host-id", .{dir}) catch "";+}++/// One registration's saved sign-in, in the JSON shape OpenAI's docs show.+pub const Record = struct {+ email: []const u8 = "",+ subject: []const u8 = "",+ client_id: []const u8 = "",+ host_id: []const u8 = "",+ id_token: []const u8 = "",+ access: []const u8 = "",+ refresh: []const u8 = "",+ expires_at: i64 = 0,+ earliest_refresh_at: i64 = 0,+ scopes: []const []const u8 = &.{},++ pub fn planEnabled(r: Record) bool {+ for (r.scopes) |s| if (std.mem.eql(u8, s, plan_scope)) return true;+ return false;+ }+};++fn splitScopes(arena: Allocator, scope: []const u8) []const []const u8 {+ var list: std.ArrayList([]const u8) = .empty;+ var it = std.mem.tokenizeAny(u8, scope, " +");+ while (it.next()) |s| list.append(arena, s) catch break;+ return list.items;+}++pub fn parseRecord(arena: Allocator, bytes: []const u8) ?Record {+ const v = std.json.parseFromSliceLeaky(Value, arena, bytes, .{ .allocate = .alloc_always }) catch return null;+ if (v != .object) return null;+ const o = v.object;+ var r: Record = .{+ .email = strFieldObj(o, "email") orelse "",+ .subject = strFieldObj(o, "subject") orelse "",+ .client_id = strFieldObj(o, "client_id") orelse "",+ .host_id = strFieldObj(o, "ext_agent_host_id") orelse "",+ .id_token = strFieldObj(o, "id_token") orelse "",+ .access = strFieldObj(o, "access_token") orelse "",+ .refresh = strFieldObj(o, "refresh_token") orelse "",+ .expires_at = util.intFieldObj(o, "expires_at", 0),+ .earliest_refresh_at = util.intFieldObj(o, "earliest_refresh_at", 0),+ };+ if (o.get("scopes")) |s| if (s == .array) {+ var list: std.ArrayList([]const u8) = .empty;+ for (s.array.items) |item| if (item == .string) list.append(arena, item.string) catch break;+ r.scopes = list.items;+ };+ return r;+}++pub fn serializeRecord(arena: Allocator, r: Record, saved_at: []const u8) ![]const u8 {+ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena, "email", .{ .string = r.email });+ try obj.put(arena, "issuer", .{ .string = jwt.issuer });+ try obj.put(arena, "subject", .{ .string = r.subject });+ try obj.put(arena, "client_id", .{ .string = r.client_id });+ try obj.put(arena, "ext_agent_host_id", .{ .string = r.host_id });+ try obj.put(arena, "id_token", .{ .string = r.id_token });+ try obj.put(arena, "access_token", .{ .string = r.access });+ try obj.put(arena, "refresh_token", .{ .string = r.refresh });+ try obj.put(arena, "token_type", .{ .string = "Bearer" });+ try obj.put(arena, "expires_at", .{ .integer = r.expires_at });+ try obj.put(arena, "earliest_refresh_at", .{ .integer = r.earliest_refresh_at });+ var list = std.json.Array.init(arena);+ for (r.scopes) |s| try list.append(.{ .string = s });+ try obj.put(arena, "scopes", .{ .array = list });+ try obj.put(arena, "saved_at", .{ .string = saved_at });+ var aw: Io.Writer.Allocating = .init(arena);+ var json: std.json.Stringify = .{ .writer = &aw.writer };+ try json.write(Value{ .object = obj });+ return aw.writer.buffered();+}++fn readRecord(io: Io, arena: Allocator, home: []const u8) ?Record {+ const data = Io.Dir.cwd().readFileAlloc(io, recordPath(arena, home), arena, .limited(64 * 1024)) catch return null;+ return parseRecord(arena, data);+}++fn ensureDirs(io: Io, arena: Allocator, home: []const u8) void {+ const credentials = std.fs.path.dirname(recordPath(arena, home)) orelse return;+ const base = std.fs.path.dirname(credentials) orelse return;+ for ([_][]const u8{ base, credentials }) |path| {+ Io.Dir.cwd().createDir(io, path, credential_store.private_dir) catch {};+ const dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch continue;+ defer dir.close(io);+ if (builtin.os.tag != .windows) dir.setPermissions(io, credential_store.private_dir) catch {};+ }+}++fn writeRecord(io: Io, arena: Allocator, home: []const u8, r: Record) !void {+ ensureDirs(io, arena, home);+ var stamp: [24]u8 = undefined;+ const text = try serializeRecord(arena, r, helpers.rfc3339Utc(&stamp, util.unixMs(io)));+ try credential_store.replaceFile(io, Io.Dir.cwd(), recordPath(arena, home), text, credential_store.private_file);+}++/// A version-4 UUID as the `urn:uuid:` host id OpenAI accepts.+pub fn formatHostId(bytes: [16]u8) [45]u8 {+ var b = bytes;+ b[6] = (b[6] & 0x0f) | 0x40;+ b[8] = (b[8] & 0x3f) | 0x80;+ const hex = std.fmt.bytesToHex(b, .lower);+ var out: [45]u8 = undefined;+ _ = std.fmt.bufPrint(&out, "urn:uuid:{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable;+ return out;+}++/// This machine's stable host id, created once before the first sign-in.+fn hostId(io: Io, arena: Allocator, home: []const u8) ![]const u8 {+ const path = hostPath(arena, home);+ if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256))) |data| {+ const trimmed = std.mem.trim(u8, data, " \t\r\n");+ if (trimmed.len > 0) return trimmed;+ } else |_| {}+ var bytes: [16]u8 = undefined;+ io.random(&bytes);+ const id = try arena.dupe(u8, &formatHostId(bytes));+ ensureDirs(io, arena, home);+ try credential_store.replaceFile(io, Io.Dir.cwd(), path, try std.fmt.allocPrint(arena, "{s}\n", .{id}), credential_store.private_file);+ return id;+}++pub fn percentEncode(arena: Allocator, s: []const u8) ![]const u8 {+ const hex = "0123456789ABCDEF";+ var out: std.ArrayList(u8) = .empty;+ for (s) |c| {+ if (std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~')+ try out.append(arena, c)+ else+ try out.appendSlice(arena, &.{ '%', hex[c >> 4], hex[c & 15] });+ }+ return out.items;+}++pub fn percentDecode(arena: Allocator, s: []const u8) ![]const u8 {+ var out: std.ArrayList(u8) = .empty;+ var i: usize = 0;+ while (i < s.len) : (i += 1) {+ if (s[i] == '+') {+ try out.append(arena, ' ');+ } else if (s[i] == '%' and i + 2 < s.len) {+ const byte = std.fmt.parseInt(u8, s[i + 1 .. i + 3], 16) catch {+ try out.append(arena, '%');+ continue;+ };+ try out.append(arena, byte);+ i += 2;+ } else try out.append(arena, s[i]);+ }+ return out.items;+}++fn form(arena: Allocator, pairs: []const [2][]const u8) ![]const u8 {+ var out: std.ArrayList(u8) = .empty;+ for (pairs, 0..) |p, i| {+ if (i > 0) try out.append(arena, '&');+ try out.appendSlice(arena, p[0]);+ try out.append(arena, '=');+ try out.appendSlice(arena, try percentEncode(arena, p[1]));+ }+ return out.items;+}++/// Everything one authorization attempt sends, held until its callback.+pub const Attempt = struct {+ client_id: []const u8,+ redirect: []const u8,+ state: []const u8,+ nonce: []const u8,+ challenge: []const u8,+ host_id: []const u8,+ id_token_hint: []const u8 = "",+ login_hint: []const u8 = "",+};++pub fn authorizeUrl(arena: Allocator, a: Attempt) ![]const u8 {+ var pairs: std.ArrayList([2][]const u8) = .empty;+ try pairs.appendSlice(arena, &.{+ .{ "client_id", a.client_id }, .{ "response_type", "code" }, .{ "redirect_uri", a.redirect },+ .{ "scope", scopes }, .{ "resource", resource }, .{ "state", a.state },+ .{ "nonce", a.nonce }, .{ "code_challenge", a.challenge }, .{ "code_challenge_method", "S256" },+ .{ "ext_agent_host_id", a.host_id },+ });+ // The name hint belongs only to a first registration.+ if (std.mem.eql(u8, a.client_id, dynamic_client)) try pairs.append(arena, .{ "agent_name_hint", agent_name });+ if (a.id_token_hint.len > 0) try pairs.append(arena, .{ "id_token_hint", a.id_token_hint });+ if (a.login_hint.len > 0) try pairs.append(arena, .{ "login_hint", a.login_hint });+ return std.fmt.allocPrint(arena, "{s}?{s}", .{ authorize_url, try form(arena, pairs.items) });+}++pub const Callback = struct { code: []const u8 = "", state: []const u8 = "", client_id: []const u8 = "", err: []const u8 = "", err_desc: []const u8 = "" };++/// The callback's query, or null when the request line is some other path+/// (a browser also asks for /favicon.ico).+pub fn parseCallback(arena: Allocator, req_line: []const u8) ?Callback {+ var parts = std.mem.tokenizeScalar(u8, req_line, ' ');+ _ = parts.next() orelse return null;+ const target = parts.next() orelse return null;+ const q = std.mem.indexOfScalar(u8, target, '?');+ if (!std.mem.eql(u8, target[0 .. q orelse target.len], "/auth/callback")) return null;+ var cb: Callback = .{};+ var it = std.mem.tokenizeScalar(u8, if (q) |i| target[i + 1 ..] else "", '&');+ while (it.next()) |pair| {+ const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;+ const value = percentDecode(arena, pair[eq + 1 ..]) catch continue;+ const key = pair[0..eq];+ if (std.mem.eql(u8, key, "code")) cb.code = value else if (std.mem.eql(u8, key, "state")) cb.state = value else if (std.mem.eql(u8, key, "client_id")) cb.client_id = value else if (std.mem.eql(u8, key, "error")) cb.err = value else if (std.mem.eql(u8, key, "error_description")) cb.err_desc = value;+ }+ return cb;+}++fn randomToken(io: Io, arena: Allocator, comptime n: usize) []const u8 {+ var bytes: [n]u8 = undefined;+ io.random(&bytes);+ return helpers.b64url(arena, &bytes);+}++const Listener = struct { server: std.Io.net.Server, port: u16 };++fn listen(io: Io) !Listener {+ for (callback_ports) |port| {+ var buf: [32]u8 = undefined;+ const literal = try std.fmt.bufPrint(&buf, "127.0.0.1:{d}", .{port});+ const addr = std.Io.net.IpAddress.parseLiteral(literal) catch continue;+ const server = std.Io.net.IpAddress.listen(&addr, io, .{}) catch continue;+ return .{ .server = server, .port = port };+ }+ return error.NoCallbackPort;+}++const Outcome = struct { state: page.State, account: []const u8 = "", detail: []const u8 = "" };++fn failed(detail: []const u8) Outcome {+ return .{ .state = .@"error", .detail = detail };+}++/// Validate the callback, exchange the code, check the ID token, save.+fn finish(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, saved: ?Record, a: Attempt, verifier: []const u8, cb: Callback) Outcome {+ if (!std.mem.eql(u8, cb.state, a.state)) return failed("the callback's state did not match this sign-in");+ if (std.mem.eql(u8, cb.err, "access_denied")) return .{ .state = .denied };+ if (cb.err.len > 0) return failed(std.fmt.allocPrint(arena, "{s} {s}", .{ cb.err, cb.err_desc }) catch cb.err);+ if (cb.code.len == 0) return failed("the callback carried no code");+ const returning = !std.mem.eql(u8, a.client_id, dynamic_client);+ if (returning and cb.client_id.len > 0 and !std.mem.eql(u8, cb.client_id, a.client_id)) return failed("the callback named a different app registration");+ if (!returning and (cb.client_id.len == 0 or std.mem.eql(u8, cb.client_id, dynamic_client))) return failed("the registration returned no app id");+ const issued = if (returning) a.client_id else cb.client_id;+ const body = form(arena, &.{ .{ "grant_type", "authorization_code" }, .{ "client_id", issued }, .{ "code", cb.code }, .{ "code_verifier", verifier }, .{ "redirect_uri", a.redirect }, .{ "resource", resource } }) catch return failed("out of memory");+ const tok = helpers.oauthFormPost(io, gpa, arena, token_url, body) catch |err| return failed(@errorName(err));+ if (tok.get("error")) |e| return failed(if (e == .string) e.string else "the token exchange failed");+ const access = strFieldObj(tok, "access_token") orelse return failed("the token response had no access token");+ const id_token = strFieldObj(tok, "id_token") orelse "";+ const now_s = @divTrunc(util.unixMs(io), 1000);+ const claims = jwt.verify(io, gpa, arena, id_token, issued, a.nonce, now_s) catch |err| return failed(@errorName(err));+ if (saved) |s| if (returning and s.subject.len > 0 and !std.mem.eql(u8, s.subject, claims.sub))+ return failed("signed in as a different ChatGPT account than this registration");+ const record: Record = .{+ .email = claims.email,+ .subject = claims.sub,+ .client_id = issued,+ .host_id = a.host_id,+ .id_token = id_token,+ .access = access,+ .refresh = strFieldObj(tok, "refresh_token") orelse "",+ .expires_at = now_s + util.intFieldObj(tok, "expires_in", 3600),+ .earliest_refresh_at = util.intFieldObj(tok, "earliest_refresh_at", 0),+ .scopes = splitScopes(arena, strFieldObj(tok, "scope") orelse ""),+ };+ writeRecord(io, arena, home, record) catch |err| return failed(@errorName(err));+ const state: page.State = if (!record.planEnabled()) .noplan else if (returning) .ok else .first;+ return .{ .state = state, .account = claims.email };+}++fn report(out: *Io.Writer, o: Outcome) !void {+ switch (o.state) {+ .first, .ok => try out.print("✓ signed in to ChatGPT as {s}; plan usage is on. Use it with /model chatgpt-new or `graff --model chatgpt-new/gpt-6.1-sol`. Manage usage: {s}\n", .{ o.account, manage_usage_url }),+ .noplan => try out.print("✓ signed in to ChatGPT as {s}, but plan usage was not allowed. Run `graff login chatgpt-new` again and allow it, or use an API key.\n", .{o.account}),+ .denied => try out.writeAll("✗ ChatGPT sign-in was cancelled. Nothing changed.\n"),+ .@"error" => try out.print("✗ ChatGPT sign-in failed: {s}\n", .{o.detail}),+ }+ try out.flush();+}++/// `graff login chatgpt-new`: open the browser, wait for the loopback callback,+/// answer it with the branded page, and save the record.+pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {+ var obuf: [4096]u8 = undefined;+ var ow = Io.File.stdout().writer(io, &obuf);+ const out = &ow.interface;+ const saved = readRecord(io, arena, home);+ const returning = if (saved) |s| s.client_id.len > 0 else false;+ const verifier = randomToken(io, arena, 48);+ var digest: [32]u8 = undefined;+ std.crypto.hash.sha2.Sha256.hash(verifier, &digest, .{});+ var listener = try listen(io);+ defer listener.server.deinit(io);+ const attempt: Attempt = .{+ .client_id = if (returning) saved.?.client_id else dynamic_client,+ .redirect = try std.fmt.allocPrint(arena, "http://127.0.0.1:{d}/auth/callback", .{listener.port}),+ .state = randomToken(io, arena, 24),+ .nonce = randomToken(io, arena, 24),+ .challenge = helpers.b64url(arena, &digest),+ .host_id = try hostId(io, arena, home),+ .id_token_hint = if (returning) saved.?.id_token else "",+ .login_hint = if (returning) saved.?.email else "",+ };+ const url = try authorizeUrl(arena, attempt);+ // With an id_token_hint the URL carries a credential: never print it.+ if (attempt.id_token_hint.len == 0)+ try out.print("\nSign in with ChatGPT (your browser should open it):\n\n{s}\n\n", .{url})+ else+ try out.writeAll("\nOpening your browser to sign in with ChatGPT…\n");+ try out.print("waiting for the sign-in on {s} …\n", .{attempt.redirect});+ try out.flush();+ helpers.openBrowser(io, url);+ while (true) {+ const stream = try listener.server.accept(io);+ defer stream.close(io);+ var rbuf: [16 * 1024]u8 = undefined;+ var sr = std.Io.net.Stream.Reader.init(stream, io, &rbuf);+ const req_line = (sr.interface.takeDelimiter('\n') catch null) orelse continue;+ var wbuf: [8192]u8 = undefined;+ var sw = std.Io.net.Stream.Writer.init(stream, io, &wbuf);+ const cb = parseCallback(arena, req_line) orelse {+ sw.interface.writeAll(page.not_found) catch {};+ sw.interface.flush() catch {};+ continue;+ };+ // The browser waits on this response, so the page shows the outcome.+ const outcome = finish(io, gpa, arena, home, saved, attempt, verifier, cb);+ sw.interface.writeAll(page.response(arena, outcome.state, outcome.account) catch page.not_found) catch {};+ sw.interface.flush() catch {};+ return report(out, outcome);+ }+}++var dead_refresh: u64 = 0;++fn refreshed(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, r: Record) ?Record {+ const id = std.hash.Wyhash.hash(0, r.refresh);+ if (id == dead_refresh) return null; // known dead: no round trip+ const body = form(arena, &.{ .{ "grant_type", "refresh_token" }, .{ "client_id", r.client_id }, .{ "refresh_token", r.refresh }, .{ "resource", resource } }) catch return null;+ const tok = helpers.oauthFormPost(io, gpa, arena, token_url, body) catch return null; // transient+ if (tok.get("error")) |e| {+ if (helpers.permanentRefreshFailure(if (e == .string) e.string else "")) dead_refresh = id;+ return null;+ }+ const now_s = @divTrunc(util.unixMs(io), 1000);+ var next = r;+ next.access = strFieldObj(tok, "access_token") orelse return null;+ next.refresh = strFieldObj(tok, "refresh_token") orelse r.refresh;+ next.expires_at = now_s + util.intFieldObj(tok, "expires_in", 3600);+ next.earliest_refresh_at = util.intFieldObj(tok, "earliest_refresh_at", 0);+ if (strFieldObj(tok, "scope")) |s| next.scopes = splitScopes(arena, s);+ if (strFieldObj(tok, "id_token")) |t| {+ if (jwt.verify(io, gpa, arena, t, r.client_id, null, now_s)) |_| {+ next.id_token = t;+ } else |_| {}+ }+ // The grant rotated the refresh token: an unwritten record is a logout.+ writeRecord(io, arena, home, next) catch writeRecord(io, arena, home, next) catch |err| {+ helpers.persist_error = @errorName(err);+ };+ return next;+}++/// The access token for requests, refreshed near expiry or when `force`d by+/// a 401. Null when signed out or when plan usage was not granted. Callers+/// hold oauth.refreshOAuthKey's mutex, which serializes rotating refreshes.+pub fn loadChatgptOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {+ const r = readRecord(io, arena, home) orelse return null;+ if (r.access.len == 0 or !r.planEnabled()) return null;+ if (helpers.supersededToken(force, r.access, stale)) return r.access;+ const now_s = @divTrunc(util.unixMs(io), 1000);+ // OpenAI answers a refresh before earliest_refresh_at with invalid_grant,+ // which reads as a dead token. Not even a 401 may spend it early.+ if (now_s < r.earliest_refresh_at) return r.access;+ const due = r.expires_at != 0 and now_s >= r.expires_at - refresh_margin_s;+ if (!(force or due) or r.refresh.len == 0) return r.access;+ const next = refreshed(io, gpa, arena, home, r) orelse return r.access;+ return next.access;+}++/// Sign out: revoke the refresh token, then clear the tokens. The app id,+/// account and host id stay so the next sign-in skips registration.+pub fn logout(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {+ var obuf: [1024]u8 = undefined;+ var ow = Io.File.stdout().writer(io, &obuf);+ const out = &ow.interface;+ var r = readRecord(io, arena, home) orelse {+ try out.writeAll("not signed in to ChatGPT\n");+ return out.flush();+ };+ if (r.refresh.len > 0) {+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ const body = try form(arena, &.{ .{ "token", r.refresh }, .{ "token_type_hint", "refresh_token" }, .{ "client_id", r.client_id } });+ _ = client.fetch(.{ .location = .{ .url = revoke_url }, .method = .POST, .payload = body, .headers = .{ .content_type = .{ .override = "application/x-www-form-urlencoded" } } }) catch {};+ }+ r.access = "";+ r.refresh = "";+ r.id_token = "";+ r.scopes = &.{};+ r.expires_at = 0;+ try writeRecord(io, arena, home, r);+ try out.writeAll("✓ signed out of ChatGPT on this computer\n");+ try out.flush();+}++test {+ _ = .{ @import("oauth_chatgpt_tests.zig"), @import("oauth_chatgpt_jwt.zig"), @import("oauth_chatgpt_page.zig") };+}diff --git a/src/oauth_chatgpt_jwt.zig b/src/oauth_chatgpt_jwt.zignew file mode 100644index 00000000..cf21aab2--- /dev/null+++ b/src/oauth_chatgpt_jwt.zig@@ -0,0 +1,121 @@+//! ID-token checks for the ChatGPT plan sign-in (ADR 0221): the RS256+//! signature against OpenAI's published JWKS, then issuer, audience, expiry+//! and nonce. The signature math is std.crypto's PKCS#1 v1.5 verifier; this+//! file only picks the key and reads the claims.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;+const rsa = std.crypto.Certificate.rsa;+const Sha256 = std.crypto.hash.sha2.Sha256;++pub const issuer = "https://auth.openai.com";+pub const jwks_url = issuer ++ "/.well-known/jwks.json";++pub const Claims = struct { sub: []const u8, email: []const u8 = "", exp: i64 };++fn decode(arena: Allocator, part: []const u8) ![]u8 {+ const dec = std.base64.url_safe_no_pad.Decoder;+ const buf = try arena.alloc(u8, dec.calcSizeForSlice(part) catch return error.BadIdToken);+ dec.decode(buf, part) catch return error.BadIdToken;+ return buf;+}++fn object(arena: Allocator, bytes: []const u8) !std.json.ObjectMap {+ const v = std.json.parseFromSliceLeaky(Value, arena, bytes, .{ .allocate = .alloc_always }) catch return error.BadIdToken;+ return if (v == .object) v.object else error.BadIdToken;+}++fn str(obj: std.json.ObjectMap, name: []const u8) ?[]const u8 {+ const v = obj.get(name) orelse return null;+ return if (v == .string) v.string else null;+}++fn audienceMatches(aud: ?Value, want: []const u8) bool {+ const v = aud orelse return false;+ return switch (v) {+ .string => |s| std.mem.eql(u8, s, want),+ .array => |arr| for (arr.items) |item| {+ if (item == .string and std.mem.eql(u8, item.string, want)) break true;+ } else false,+ else => false,+ };+}++/// Verify `token` with one JWK (`n`, `e` base64url) and return its claims+/// after the issuer, audience, expiry and nonce checks. A null `nonce` skips+/// that check: refresh responses carry none.+pub fn verifyWithKey(arena: Allocator, token: []const u8, n_b64: []const u8, e_b64: []const u8, audience: []const u8, nonce: ?[]const u8, now_s: i64) !Claims {+ const dot1 = std.mem.indexOfScalar(u8, token, '.') orelse return error.BadIdToken;+ const dot2 = std.mem.indexOfScalarPos(u8, token, dot1 + 1, '.') orelse return error.BadIdToken;+ const header = try object(arena, try decode(arena, token[0..dot1]));+ if (!std.mem.eql(u8, str(header, "alg") orelse "", "RS256")) return error.BadIdToken;+ const sig = try decode(arena, token[dot2 + 1 ..]);+ const n = std.mem.trimStart(u8, try decode(arena, n_b64), &.{0});+ const key = rsa.PublicKey.fromBytes(try decode(arena, e_b64), n) catch return error.UnknownSigningKey;+ switch (n.len) {+ inline 256, 384, 512 => |len| {+ if (sig.len != len) return error.BadSignature;+ rsa.PKCS1v1_5Signature.verify(len, sig[0..len].*, token[0..dot2], key, Sha256) catch return error.BadSignature;+ },+ else => return error.UnknownSigningKey,+ }+ const claims = try object(arena, try decode(arena, token[dot1 + 1 .. dot2]));+ if (!std.mem.eql(u8, str(claims, "iss") orelse "", issuer)) return error.WrongIssuer;+ if (!audienceMatches(claims.get("aud"), audience)) return error.WrongAudience;+ const exp: i64 = if (claims.get("exp")) |v| (if (v == .integer) v.integer else 0) else 0;+ if (exp < now_s - 60) return error.Expired;+ if (nonce) |want| if (!std.mem.eql(u8, str(claims, "nonce") orelse "", want)) return error.NonceMismatch;+ return .{ .sub = str(claims, "sub") orelse return error.BadIdToken, .email = str(claims, "email") orelse "", .exp = exp };+}++/// Fetch OpenAI's JWKS, pick the key the token's `kid` names, and verify.+pub fn verify(io: Io, gpa: Allocator, arena: Allocator, token: []const u8, audience: []const u8, nonce: ?[]const u8, now_s: i64) !Claims {+ const dot1 = std.mem.indexOfScalar(u8, token, '.') orelse return error.BadIdToken;+ const kid = str(try object(arena, try decode(arena, token[0..dot1])), "kid") orelse return error.BadIdToken;+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var aw: Io.Writer.Allocating = .init(arena);+ const res = try client.fetch(.{ .location = .{ .url = jwks_url }, .method = .GET, .response_writer = &aw.writer });+ if (res.status != .ok) return error.UnknownSigningKey;+ const keys = (try object(arena, aw.writer.buffered())).get("keys") orelse return error.UnknownSigningKey;+ if (keys != .array) return error.UnknownSigningKey;+ for (keys.array.items) |k| {+ if (k != .object or !std.mem.eql(u8, str(k.object, "kid") orelse "", kid)) continue;+ return verifyWithKey(arena, token, str(k.object, "n") orelse continue, str(k.object, "e") orelse continue, audience, nonce, now_s);+ }+ return error.UnknownSigningKey;+}++// A 2048-bit key and token made with openssl for these tests only:+// iss auth.openai.com, aud oaiapp_test, sub user-1, nonce n0, exp 2100-01-01.+const test_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImdyYWZmLXRlc3QiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2F1dGgub3BlbmFpLmNvbSIsImF1ZCI6Im9haWFwcF90ZXN0Iiwic3ViIjoidXNlci0xIiwiZW1haWwiOiJhQGV4YW1wbGUuY29tIiwiZXhwIjo0MTAyNDQ0ODAwLCJub25jZSI6Im4wIn0.fZDooG1-3My4XerEC_UcvTJ2aOLqUuB0Clk61W1NQMoPYJdOqhwgOmurE94MYz97CGmVoHsHVMzlZpHxBz78Fl4rg6fE2N0adoGzdUkgZyFClbtA5-r1nrqHLmbOuC6UzRQda35tzONViXC2gKBMBzedX1jkyeNb3OocEeygle93s6JSl6rIogX3mlxqTW0_hIqFG2mpruiCQc11c4w1_IYOBphewCJs6586nuO2Xu8AoKt7BB9IvmIhIgfNzufs6tpzmO6e0z9b4zrsXJcWgG-kzT7BjA-V9HWkSb8j9ke5-qm_P4Mo1qX7TLpo5IJsNx2LcwerWXeHdEV58gcugA";+const test_n = "3BnXtT30BbTxcaOT8ikBt_uq2BbhmNDOQ58iQ2NTBu2fHkc8V60jmAIPckEQmXdcX2an0Njy9qWkL8ZPVt81zxfPpvogf6Wv4udel8n--kgNE4uwm0ZJO8lCYA7dm5aBiCCttqvar8x-gQNQ08ozDPbfQt0m-_3Z091LbsszBcFiaxfyUR7pYAwiCeWv4_TOzylOi5bsZXF_Qeyo3T-TtEQdS1pDxySY4sRfNeHaC5NK3dO7_3h9eoe8WTQFclQ3FhPD69Qdd_UAQlWG2jwrkQxqh1j6U6O3Ugu0znLlYyAndv3RT4MQaHJyKy_iVZUw9JUR6Ae5z5voK_Wfd9fNuw";+const now_2026: i64 = 1_790_000_000;++test "ChatGPT ID token: a valid RS256 token verifies and yields its claims" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const claims = try verifyWithKey(arena.allocator(), test_token, test_n, "AQAB", "oaiapp_test", "n0", now_2026);+ try std.testing.expectEqualStrings("user-1", claims.sub);+ try std.testing.expectEqualStrings("[email protected]", claims.email);+ // Refresh responses carry no nonce: a null nonce skips only that check.+ _ = try verifyWithKey(arena.allocator(), test_token, test_n, "AQAB", "oaiapp_test", null, now_2026);+}++test "ChatGPT ID token: audience, nonce, expiry and signature failures are refused" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ try std.testing.expectError(error.WrongAudience, verifyWithKey(a, test_token, test_n, "AQAB", "oaiapp_other", "n0", now_2026));+ try std.testing.expectError(error.NonceMismatch, verifyWithKey(a, test_token, test_n, "AQAB", "oaiapp_test", "n1", now_2026));+ try std.testing.expectError(error.Expired, verifyWithKey(a, test_token, test_n, "AQAB", "oaiapp_test", "n0", 4_200_000_000));+ // Same header and signature over a payload whose sub was changed.+ const forged_payload = "eyJpc3MiOiJodHRwczovL2F1dGgub3BlbmFpLmNvbSIsImF1ZCI6Im9haWFwcF90ZXN0Iiwic3ViIjoidXNlci0yIiwiZW1haWwiOiJhQGV4YW1wbGUuY29tIiwiZXhwIjo0MTAyNDQ0ODAwLCJub25jZSI6Im4wIn0";+ const dot1 = std.mem.indexOfScalar(u8, test_token, '.').?;+ const dot2 = std.mem.lastIndexOfScalar(u8, test_token, '.').?;+ const forged = try std.mem.concat(a, u8, &.{ test_token[0 .. dot1 + 1], forged_payload, test_token[dot2..] });+ try std.testing.expectError(error.BadSignature, verifyWithKey(a, forged, test_n, "AQAB", "oaiapp_test", "n0", now_2026));+ try std.testing.expectError(error.BadIdToken, verifyWithKey(a, "not-a-jwt", test_n, "AQAB", "oaiapp_test", "n0", now_2026));+}diff --git a/src/oauth_chatgpt_page.zig b/src/oauth_chatgpt_page.zignew file mode 100644index 00000000..68e5df5a--- /dev/null+++ b/src/oauth_chatgpt_page.zig@@ -0,0 +1,73 @@+//! The page the ChatGPT sign-in's loopback callback answers with (ADR 0221):+//! codegraff.com's paper, ink, coral and cobalt, in light and dark, one+//! template with five states. The images are embedded, so the page makes no+//! network request while the authorization code is in the address bar, and+//! its script swaps that URL for /auth/done once it loads.++const std = @import("std");+const Allocator = std.mem.Allocator;++pub const State = enum { first, ok, noplan, denied, @"error" };++const template = @embedFile("oauth_page/chatgpt_callback.html");+const emblem = @embedFile("oauth_page/codegraff-emblem-96.png");+const art = @embedFile("oauth_page/auth-handoff-760.jpg");++fn dataUri(arena: Allocator, mime: []const u8, bytes: []const u8) ![]const u8 {+ const enc = std.base64.standard.Encoder;+ const buf = try arena.alloc(u8, enc.calcSize(bytes.len));+ return std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ mime, enc.encode(buf, bytes) });+}++fn escapeHtml(arena: Allocator, text: []const u8) ![]const u8 {+ var out: std.ArrayList(u8) = .empty;+ for (text) |c| switch (c) {+ '&' => try out.appendSlice(arena, "&"),+ '<' => try out.appendSlice(arena, "<"),+ '>' => try out.appendSlice(arena, ">"),+ '"' => try out.appendSlice(arena, """),+ '\'' => try out.appendSlice(arena, "'"),+ else => try out.append(arena, c),+ };+ return out.items;+}++/// The page body for one outcome. `account` is the signed-in email, shown in+/// the states that have one.+pub fn render(arena: Allocator, state: State, account: []const u8) ![]const u8 {+ var page: []const u8 = template;+ page = try std.mem.replaceOwned(u8, arena, page, "{{state}}", @tagName(state));+ page = try std.mem.replaceOwned(u8, arena, page, "{{account}}", try escapeHtml(arena, account));+ page = try std.mem.replaceOwned(u8, arena, page, "{{emblem}}", try dataUri(arena, "image/png", emblem));+ return std.mem.replaceOwned(u8, arena, page, "{{art}}", try dataUri(arena, "image/jpeg", art));+}++/// The whole HTTP response: not cached, no referrer, connection closed.+pub fn response(arena: Allocator, state: State, account: []const u8) ![]const u8 {+ const body = try render(arena, state, account);+ return std.fmt.allocPrint(arena, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n{s}", .{ body.len, body });+}++pub const not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";++test "ChatGPT callback page: every state renders complete, escaped and self-contained" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ for ([_]State{ .first, .ok, .noplan, .denied, .@"error" }) |state| {+ const page = try render(a, state, "[email protected]");+ const attr = try std.fmt.allocPrint(a, "data-state=\"{s}\"", .{@tagName(state)});+ try std.testing.expect(std.mem.indexOf(u8, page, attr) != null);+ try std.testing.expect(std.mem.indexOf(u8, page, "{{") == null);+ // No network fetch while the code is in the address bar.+ try std.testing.expect(std.mem.indexOf(u8, page, "src=\"http") == null);+ try std.testing.expect(std.mem.indexOf(u8, page, "data:image/jpeg;base64,") != null);+ }+ const hostile = try render(a, .ok, "<script>x</script>@example.com");+ try std.testing.expect(std.mem.indexOf(u8, hostile, "<script>x") == null);+ try std.testing.expect(std.mem.indexOf(u8, hostile, "<script>x") != null);+ const resp = try response(a, .first, "[email protected]");+ try std.testing.expect(std.mem.startsWith(u8, resp, "HTTP/1.1 200 OK\r\n"));+ try std.testing.expect(std.mem.indexOf(u8, resp, "Cache-Control: no-store\r\n") != null);+ try std.testing.expect(std.mem.indexOf(u8, resp, "Referrer-Policy: no-referrer\r\n") != null);+}diff --git a/src/oauth_chatgpt_tests.zig b/src/oauth_chatgpt_tests.zignew file mode 100644index 00000000..378da677--- /dev/null+++ b/src/oauth_chatgpt_tests.zig@@ -0,0 +1,154 @@+//! Tests for oauth_chatgpt.zig (ADR 0221), split out for the 600-line cap.+//! Everything here is offline: no browser, no token endpoint.++const std = @import("std");+const chatgpt = @import("oauth_chatgpt.zig");+const credential_store = @import("credential_store.zig");++const host = "urn:uuid:00000000-0000-4000-8000-000000000000";++test "ChatGPT sign-in: a first registration names Graff and sends every required parameter" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const url = try chatgpt.authorizeUrl(arena.allocator(), .{+ .client_id = chatgpt.dynamic_client,+ .redirect = "http://127.0.0.1:1455/auth/callback",+ .state = "st",+ .nonce = "no",+ .challenge = "ch",+ .host_id = host,+ });+ try std.testing.expect(std.mem.startsWith(u8, url, "https://auth.openai.com/api/accounts/authorize?client_id=dynamic_agent_client&"));+ for ([_][]const u8{+ "response_type=code",+ "redirect_uri=http%3A%2F%2F127.0.0.1%3A1455%2Fauth%2Fcallback",+ "scope=openid%20profile%20email%20offline_access%20resource.invoke%20chatgpt.tokens.use.direct",+ "resource=https%3A%2F%2Fapi.openai.com%2Fv1",+ "state=st",+ "nonce=no",+ "code_challenge=ch",+ "code_challenge_method=S256",+ "ext_agent_host_id=urn%3Auuid%3A00000000-0000-4000-8000-000000000000",+ "agent_name_hint=Graff",+ }) |part| try std.testing.expect(std.mem.indexOf(u8, url, part) != null);+ try std.testing.expect(std.mem.indexOf(u8, url, "id_token_hint") == null);+}++test "ChatGPT sign-in: a returning sign-in reuses the issued app id with account hints" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const url = try chatgpt.authorizeUrl(arena.allocator(), .{+ .client_id = "oaiapp_x",+ .redirect = "http://127.0.0.1:1456/auth/callback",+ .state = "st",+ .nonce = "no",+ .challenge = "ch",+ .host_id = host,+ .id_token_hint = "a.b.c",+ .login_hint = "[email protected]",+ });+ for ([_][]const u8{ "client_id=oaiapp_x&", "id_token_hint=a.b.c", "login_hint=you%40example.com", "127.0.0.1%3A1456" }) |part|+ try std.testing.expect(std.mem.indexOf(u8, url, part) != null);+ // The name hint is for first registrations only.+ try std.testing.expect(std.mem.indexOf(u8, url, "agent_name_hint") == null);+}++test "ChatGPT sign-in: callbacks decode their query and ignore other paths" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const cb = chatgpt.parseCallback(a, "GET /auth/callback?code=ac_1.x-y&scope=chatgpt.tokens.use.direct+email&state=s%2B1&client_id=oaiapp_Z HTTP/1.1\r").?;+ try std.testing.expectEqualStrings("ac_1.x-y", cb.code);+ try std.testing.expectEqualStrings("s+1", cb.state);+ try std.testing.expectEqualStrings("oaiapp_Z", cb.client_id);+ const denied = chatgpt.parseCallback(a, "GET /auth/callback?error=access_denied&state=s HTTP/1.1").?;+ try std.testing.expectEqualStrings("access_denied", denied.err);+ try std.testing.expect(chatgpt.parseCallback(a, "GET /favicon.ico HTTP/1.1") == null);+ try std.testing.expect(chatgpt.parseCallback(a, "GET /auth/callbackx?code=1 HTTP/1.1") == null);+ try std.testing.expectEqualStrings("a%20b%2Fc~d", try chatgpt.percentEncode(a, "a b/c~d"));+ try std.testing.expectEqualStrings("a b/c%", try chatgpt.percentDecode(a, "a+b%2Fc%"));+}++test "ChatGPT sign-in: the chatgpt-new provider is a flat-rate plan on the public Responses endpoint" {+ const provider = @import("provider.zig");+ const spec = provider.specFor("chatgpt-new").?;+ try std.testing.expectEqual(provider.ProviderSpec.LoginKind.chatgpt_browser, spec.login);+ try std.testing.expect(spec.sub_login);+ try std.testing.expectEqualStrings("https://api.openai.com/v1/responses", spec.url);+ try std.testing.expectEqual(@import("billing.zig").Billing.sub, @import("billing.zig").forSeat("chatgpt-new", "gpt-6.1-sol", .login));+ // The route caps input like the Codex backend and refuses /responses/compact.+ try std.testing.expectEqual(@import("pricing.zig").codex_context_window, @import("pricing.zig").contextFor("chatgpt-new", "gpt-6.1-sol"));+ const p: provider.Provider = .{ .id = "chatgpt-new", .kind = .responses, .auth = .bearer, .url = spec.url, .api_key = "", .model = "gpt-6.1-sol", .context = 270_000 };+ try std.testing.expectEqual(@import("agent_server_compact.zig").ManualRoute.in_stream, @import("agent_server_compact.zig").manualRoute(p));+}++test "ChatGPT sign-in: host ids are version-4 UUID URNs" {+ const id = chatgpt.formatHostId(@splat(0xff));+ try std.testing.expectEqualStrings("urn:uuid:ffffffff-ffff-4fff-bfff-ffffffffffff", &id);+}++const probe_record =+ \\{"email": "[email protected]", "issuer": "https://auth.openai.com", "subject": "user-1",+ \\ "client_id": "oaiapp_x", "ext_agent_host_id": "urn:uuid:1", "id_token": "a.b.c",+ \\ "access_token": "tok-1", "refresh_token": "ref-1", "token_type": "Bearer", "expires_in": 3600,+ \\ "expires_at": 4102444800, "earliest_refresh_at": 4102444000,+ \\ "scopes": ["chatgpt.tokens.use.direct", "email", "offline_access", "openid", "profile", "resource.invoke"],+ \\ "saved_at": "2026-09-30T00:00:00Z"}+;++test "ChatGPT sign-in: the saved record round-trips and reads the trial script's format" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const r = chatgpt.parseRecord(a, probe_record).?;+ try std.testing.expectEqualStrings("oaiapp_x", r.client_id);+ try std.testing.expectEqualStrings("urn:uuid:1", r.host_id);+ try std.testing.expectEqualStrings("ref-1", r.refresh);+ try std.testing.expectEqual(@as(i64, 4102444800), r.expires_at);+ try std.testing.expect(r.planEnabled());+ const again = chatgpt.parseRecord(a, try chatgpt.serializeRecord(a, r, "2026-09-30T00:00:00Z")).?;+ try std.testing.expectEqualStrings(r.access, again.access);+ try std.testing.expectEqualStrings(r.subject, again.subject);+ try std.testing.expectEqual(r.scopes.len, again.scopes.len);+ var no_plan = r;+ no_plan.scopes = &.{ "openid", "email" };+ try std.testing.expect(!no_plan.planEnabled());+}++test "ChatGPT sign-in: loading needs plan usage and never refreshes a fresh token" {+ const io = std.testing.io;+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ try std.testing.expect(chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, false, null) == null);+ try tmp.dir.createDir(io, ".openai", credential_store.private_dir);+ try tmp.dir.createDir(io, ".openai/credentials", credential_store.private_dir);+ const write = struct {+ fn record(d: std.Io.Dir, alloc: std.mem.Allocator, r: chatgpt.Record) !void {+ try credential_store.replaceFile(std.testing.io, d, ".openai/credentials/graff-oauth.json", try chatgpt.serializeRecord(alloc, r, "now"), credential_store.private_file);+ }+ };+ var r = chatgpt.parseRecord(a, probe_record).?;+ try write.record(tmp.dir, a, r);+ // Far from expiry and not forced: the saved token, with no network call.+ try std.testing.expectEqualStrings("tok-1", chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, false, null).?);+ // A 401 on a token that is no longer on disk adopts the one that is.+ try std.testing.expectEqualStrings("tok-1", chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, true, "tok-0").?);+ // A 401 on the current token before earliest_refresh_at keeps it: OpenAI+ // would answer that refresh with invalid_grant.+ try std.testing.expectEqualStrings("tok-1", chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, true, "tok-1").?);+ // Expired with nothing to refresh with: still the saved token, still offline.+ r.expires_at = 1;+ r.earliest_refresh_at = 0;+ r.refresh = "";+ try write.record(tmp.dir, a, r);+ try std.testing.expectEqualStrings("tok-1", chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, false, null).?);+ // Signed in without plan usage: nothing to send requests with.+ r.scopes = &.{ "openid", "email" };+ try write.record(tmp.dir, a, r);+ try std.testing.expect(chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, false, null) == null);+}diff --git a/src/oauth_helpers.zig b/src/oauth_helpers.zigindex bb3fd082..53b487f9 100644--- a/src/oauth_helpers.zig+++ b/src/oauth_helpers.zig@@ -92,7 +92,7 @@ pub fn writeCodexAuth(io: Io, arena: Allocator, home: []const u8, id_token: []co/// `Option<DateTime<Utc>>`). The literal "harness-login" this used to write is/// not a timestamp — tolerable in a file only `graff login` touched, not in one/// a silent mid-turn refresh now rewrites under the other CLI's feet.-fn rfc3339Utc(buf: *[24]u8, unix_ms: i64) []const u8 {+pub fn rfc3339Utc(buf: *[24]u8, unix_ms: i64) []const u8 {const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, @divFloor(unix_ms, 1000))) };const yd = es.getEpochDay().calculateYearDay();const md = yd.calculateMonthDay();@@ -536,9 +536,14 @@ test "#402: a refresh write preserves the fields the codex CLI owns" {try std.testing.expectEqual(@as(usize, 1), names);}+/// Opens `url` in the default browser, or in GRAFF_BROWSER when set (an app+/// name for `open -a` on macOS, a command elsewhere).pub fn openBrowser(io: Io, url: []const u8) void {+ const chosen: ?[]const u8 = if (std.c.getenv("GRAFF_BROWSER")) |v| std.mem.span(v) else null;const argv: []const []const u8 = if (builtin.os.tag == .macos)- &.{ "open", url }+ (if (chosen) |app| &.{ "open", "-a", app, url } else &.{ "open", url })+ else if (chosen) |cmd|+ &.{ cmd, url }else&.{ "xdg-open", url };var child = std.process.spawn(io, .{ .argv = argv, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore }) catch return;diff --git a/src/oauth_page/auth-handoff-760.jpg b/src/oauth_page/auth-handoff-760.jpgnew file mode 100644index 00000000..f8dc7fe4Binary files /dev/null and b/src/oauth_page/auth-handoff-760.jpg differdiff --git a/src/oauth_page/chatgpt_callback.html b/src/oauth_page/chatgpt_callback.htmlnew file mode 100644index 00000000..b575f03f--- /dev/null+++ b/src/oauth_page/chatgpt_callback.html@@ -0,0 +1,91 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="referrer" content="no-referrer">+<meta name="color-scheme" content="light dark">+<title>Graff · Sign in with ChatGPT</title>+<style>+:root{--paper:#f6eedf;--rice:#fffaf0;--ink:#1b1714;--ink-rgb:27 23 20;--coral:#d45a43;--coral-strong:#b3422e;--coral-hover:#bd4935;--on-coral:#fff;--cobalt:#2654d9;--panel:#2654d9;--gold:#f7a63b;--line:rgb(27 23 20 / .15);+--display:"Sinar Grotesk","Gramatika",ui-sans-serif,-apple-system,BlinkMacSystemFont,"Helvetica Neue",Arial,sans-serif;+--body:"Gramatika",ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;+--mono:"Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace}+@media (prefers-color-scheme:dark){:root{--paper:#100f0d;--rice:#191714;--ink:#f3ecdf;--ink-rgb:243 236 223;--coral:#ef8069;--coral-strong:#ef8069;--coral-hover:#f39580;--on-coral:#100f0d;--cobalt:#91adff;--panel:#1d3a8f;--gold:#ffc16b;--line:rgb(243 236 223 / .16)}}+*{box-sizing:border-box}+html,body{margin:0;min-height:100%}+body{background:var(--paper);color:var(--ink);font:400 16px/1.5 var(--body);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}+body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;opacity:.5;background-image:radial-gradient(circle at 20% 10%,rgb(var(--ink-rgb) / .06) 0 .65px,transparent .8px),radial-gradient(circle at 80% 60%,rgb(var(--ink-rgb) / .045) 0 .55px,transparent .75px);background-size:7px 7px,11px 11px}+header{position:relative;z-index:1;display:flex;align-items:center;gap:.7rem;height:4rem;padding:0 1.25rem;border-bottom:1px solid var(--line)}+header img{display:block;width:28px;height:28px;border-radius:6px}+.brand{font:600 1.125rem/1 var(--display);letter-spacing:-.025em}+.context{padding-left:.7rem;border-left:1px solid var(--line);font-size:.8125rem;color:rgb(var(--ink-rgb) / .55)}+main{position:relative;z-index:1;display:grid;grid-template-columns:minmax(0,1fr);max-width:1280px;min-height:calc(100vh - 4rem);margin:0 auto}+.copy{order:2;display:flex;align-items:center;padding:3rem 1.25rem}+.inner{width:100%;max-width:28rem}+.eyebrow{margin:0 0 1rem;font-size:.875rem;font-weight:500;color:var(--coral)}+h1{margin:0;font:600 3rem/.95 var(--display);letter-spacing:-.045em;text-wrap:balance}+.lede{margin:1.25rem 0 0;font-size:.875rem;line-height:1.5rem;color:rgb(var(--ink-rgb) / .62)}+.ledger{margin:2rem 0 0;padding:0;list-style:none;border-top:1px solid var(--line)}+.ledger li{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.25rem 1rem;padding:.75rem 0;border-bottom:1px solid var(--line);font-size:.875rem}+.ledger li>span{color:rgb(var(--ink-rgb) / .55)}+.ledger strong{font-weight:500;overflow-wrap:anywhere}+.dot{display:inline-block;width:.45rem;height:.45rem;margin:0 .5rem .1rem 0;border-radius:50%;background:var(--coral)}+.off{background:rgb(var(--ink-rgb) / .3)}+.actions{display:flex;flex-wrap:wrap;gap:.75rem;margin-top:2rem}+.btn{display:inline-flex;min-height:2.75rem;align-items:center;justify-content:center;padding:0 1.25rem;border-radius:6px;font:600 .875rem/1 var(--body);text-decoration:none;transition:color .15s,border-color .15s,background-color .15s}+.btn-primary{background:var(--coral-strong);color:var(--on-coral)}+.btn-primary:hover{background:var(--coral-hover)}+.btn-secondary{border:1px solid rgb(var(--ink-rgb) / .22);background:var(--rice);color:var(--ink)}+.btn-secondary:hover{border-color:var(--cobalt);color:var(--cobalt)}+a:focus-visible{outline:2px solid var(--gold);outline-offset:2px}+.hint{margin:1.25rem 0 0;font-size:.875rem;color:rgb(var(--ink-rgb) / .62)}+footer{margin-top:2.5rem;padding-top:1.25rem;border-top:1px solid var(--line);font-size:.75rem;line-height:1.25rem;color:rgb(var(--ink-rgb) / .48)}+aside{order:1;position:relative;min-height:250px;overflow:hidden;border-bottom:1px solid var(--line);background:var(--panel);background-clip:padding-box}+aside img{position:absolute;inset:-1px;width:calc(100% + 2px);height:calc(100% + 2px);object-fit:cover}+.caption{position:absolute;left:1.25rem;right:1.25rem;bottom:1.25rem;max-width:24rem;padding:1rem 1.25rem;border:1px solid rgb(var(--ink-rgb) / .2);background:var(--paper)}+.caption p{margin:0}+.big{font:600 1.5rem/1 var(--display);letter-spacing:-.03em}+.small{margin-top:.5rem!important;font-size:.75rem;line-height:1.25rem;color:rgb(var(--ink-rgb) / .55)}+body[data-state="first"] [data-for]:not([data-for~="first"]),+body[data-state="ok"] [data-for]:not([data-for~="ok"]),+body[data-state="noplan"] [data-for]:not([data-for~="noplan"]),+body[data-state="denied"] [data-for]:not([data-for~="denied"]),+body[data-state="error"] [data-for]:not([data-for~="error"]){display:none!important}+@media (min-width:640px){.copy{padding:4rem 2.5rem}h1{font-size:3.75rem}.lede{font-size:1rem;line-height:1.75rem}.caption{right:auto;left:1.75rem;bottom:1.75rem}}+@media (min-width:1024px){main{grid-template-columns:minmax(0,.88fr) minmax(500px,1.12fr)}.copy{order:1;padding:5rem 4rem}aside{order:2;min-height:100%;border-bottom:0;border-left:1px solid var(--line)}.caption{left:2rem;bottom:2rem}}+@media (prefers-color-scheme:dark){header img{padding:3px;background:#f3ecdf}}+@media (prefers-reduced-motion:reduce){*{transition:none!important}}+</style>+</head>+<body data-state="{{state}}">+<header><img src="{{emblem}}" alt="" width="28" height="28"><span class="brand">Graff</span><span class="context">secure sign-in</span></header>+<main>+<section class="copy"><div class="inner">+<p class="eyebrow">Sign in with ChatGPT</p>+<h1 data-for="first">You're using your ChatGPT plan.</h1>+<h1 data-for="ok">You're signed in.</h1>+<h1 data-for="noplan">Signed in. Plan usage is off.</h1>+<h1 data-for="denied">Sign-in cancelled.</h1>+<h1 data-for="error">Sign-in didn't finish.</h1>+<p class="lede" data-for="first">Eligible requests in Graff now use your ChatGPT plan. You can review usage and set limits in ChatGPT settings.</p>+<p class="lede" data-for="ok">Graff keeps using your ChatGPT plan on this computer.</p>+<p class="lede" data-for="noplan">Graff can't use your ChatGPT plan until you allow it. Sign in again and approve plan usage, or keep using an API key.</p>+<p class="lede" data-for="denied">Nothing changed. Start the sign-in again from Graff when you're ready.</p>+<p class="lede" data-for="error">Graff couldn't complete the sign-in. Graff shows what went wrong.</p>+<ul class="ledger" data-for="first ok noplan">+<li><span>Account</span><strong>{{account}}</strong></li>+<li><span>ChatGPT plan</span><strong data-for="first ok"><i class="dot"></i>In use</strong><strong data-for="noplan"><i class="dot off"></i>Not allowed</strong></li>+<li><span>Credentials</span><strong>Stored on this computer</strong></li>+</ul>+<div class="actions" data-for="first ok">+<a class="btn btn-secondary" href="https://chatgpt.com/settings/usage" target="_blank" rel="noopener noreferrer">Manage usage</a>+</div>+<p class="hint">Return to Graff to continue. You can close this tab.</p>+<footer>Graff is the open-source coding harness. Your ChatGPT tokens stay on this computer and are never sent to Codegraff.</footer>+</div></section>+<aside><img src="{{art}}" alt="Two workshop mice complete a careful handoff of a sealed envelope and a brass key."><div class="caption"><p class="big">One secure handoff. No password to remember.</p><p class="small">Sign in with ChatGPT for Graff.</p></div></aside>+</main>+<script>if(location.protocol==="http:"){try{history.replaceState(null,"","/auth/done")}catch(e){}}</script>+</body>+</html>diff --git a/src/oauth_page/codegraff-emblem-96.png b/src/oauth_page/codegraff-emblem-96.pngnew file mode 100644index 00000000..0ece595fBinary files /dev/null and b/src/oauth_page/codegraff-emblem-96.png differdiff --git a/src/picker_auth.zig b/src/picker_auth.zigindex 6f7fe763..88ea39f0 100644--- a/src/picker_auth.zig+++ b/src/picker_auth.zig@@ -81,6 +81,12 @@ pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id:source.* = .login;reloaded = true;}+ } else if (std.mem.eql(u8, provider_id, "chatgpt-new")) {+ if (@import("oauth_chatgpt.zig").loadChatgptOAuth(root.io, root.gpa, arena, home, false, null)) |k| {+ value.* = k;+ source.* = .login;+ reloaded = true;+ }}// #402: the live Agent holds its OWN Provider copy — providers.applyProviderInner// is otherwise the only writer — so refreshing Keys alone left the active@@ -320,6 +326,12 @@ pub fn offerProviderAuth(try out.flush();return;};+ } else if (std.mem.eql(u8, pid, "chatgpt-new")) {+ @import("oauth_chatgpt.zig").login(root.io, root.gpa, arena, home) catch |err| {+ try out.print("\xe2\x9c\x97 chatgpt login failed: {t}\n", .{err});+ try out.flush();+ return;+ };}reloadLoginKey(root, keys, arena, pid);} else {diff --git a/src/pricing.zig b/src/pricing.zigindex e89fb05a..2c60e7ee 100644--- a/src/pricing.zig+++ b/src/pricing.zig@@ -172,169 +172,7 @@ pub const ThinkingSupport = enum { unknown, no, both, only };// window" rejection. 270k -> compaction at 216k, ~56k below the ~272k wall.pub const codex_context_window: u64 = 270_000;-pub const model_table = [_]ModelInfo{- // Local Apple-Silicon model served by mlx-lm (mlx_lm.server, OpenAI-compatible).- .{ .provider = "mlx", .name = "mlx-community/Qwen3.6-27B-OptiQ-4bit", .context = 262_144 },- // LM Studio serves whatever model is loaded; "lmstudio" is a routing alias —- // swap for your loaded model id if LM Studio requires an exact match (GET :1234/v1/models).- .{ .provider = "lmstudio", .name = "lmstudio", .context = 200_000 },- // Anthropic: no-key/offline FALLBACK ONLY; with a key, router_catalog swaps- // in the live /v1/models list. Rows exist so boot, --schema and routing- // (the default, ladder and vision picks) resolve before that fetch.- .{ .provider = "anthropic", .name = "claude-opus-5-5", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-sonnet-5-5", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-fable-5-1", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-opus-5", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-sonnet-5", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-fable-5", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-opus-4-8", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-opus-4-7", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-opus-4-6", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-sonnet-4-6", .context = 1_000_000 },- .{ .provider = "anthropic", .name = "claude-haiku-4-5", .context = 200_000 },- .{ .provider = "anthropic", .name = "claude-opus-4-5", .context = 200_000 },- .{ .provider = "anthropic", .name = "claude-sonnet-4-5", .context = 200_000 },- .{ .provider = "deepseek", .name = "deepseek-v4-pro", .context = 1_000_000 },- .{ .provider = "deepseek", .name = "deepseek-v4-flash", .context = 1_000_000 },- .{ .provider = "deepseek", .name = "deepseek-chat", .context = 1_000_000 },- .{ .provider = "deepseek", .name = "deepseek-reasoner", .context = 1_000_000 },- .{ .provider = "openai", .name = "gpt-6-astra", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-6-sol", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-6.1-sol", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-6-luna", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-5.6", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-5.6-terra", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-5.6-luna", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-5.5", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-5.4", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-5.4-pro", .context = 1_050_000 },- .{ .provider = "openai", .name = "gpt-5.4-mini", .context = 400_000 },- .{ .provider = "openai", .name = "gpt-5.2", .context = 400_000 },- .{ .provider = "openai", .name = "gpt-5-codex", .context = 400_000 },- .{ .provider = "minimax", .name = "MiniMax-M3", .context = 512_000 },- .{ .provider = "minimax", .name = "MiniMax-M2.7", .context = 204_800 },- .{ .provider = "minimax", .name = "MiniMax-M2.5", .context = 204_800 },- .{ .provider = "xiaomi", .name = "mimo-v2.6-pro", .context = 1_048_576 },- .{ .provider = "xiaomi", .name = "mimo-v2.6-flash", .context = 1_048_576 },- .{ .provider = "xiaomi", .name = "mimo-v2.6-pro-ultraspeed", .context = 1_048_576 },- .{ .provider = "xiaomi", .name = "mimo-v2.5-pro", .context = 1_048_576 },- .{ .provider = "xiaomi", .name = "mimo-v2.5", .context = 1_048_576 },- .{ .provider = "xiaomi", .name = "mimo-v2.5-pro-ultraspeed", .context = 1_048_576 },- .{ .provider = "xiaomi", .name = "mimo-v2-flash", .context = 262_144 },- // Offline snapshot only: at startup models_cache.zig replaces the whole- // Codex slice from the account-scoped /models response (5-minute cache).- // These rows keep Codex usable when auth or discovery is unavailable.- .{ .provider = "codex", .name = "gpt-6-astra", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-6-sol", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-6.1-sol", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-5.6-sol", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-5.6-terra", .context = 272_000 },- .{ .provider = "codegraff", .name = "muse-spark-1.2", .context = 262_144 },- .{ .provider = "codegraff", .name = "muse-spark-1.2-contributor", .context = 262_144 },- .{ .provider = "meta", .name = "muse-spark-1.2", .context = 1_048_576 },- .{ .provider = "meta", .name = "muse-spark-1.2-contributor", .context = 1_048_576 },- .{ .provider = "codex", .name = "gpt-5.6-luna", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-5.5", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-5.4", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-5.4-mini", .context = 272_000 },- .{ .provider = "codex", .name = "gpt-5.3-codex-spark", .context = 128_000 },- // Sakana AI — Fugu (OpenAI-compatible chat/completions). `fugu` is the fast- // mini model, `fugu-ultra` the multi-agent reasoning conductor. Sakana does- // not publish a context window; use the harness's conservative 200k default- // (auto-compaction + #88 overflow recovery cover an underestimate safely).- .{ .provider = "fugu", .name = "fugu", .context = 200_000 },- .{ .provider = "fugu", .name = "fugu-ultra", .context = 200_000 },- .{ .provider = "fugu", .name = "fugu-ultra-20260615", .context = 200_000 },- // Fireworks AI (OpenAI-compatible, api.fireworks.ai/inference/v1). Full- // account-path model ids; context windows from models.dev (snapshot- // 2026-06-23). Not yet live-tested here (no key on hand), but the wire shape- // is the same OpenAI one fugu/deepseek use. Set FIREWORKS_API_KEY or- // `graff key set fireworks <key>`; verify the live list at .../v1/models.- .{ .provider = "fireworks", .name = "accounts/fireworks/models/deepseek-v4-pro", .context = 1_000_000 },- .{ .provider = "fireworks", .name = "accounts/fireworks/models/deepseek-v4-flash", .context = 1_000_000 },- .{ .provider = "fireworks", .name = "accounts/fireworks/models/kimi-k2p7-code", .context = 262_000 },- .{ .provider = "fireworks", .name = "accounts/fireworks/models/kimi-k2p6", .context = 262_000 },- .{ .provider = "fireworks", .name = "accounts/fireworks/models/glm-5p2", .context = 1_048_576 },- .{ .provider = "fireworks", .name = "accounts/fireworks/models/minimax-m3", .context = 512_000 },- .{ .provider = "fireworks", .name = "accounts/fireworks/models/qwen3p7-plus", .context = 262_144 },- .{ .provider = "fireworks", .name = "accounts/fireworks/models/gpt-oss-120b", .context = 131_072 },- // PR #395 providers (groq/mistral/kilo): context rows so boot and routing- // work before any live /models fetch. gpt-oss-120b matches the fireworks- // row for the same weights; kilo-auto routes dynamically, so its row- // carries the conservative small-model window.- .{ .provider = "groq", .name = "openai/gpt-oss-120b", .context = 131_072 },- // Cerebras Inference (api.cerebras.ai OpenAI chat) — not the WSE CSL SDK.- .{ .provider = "cerebras", .name = "gpt-oss-120b", .context = 131_072 },- .{ .provider = "cerebras", .name = "gemma-4-31b", .context = 131_072 },- .{ .provider = "mistral", .name = "mistral-medium-latest", .context = 131_072 },- .{ .provider = "kilo", .name = "kilo-auto/small", .context = 131_072 },- // codegraff gateway (its claude aliases use dots, so they don't collide- // with the anthropic rows above)- .{ .provider = "codegraff", .name = "claude-opus-4.8", .context = 1_000_000 },- .{ .provider = "codegraff", .name = "claude-sonnet-4.6", .context = 1_000_000 },- .{ .provider = "codegraff", .name = "deepseek-v4-pro", .context = 1_000_000 },- .{ .provider = "codegraff", .name = "deepseek-v4-flash", .context = 1_000_000 },- .{ .provider = "codegraff", .name = "minimax-m3", .context = 1_000_000 },- .{ .provider = "codegraff", .name = "gpt-6-astra", .context = 1_050_000 },- .{ .provider = "codegraff", .name = "gpt-5.6-sol", .context = 1_050_000 },- .{ .provider = "codegraff", .name = "gpt-5.6-terra", .context = 1_050_000 },- .{ .provider = "codegraff", .name = "gpt-5.6-luna", .context = 1_050_000 },- .{ .provider = "codegraff", .name = "gpt-5.6", .context = 1_050_000 },- .{ .provider = "codegraff", .name = "gpt-5.5", .context = 1_050_000 },- .{ .provider = "codegraff", .name = "kimi-k2.6", .context = 262_144 },- .{ .provider = "codegraff", .name = "grok-4.7", .context = 500_000 },- .{ .provider = "codegraff", .name = "grok-4.6", .context = 500_000 },- .{ .provider = "codegraff", .name = "grok-build", .context = 256_000 },- .{ .provider = "codegraff", .name = "glm-5.2", .context = 204_800 },- .{ .provider = "codegraff", .name = "glm-5.3-flash", .context = 202_752 },- .{ .provider = "codegraff", .name = "mimo-v2.6-pro", .context = 1_048_576 },- .{ .provider = "codegraff", .name = "mimo-v2.6-flash", .context = 1_048_576 },- .{ .provider = "codegraff", .name = "mimo-v2.5", .context = 128_000 },- .{ .provider = "codegraff", .name = "mimo-v2.5-pro", .context = 128_000 },- // Kimi Code offline fallback. Authenticated startup replaces this slice- // from /coding/v1/models; K3 is the current explicit generation while the- // two compatibility aliases keep their smaller advertised window.- .{ .provider = "kimi", .name = "k3", .context = 1_048_576, .protocol = .kimi, .supports_reasoning = true, .support_efforts = &.{ "low", "high", "max" }, .default_effort = "high" },- .{ .provider = "kimi", .name = "kimi-for-coding", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },- .{ .provider = "kimi", .name = "kimi-for-coding-highspeed", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },- .{ .provider = "moonshot", .name = "kimi-latest", .context = 131_072 },-- .{ .provider = "moonshot", .name = "kimi-k2.7-code", .context = 262_144, .supports_reasoning = true },- .{ .provider = "moonshot", .name = "kimi-k2.6", .context = 262_144, .supports_reasoning = true },- // Moonshot platform K3 (api.moonshot.ai, model id `kimi-k3`). Distinct from- // Kimi Code's native `k3` row: `--model kimi-k3` with only MOONSHOT_API_KEY- // must not rewrite onto the coding-plan login.- .{ .provider = "moonshot", .name = "kimi-k3", .context = 1_048_576, .supports_reasoning = true, .support_efforts = &.{ "low", "high", "max" }, .default_effort = "max" },- .{ .provider = "xai", .name = "grok-4.7", .context = 500_000, .supports_reasoning = true },- .{ .provider = "xai", .name = "grok-4.6", .context = 500_000, .supports_reasoning = true },- .{ .provider = "xai", .name = "grok-4.3", .context = 1_000_000 },- .{ .provider = "xai", .name = "grok-build", .context = 256_000 },- .{ .provider = "zai", .name = "glm-5.3", .context = 1_000_000, .supports_reasoning = true },- .{ .provider = "zai", .name = "glm-5.2", .context = 1_000_000, .supports_reasoning = true },- .{ .provider = "zai", .name = "glm-5-turbo", .context = 204_800, .supports_reasoning = true },- .{ .provider = "zai", .name = "glm-5v-turbo", .context = 204_800, .supports_reasoning = true },- .{ .provider = "zai", .name = "glm-5", .context = 204_800 },- .{ .provider = "zai", .name = "glm-4.7", .context = 204_800 },- .{ .provider = "zai", .name = "glm-4.5", .context = 131_072 },- // Google AI Studio. Every gemini-3.x row is the live inputTokenLimit- // (1,048,576) read from generativelanguage /v1beta/models — its- // OpenAI-compat /models omits the window entirely, so without these rows- // contextFor falls to default_context and a 1M model compacts at 160k.- // Efforts mirror the compat layer's own rejection message: "Valid values- // are: high, low, medium, minimal, none".- .{ .provider = "google", .name = "gemini-3.8-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both, .support_efforts = &.{ "minimal", "low", "medium", "high" }, .default_effort = "medium" },- .{ .provider = "google", .name = "gemini-3.7-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both, .support_efforts = &.{ "minimal", "low", "medium", "high" }, .default_effort = "medium" },- .{ .provider = "google", .name = "gemini-3.6-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },- .{ .provider = "google", .name = "gemini-3.5-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },- .{ .provider = "google", .name = "gemini-3.5-flash-lite", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },- .{ .provider = "google", .name = "gemini-3.1-pro-preview", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },- .{ .provider = "google", .name = "gemini-3.1-flash-lite", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },- .{ .provider = "google", .name = "gemini-3-flash-preview", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },- .{ .provider = "google", .name = "gemma-4-31b-it", .context = 262_144 },- .{ .provider = "google", .name = "gemma-4-26b-a4b-it", .context = 262_144 },- .{ .provider = "vercel", .name = "alibaba/qwen3.8-27b", .context = 1_000_000, .supports_reasoning = true },- .{ .provider = "openrouter", .name = "anthropic/claude-sonnet-4.6", .context = 1_000_000, .supports_reasoning = true },-};+pub const model_table = @import("pricing_models.zig").rows;/// Active catalog for routing, pickers, completion, and runtime listings./// It starts with the offline table above; authenticated Codex discovery swaps@@ -454,7 +292,8 @@ pub var context_overlay: []const ModelInfo = &.{};/// Context window for a model as served by a specific provider; falls back/// to any provider's row for the name, then to the conservative default.pub fn contextFor(provider_id: []const u8, model: []const u8) u64 {- const is_codex = std.mem.eql(u8, provider_id, "codex");+ // The ChatGPT plan route caps input like the Codex backend it shares.+ const is_codex = std.mem.eql(u8, provider_id, "codex") or std.mem.eql(u8, provider_id, "chatgpt-new");// Provider-specific baked row is authoritative (gateway gpt-5.5 = 400k, not// the API's 1.05M), so it wins over the fresh name-only overlay below.for (models()) |m| {diff --git a/src/pricing_models.zig b/src/pricing_models.zignew file mode 100644index 00000000..7e648c81--- /dev/null+++ b/src/pricing_models.zig@@ -0,0 +1,180 @@+//! The baked model catalog: provider, model name and context window, plus the+//! per-model protocol and effort facts some providers need. Live catalogs+//! (Codex, Anthropic, gateways) replace their provider's slice at startup;+//! these rows are the offline floor. Split out of pricing.zig for the+//! 600-line cap, like pricing_table.zig's prices.+const ModelInfo = @import("pricing.zig").ModelInfo;++pub const rows = [_]ModelInfo{+ // Local Apple-Silicon model served by mlx-lm (mlx_lm.server, OpenAI-compatible).+ .{ .provider = "mlx", .name = "mlx-community/Qwen3.6-27B-OptiQ-4bit", .context = 262_144 },+ // LM Studio serves whatever model is loaded; "lmstudio" is a routing alias —+ // swap for your loaded model id if LM Studio requires an exact match (GET :1234/v1/models).+ .{ .provider = "lmstudio", .name = "lmstudio", .context = 200_000 },+ // Anthropic: no-key/offline FALLBACK ONLY; with a key, router_catalog swaps+ // in the live /v1/models list. Rows exist so boot, --schema and routing+ // (the default, ladder and vision picks) resolve before that fetch.+ .{ .provider = "anthropic", .name = "claude-opus-5-5", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-sonnet-5-5", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-fable-5-1", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-opus-5", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-sonnet-5", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-fable-5", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-opus-4-8", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-opus-4-7", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-opus-4-6", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-sonnet-4-6", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-haiku-4-5", .context = 200_000 },+ .{ .provider = "anthropic", .name = "claude-opus-4-5", .context = 200_000 },+ .{ .provider = "anthropic", .name = "claude-sonnet-4-5", .context = 200_000 },+ .{ .provider = "deepseek", .name = "deepseek-v4-pro", .context = 1_000_000 },+ .{ .provider = "deepseek", .name = "deepseek-v4-flash", .context = 1_000_000 },+ .{ .provider = "deepseek", .name = "deepseek-chat", .context = 1_000_000 },+ .{ .provider = "deepseek", .name = "deepseek-reasoner", .context = 1_000_000 },+ .{ .provider = "openai", .name = "gpt-6-astra", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-6-sol", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-6.1-sol", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-6-luna", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-5.6", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-5.6-terra", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-5.6-luna", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-5.5", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-5.4", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-5.4-pro", .context = 1_050_000 },+ .{ .provider = "openai", .name = "gpt-5.4-mini", .context = 400_000 },+ .{ .provider = "openai", .name = "gpt-5.2", .context = 400_000 },+ .{ .provider = "openai", .name = "gpt-5-codex", .context = 400_000 },+ .{ .provider = "minimax", .name = "MiniMax-M3", .context = 512_000 },+ .{ .provider = "minimax", .name = "MiniMax-M2.7", .context = 204_800 },+ .{ .provider = "minimax", .name = "MiniMax-M2.5", .context = 204_800 },+ .{ .provider = "xiaomi", .name = "mimo-v2.6-pro", .context = 1_048_576 },+ .{ .provider = "xiaomi", .name = "mimo-v2.6-flash", .context = 1_048_576 },+ .{ .provider = "xiaomi", .name = "mimo-v2.6-pro-ultraspeed", .context = 1_048_576 },+ .{ .provider = "xiaomi", .name = "mimo-v2.5-pro", .context = 1_048_576 },+ .{ .provider = "xiaomi", .name = "mimo-v2.5", .context = 1_048_576 },+ .{ .provider = "xiaomi", .name = "mimo-v2.5-pro-ultraspeed", .context = 1_048_576 },+ .{ .provider = "xiaomi", .name = "mimo-v2-flash", .context = 262_144 },+ // Offline snapshot only: at startup models_cache.zig replaces the whole+ // Codex slice from the account-scoped /models response (5-minute cache).+ // These rows keep Codex usable when auth or discovery is unavailable.+ .{ .provider = "codex", .name = "gpt-6-astra", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-6-sol", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-6.1-sol", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-5.6-sol", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-5.6-terra", .context = 272_000 },+ .{ .provider = "codegraff", .name = "muse-spark-1.2", .context = 262_144 },+ .{ .provider = "codegraff", .name = "muse-spark-1.2-contributor", .context = 262_144 },+ .{ .provider = "meta", .name = "muse-spark-1.2", .context = 1_048_576 },+ .{ .provider = "meta", .name = "muse-spark-1.2-contributor", .context = 1_048_576 },+ .{ .provider = "codex", .name = "gpt-5.6-luna", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-5.5", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-5.4", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-5.4-mini", .context = 272_000 },+ .{ .provider = "codex", .name = "gpt-5.3-codex-spark", .context = 128_000 },+ // The ChatGPT plan through the new sign-in (ADR 0221): the same ~272k input+ // cap as Codex. Offline rows only; there is no live catalog for it yet.+ .{ .provider = "chatgpt-new", .name = "gpt-6.1-sol", .context = 272_000 },+ .{ .provider = "chatgpt-new", .name = "gpt-6-astra", .context = 272_000 },+ .{ .provider = "chatgpt-new", .name = "gpt-6-sol", .context = 272_000 },+ .{ .provider = "chatgpt-new", .name = "gpt-6-luna", .context = 272_000 },+ .{ .provider = "chatgpt-new", .name = "gpt-5.6-sol", .context = 272_000 },+ .{ .provider = "chatgpt-new", .name = "gpt-5.6-terra", .context = 272_000 },+ .{ .provider = "chatgpt-new", .name = "gpt-5.6-luna", .context = 272_000 },+ .{ .provider = "chatgpt-new", .name = "gpt-5.5", .context = 272_000 },+ // Sakana AI — Fugu (OpenAI-compatible chat/completions). `fugu` is the fast+ // mini model, `fugu-ultra` the multi-agent reasoning conductor. Sakana does+ // not publish a context window; use the harness's conservative 200k default+ // (auto-compaction + #88 overflow recovery cover an underestimate safely).+ .{ .provider = "fugu", .name = "fugu", .context = 200_000 },+ .{ .provider = "fugu", .name = "fugu-ultra", .context = 200_000 },+ .{ .provider = "fugu", .name = "fugu-ultra-20260615", .context = 200_000 },+ // Fireworks AI (OpenAI-compatible, api.fireworks.ai/inference/v1). Full+ // account-path model ids; context windows from models.dev (snapshot+ // 2026-06-23). Not yet live-tested here (no key on hand), but the wire shape+ // is the same OpenAI one fugu/deepseek use. Set FIREWORKS_API_KEY or+ // `graff key set fireworks <key>`; verify the live list at .../v1/models.+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/deepseek-v4-pro", .context = 1_000_000 },+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/deepseek-v4-flash", .context = 1_000_000 },+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/kimi-k2p7-code", .context = 262_000 },+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/kimi-k2p6", .context = 262_000 },+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/glm-5p2", .context = 1_048_576 },+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/minimax-m3", .context = 512_000 },+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/qwen3p7-plus", .context = 262_144 },+ .{ .provider = "fireworks", .name = "accounts/fireworks/models/gpt-oss-120b", .context = 131_072 },+ // PR #395 providers (groq/mistral/kilo): context rows so boot and routing+ // work before any live /models fetch. gpt-oss-120b matches the fireworks+ // row for the same weights; kilo-auto routes dynamically, so its row+ // carries the conservative small-model window.+ .{ .provider = "groq", .name = "openai/gpt-oss-120b", .context = 131_072 },+ // Cerebras Inference (api.cerebras.ai OpenAI chat) — not the WSE CSL SDK.+ .{ .provider = "cerebras", .name = "gpt-oss-120b", .context = 131_072 },+ .{ .provider = "cerebras", .name = "gemma-4-31b", .context = 131_072 },+ .{ .provider = "mistral", .name = "mistral-medium-latest", .context = 131_072 },+ .{ .provider = "kilo", .name = "kilo-auto/small", .context = 131_072 },+ // codegraff gateway (its claude aliases use dots, so they don't collide+ // with the anthropic rows above)+ .{ .provider = "codegraff", .name = "claude-opus-4.8", .context = 1_000_000 },+ .{ .provider = "codegraff", .name = "claude-sonnet-4.6", .context = 1_000_000 },+ .{ .provider = "codegraff", .name = "deepseek-v4-pro", .context = 1_000_000 },+ .{ .provider = "codegraff", .name = "deepseek-v4-flash", .context = 1_000_000 },+ .{ .provider = "codegraff", .name = "minimax-m3", .context = 1_000_000 },+ .{ .provider = "codegraff", .name = "gpt-6-astra", .context = 1_050_000 },+ .{ .provider = "codegraff", .name = "gpt-5.6-sol", .context = 1_050_000 },+ .{ .provider = "codegraff", .name = "gpt-5.6-terra", .context = 1_050_000 },+ .{ .provider = "codegraff", .name = "gpt-5.6-luna", .context = 1_050_000 },+ .{ .provider = "codegraff", .name = "gpt-5.6", .context = 1_050_000 },+ .{ .provider = "codegraff", .name = "gpt-5.5", .context = 1_050_000 },+ .{ .provider = "codegraff", .name = "kimi-k2.6", .context = 262_144 },+ .{ .provider = "codegraff", .name = "grok-4.7", .context = 500_000 },+ .{ .provider = "codegraff", .name = "grok-4.6", .context = 500_000 },+ .{ .provider = "codegraff", .name = "grok-build", .context = 256_000 },+ .{ .provider = "codegraff", .name = "glm-5.2", .context = 204_800 },+ .{ .provider = "codegraff", .name = "glm-5.3-flash", .context = 202_752 },+ .{ .provider = "codegraff", .name = "mimo-v2.6-pro", .context = 1_048_576 },+ .{ .provider = "codegraff", .name = "mimo-v2.6-flash", .context = 1_048_576 },+ .{ .provider = "codegraff", .name = "mimo-v2.5", .context = 128_000 },+ .{ .provider = "codegraff", .name = "mimo-v2.5-pro", .context = 128_000 },+ // Kimi Code offline fallback. Authenticated startup replaces this slice+ // from /coding/v1/models; K3 is the current explicit generation while the+ // two compatibility aliases keep their smaller advertised window.+ .{ .provider = "kimi", .name = "k3", .context = 1_048_576, .protocol = .kimi, .supports_reasoning = true, .support_efforts = &.{ "low", "high", "max" }, .default_effort = "high" },+ .{ .provider = "kimi", .name = "kimi-for-coding", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },+ .{ .provider = "kimi", .name = "kimi-for-coding-highspeed", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },+ .{ .provider = "moonshot", .name = "kimi-latest", .context = 131_072 },++ .{ .provider = "moonshot", .name = "kimi-k2.7-code", .context = 262_144, .supports_reasoning = true },+ .{ .provider = "moonshot", .name = "kimi-k2.6", .context = 262_144, .supports_reasoning = true },+ // Moonshot platform K3 (api.moonshot.ai, model id `kimi-k3`). Distinct from+ // Kimi Code's native `k3` row: `--model kimi-k3` with only MOONSHOT_API_KEY+ // must not rewrite onto the coding-plan login.+ .{ .provider = "moonshot", .name = "kimi-k3", .context = 1_048_576, .supports_reasoning = true, .support_efforts = &.{ "low", "high", "max" }, .default_effort = "max" },+ .{ .provider = "xai", .name = "grok-4.7", .context = 500_000, .supports_reasoning = true },+ .{ .provider = "xai", .name = "grok-4.6", .context = 500_000, .supports_reasoning = true },+ .{ .provider = "xai", .name = "grok-4.3", .context = 1_000_000 },+ .{ .provider = "xai", .name = "grok-build", .context = 256_000 },+ .{ .provider = "zai", .name = "glm-5.3", .context = 1_000_000, .supports_reasoning = true },+ .{ .provider = "zai", .name = "glm-5.2", .context = 1_000_000, .supports_reasoning = true },+ .{ .provider = "zai", .name = "glm-5-turbo", .context = 204_800, .supports_reasoning = true },+ .{ .provider = "zai", .name = "glm-5v-turbo", .context = 204_800, .supports_reasoning = true },+ .{ .provider = "zai", .name = "glm-5", .context = 204_800 },+ .{ .provider = "zai", .name = "glm-4.7", .context = 204_800 },+ .{ .provider = "zai", .name = "glm-4.5", .context = 131_072 },+ // Google AI Studio. Every gemini-3.x row is the live inputTokenLimit+ // (1,048,576) read from generativelanguage /v1beta/models — its+ // OpenAI-compat /models omits the window entirely, so without these rows+ // contextFor falls to default_context and a 1M model compacts at 160k.+ // Efforts mirror the compat layer's own rejection message: "Valid values+ // are: high, low, medium, minimal, none".+ .{ .provider = "google", .name = "gemini-3.8-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both, .support_efforts = &.{ "minimal", "low", "medium", "high" }, .default_effort = "medium" },+ .{ .provider = "google", .name = "gemini-3.7-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both, .support_efforts = &.{ "minimal", "low", "medium", "high" }, .default_effort = "medium" },+ .{ .provider = "google", .name = "gemini-3.6-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },+ .{ .provider = "google", .name = "gemini-3.5-flash", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },+ .{ .provider = "google", .name = "gemini-3.5-flash-lite", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },+ .{ .provider = "google", .name = "gemini-3.1-pro-preview", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },+ .{ .provider = "google", .name = "gemini-3.1-flash-lite", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },+ .{ .provider = "google", .name = "gemini-3-flash-preview", .context = 1_048_576, .supports_reasoning = true, .thinking_support = .both },+ .{ .provider = "google", .name = "gemma-4-31b-it", .context = 262_144 },+ .{ .provider = "google", .name = "gemma-4-26b-a4b-it", .context = 262_144 },+ .{ .provider = "vercel", .name = "alibaba/qwen3.8-27b", .context = 1_000_000, .supports_reasoning = true },+ .{ .provider = "openrouter", .name = "anthropic/claude-sonnet-4.6", .context = 1_000_000, .supports_reasoning = true },+};diff --git a/src/provider.zig b/src/provider.zigindex 75451e2f..545a1c46 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -45,7 +45,7 @@ fn contextWindowFor(provider_id: []const u8, model: []const u8) u64 {/// provider_specs; one additional OpenAI-compatible router may be loaded from/// `.graff/.config.router` at startup.pub const ProviderSpec = struct {- pub const LoginKind = enum { api_key, codegraff_device, codex_device, kimi_device, xai_device, zai_cli };+ pub const LoginKind = enum { api_key, codegraff_device, codex_device, kimi_device, xai_device, zai_cli, chatgpt_browser };pub const CatalogKind = enum { baked, codex, kimi, openai, anthropic };id: []const u8,@@ -130,6 +130,11 @@ pub const provider_specs = [_]ProviderSpec{// (see loadCodexAuth), the same on-disk-credential trick used for the// codegraff gateway key in ~/forge/.credentials.json..{ .id = "codex", .display_name = "Codex (ChatGPT)", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .env_key = "CODEX_DISABLED", .default_model = "gpt-5.6-sol", .login = .codex_device, .sub_login = true, .catalog = .codex },+ // chatgpt-new: the person's ChatGPT plan through OpenAI's sign-in for+ // open-source apps (ADR 0221). The key is the OAuth access token saved by+ // `graff login chatgpt-new`, sent to the public Responses endpoint. After+ // codex on purpose: Codex stays the primary ChatGPT route (spec order).+ .{ .id = "chatgpt-new", .display_name = "ChatGPT plan (new sign-in)", .kind = .responses, .auth = .bearer, .url = "https://api.openai.com/v1/responses", .env_key = "CHATGPT_NEW_DISABLED", .default_model = "gpt-6.1-sol", .login = .chatgpt_browser, .sub_login = true },};/// Optional workspace-local router loaded from `.graff/.config.router`.diff --git a/src/providers.zig b/src/providers.zigindex bf836b97..e33f4bdb 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -429,8 +429,8 @@ test "nextFallbackProvider: rotates after the failed provider and skips missingfor (provider_specs, 0..) |spec, i| ids[i] = spec.id;break :blk ids;};- const wrapped = nextFallbackProvider(all, "codex", &tried_codex, &allow_all).?;- try std.testing.expectEqualStrings("anthropic", wrapped.id);+ const last = [_][]const u8{provider_specs[provider_specs.len - 1].id}; // rotation wraps past the table end+ try std.testing.expectEqualStrings(provider_specs[0].id, nextFallbackProvider(all, last[0], &last, &allow_all).?.id);var values: [provider_specs.len]?[]const u8 = @splat(null);for (provider_specs, 0..) |spec, i| {diff --git a/src/rlm_query.zig b/src/rlm_query.zigindex 77ae45b6..f3091cfa 100644--- a/src/rlm_query.zig+++ b/src/rlm_query.zig@@ -75,7 +75,28 @@ pub fn buildBody(gpa: Allocator, provider: Provider, prompt: []const u8) ![]u8 {try s.endObject();try s.endArray();},- .responses => {+ .responses => if (std.mem.eql(u8, provider.id, "chatgpt-new")) {+ // The ChatGPT plan route takes only stored-nothing streamed+ // requests with an input array, and no output cap (ADR 0221).+ try s.objectField("input");+ try s.beginArray();+ try s.beginObject();+ try s.objectField("role");+ try s.write("user");+ try s.objectField("content");+ try s.write(prompt);+ try s.endObject();+ try s.endArray();+ try s.objectField("reasoning");+ try s.beginObject();+ try s.objectField("effort");+ try s.write("low");+ try s.endObject();+ try s.objectField("store");+ try s.write(false);+ try s.objectField("stream");+ try s.write(true);+ } else {try s.objectField("max_output_tokens");try s.write(max_out_tokens);try s.objectField("input");@@ -120,7 +141,33 @@ pub fn buildBody(gpa: Allocator, provider: Provider, prompt: []const u8) ![]u8 {return aw.toOwnedSlice();}+/// The `response.output_text.delta` text of a streamed body, or null when+/// `raw` is a plain JSON response.+fn sseText(gpa: Allocator, raw: []const u8) ?[]u8 {+ const head = std.mem.trimStart(u8, raw, " \t\r\n");+ if (!std.mem.startsWith(u8, head, "event:") and !std.mem.startsWith(u8, head, "data:")) return null;+ var out: std.ArrayList(u8) = .empty;+ var lines = std.mem.splitScalar(u8, raw, '\n');+ while (lines.next()) |line| {+ const data = std.mem.trim(u8, line, " \r");+ if (!std.mem.startsWith(u8, data, "data:")) continue;+ var parsed = std.json.parseFromSlice(Value, gpa, std.mem.trim(u8, data["data:".len..], " "), .{}) catch continue;+ defer parsed.deinit();+ if (parsed.value != .object) continue;+ const kind = tools.strField(parsed.value, "type") orelse continue;+ if (!std.mem.eql(u8, kind, "response.output_text.delta")) continue;+ out.appendSlice(gpa, tools.strField(parsed.value, "delta") orelse continue) catch {};+ }+ return out.toOwnedSlice(gpa) catch null;+}+fn extract(gpa: Allocator, kind: Provider.Kind, raw: []const u8) ToolOutput {+ if (sseText(gpa, raw)) |streamed| {+ defer gpa.free(streamed);+ const text = std.mem.trim(u8, streamed, " \t\r\n");+ if (text.len == 0) return .{ .text = gpa.dupe(u8, "rlm: llm_query returned no text") catch &.{}, .is_error = true };+ return .{ .text = gpa.dupe(u8, text) catch &.{} };+ }var parsed = std.json.parseFromSlice(Value, gpa, raw, .{}) catch {return .{ .text = gpa.dupe(u8, "rlm: llm_query returned non-JSON") catch &.{}, .is_error = true };};@@ -159,6 +206,23 @@ test "llm_query body is tools-off and carries the prompt on every wire" {}}+test "llm_query on the ChatGPT plan route streams, stores nothing and reads SSE text" {+ const gpa = std.testing.allocator;+ var p = sampleProvider(.responses);+ p.id = "chatgpt-new";+ p.model = "gpt-6.1-sol";+ const body = try buildBody(gpa, p, "hi");+ defer gpa.free(body);+ for ([_][]const u8{ "\"stream\":true", "\"store\":false", "\"role\":\"user\"" }) |part|+ try std.testing.expect(std.mem.indexOf(u8, body, part) != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "max_output_tokens") == null);+ const sse = "event: response.created\ndata: {\"type\":\"response.created\"}\n\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"4\"}\n\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"2\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"output\":[]}}\n\n";+ const out = extract(gpa, .responses, sse);+ defer gpa.free(out.text);+ try std.testing.expect(!out.is_error);+ try std.testing.expectEqualStrings("42", out.text);+}+test "llm_query extract reads assistant text from each wire shape" {const gpa = std.testing.allocator;const openai = "{\"choices\":[{\"message\":{\"content\":\"42\"}}]}";diff --git a/src/route_report.zig b/src/route_report.zigindex 2a03ce6b..5e290c93 100644--- a/src/route_report.zig+++ b/src/route_report.zig@@ -52,6 +52,7 @@ pub fn loginOnDisk(io: Io, arena: Allocator, home: []const u8, spec: provider_mo.kimi_device => credential_store.oauthPath(arena, home, ".kimi"),.xai_device => credential_store.oauthPath(arena, home, ".xai"),.zai_cli => credential_store.oauthPath(arena, home, ".zai"),+ .chatgpt_browser => credential_store.oauthPath(arena, home, ".openai"),.codex_device => blk: {const dir = oauth_helpers.codexHomeDir(arena, home) orelse return false;break :blk std.fmt.allocPrint(arena, "{s}/auth.json", .{dir}) catch return false;diff --git a/src/spec_provider_conformance.zig b/src/spec_provider_conformance.zigindex 9dc9b8fe..eda9cd95 100644--- a/src/spec_provider_conformance.zig+++ b/src/spec_provider_conformance.zig@@ -33,6 +33,7 @@ fn loginName(l: ProviderSpec.LoginKind) []const u8 {.kimi_device => "kimi_device",.xai_device => "xai_device",.zai_cli => "zai_cli",+ .chatgpt_browser => "chatgpt_browser",};}diff --git a/src/startup.zig b/src/startup.zigindex ecff8cc5..dddc7fb2 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -317,7 +317,16 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process// `codex` (or --refresh) runs the ChatGPT PKCE/refresh flow → ~/.codex/auth.json.if (flags.login_flag) {const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});- if (flags.xai_login) try oauth.xaiLogin(io, gpa, arena, home) else if (flags.kimi_login) try oauth.kimiLogin(io, gpa, arena, home) else if (flags.zai_login) try oauth.zaiLogin(io, gpa, arena, home) else if (flags.codex_login or flags.refresh_flag) try oauth.codexLogin(io, gpa, arena, home, flags.refresh_flag) else try oauth.codegraffLogin(io, gpa, arena, home);+ if (flags.chatgpt_login) try @import("oauth_chatgpt.zig").login(io, gpa, arena, home) else if (flags.xai_login) try oauth.xaiLogin(io, gpa, arena, home) else if (flags.kimi_login) try oauth.kimiLogin(io, gpa, arena, home) else if (flags.zai_login) try oauth.zaiLogin(io, gpa, arena, home) else if (flags.codex_login or flags.refresh_flag) try oauth.codexLogin(io, gpa, arena, home, flags.refresh_flag) else try oauth.codegraffLogin(io, gpa, arena, home);+ return true;+ }++ // `graff logout chatgpt-new`: revoke the plan's refresh token, clear the tokens.+ if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "logout")) {+ const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});+ const target = if (flags.positionals.items.len > 1) flags.positionals.items[1] else "";+ if (!@import("oauth_chatgpt.zig").isLoginName(target)) std.process.fatal("graff logout supports: chatgpt-new", .{});+ try @import("oauth_chatgpt.zig").logout(io, gpa, arena, home);return true;}@@ -478,6 +487,12 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.processsource.* = .login;continue;}+ } else if (spec.login == .chatgpt_browser) {+ if (@import("oauth_chatgpt.zig").loadChatgptOAuth(io, gpa, arena, home, false, null)) |tok| {+ value.* = tok;+ source.* = .login;+ continue;+ }} else if (spec.login == .codegraff_device) {if (oauth.loadCodegraffKey(io, arena, home)) |tok| {value.* = tok;