@weave-os/router 0.2.24 → 0.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,799 +0,0 @@
1
- /**
2
- * @weave-os/router — let a caller's own AI subscriptions pay for their opencode
3
- * turns, routed through the Weave Router.
4
- *
5
- * Model: a subscription is a CREDENTIAL scoped to the model family it can pay
6
- * for, not a provider you pick to force a model. You connect your ChatGPT
7
- * (Codex) and/or Claude (Pro/Max) plan once; the Weave Router routes every turn
8
- * to the best model and bills the plan that matches the model it served — and
9
- * only that. ChatGPT plan pays for GPT/Codex turns, Claude plan pays for Claude
10
- * turns, your Weave key pays for everything else. No manual provider-picking.
11
- *
12
- * opencode talks to one Responses-format `weave` provider; this plugin attaches
13
- * BOTH subscriptions to every request via the router's dedicated headers:
14
- * - POST {router}/v1/responses (Responses wire format)
15
- * - X-Weave-OpenAI-Subscription: <ChatGPT JWT> (pays GPT/Codex turns)
16
- * - X-Weave-OpenAI-Account-ID: <account id> (paired, Codex backend)
17
- * - X-Weave-Anthropic-Subscription: <sk-ant-oat token> (pays Claude turns)
18
- * - X-Weave-Router-Key: rk_... (from config options.headers)
19
- *
20
- * The router authenticates off X-Weave-Router-Key, routes the turn across all
21
- * models the caller's subs + key can pay for, and resolves the matching
22
- * subscription per the chosen provider (so the ChatGPT plan can never be billed
23
- * for a Claude/OSS turn, and vice-versa).
24
- *
25
- * opencode stores one credential per provider id and the loader's getAuth() is
26
- * scoped to its own provider, so the two logins live in two slots:
27
- * - provider `weave` : the request provider; owns the ChatGPT login and
28
- * the loader that injects both subs.
29
- * - provider `weave-claude` : login-only; owns the Claude login. Its token is
30
- * read from opencode's on-disk auth store by the
31
- * `weave` loader (the SDK has no get-by-id).
32
- * Connecting either account activates that subscription independently. With
33
- * neither connected, `weave` is a plain router provider and the Weave key pays.
34
- */
35
-
36
- import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin"
37
- import type { AssistantMessage, Message } from "@opencode-ai/sdk"
38
- import { readFile } from "node:fs/promises"
39
- import { homedir } from "node:os"
40
- import { join } from "node:path"
41
- import { CLASSIFIER_THREAD_HEADER, CLASSIFIER_UNAVAILABLE_TICKET, ClassifierThreads } from "./classifier-thread.ts"
42
- import { rewriteDirectiveParts } from "./directives.ts"
43
-
44
- // ---- ChatGPT (Codex) OAuth -------------------------------------------------
45
- const CHATGPT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
46
- // Overridable for self-hosted OpenAI auth proxies and for tests (mirrors the
47
- // bundled codex plugin's `options.issuer`).
48
- function chatGPTIssuer(): string {
49
- return process.env.WEAVE_CODEX_OAUTH_ISSUER ?? "https://auth.openai.com"
50
- }
51
- const OAUTH_PORT = 1455
52
- const OAUTH_TIMEOUT_MS = 5 * 60 * 1000
53
- const OAUTH_POLLING_SAFETY_MARGIN_MS = 3000
54
- const ACCESS_TOKEN_REFRESH_MARGIN_MS = 60 * 1000
55
-
56
- // ---- Claude (Anthropic) OAuth ----------------------------------------------
57
- // Canonical Claude Pro/Max OAuth (the same flow Claude Code uses): a manual
58
- // code-paste browser flow. Authorize on claude.ai, exchange/refresh on the
59
- // console token endpoint. The access token is an sk-ant-oat… subscription
60
- // bearer; the router applies the Bearer + oauth beta header on the upstream leg.
61
- const ANTHROPIC_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
62
- const ANTHROPIC_AUTHORIZE_BASE = process.env.WEAVE_ANTHROPIC_OAUTH_AUTHORIZE ?? "https://claude.ai"
63
- function anthropicTokenURL(): string {
64
- return process.env.WEAVE_ANTHROPIC_OAUTH_TOKEN ?? "https://console.anthropic.com/v1/oauth/token"
65
- }
66
- const ANTHROPIC_REDIRECT_URI = "https://console.anthropic.com/oauth/code/callback"
67
- const ANTHROPIC_SCOPE = "org:create_api_key user:profile user:inference"
68
-
69
- // Provider ids this plugin owns. `weave` is the request provider the installer
70
- // writes into opencode.json; `weave-claude` is login-only storage for the Claude
71
- // subscription. Deliberately NOT "openai"/"anthropic" — those ids are claimed by
72
- // opencode's bundled provider plugins, which rewrite the upstream off the router.
73
- const PROVIDER_ID = "weave"
74
- const ANTHROPIC_PROVIDER_ID = "weave-claude"
75
- const HEADER_ROUTER_MODEL = "x-router-model"
76
- const TOAST_TITLE = "Weave Router"
77
- const TOAST_DURATION_MS = 6000
78
-
79
- // Dedicated router subscription headers. Must match the constants in
80
- // internal/server/middleware/auth.go so the router stashes each sub and resolves
81
- // it per the routed provider.
82
- const HEADER_OPENAI_SUB = "X-Weave-OpenAI-Subscription"
83
- const HEADER_OPENAI_ACCOUNT_ID = "X-Weave-OpenAI-Account-ID"
84
- const HEADER_ANTHROPIC_SUB = "X-Weave-Anthropic-Subscription"
85
-
86
- // Lifecycle metadata for turn classification only (title/subagent/compaction
87
- // pin safety). Must match internal/requestcontext.OpenCodeAgentHeader; the
88
- // router ignores it for auth, billing, and provider eligibility.
89
- const HEADER_OPENCODE_AGENT = "X-Weave-OpenCode-Agent"
90
- const HEADER_OPENCODE_REQUEST_ID = "X-Weave-OpenCode-Request-ID"
91
- type OpenCodeAgent = "build" | "title" | "explore" | "compaction"
92
- const OPENCODE_AGENTS: ReadonlySet<string> = new Set<OpenCodeAgent>(["build", "title", "explore", "compaction"])
93
-
94
- function knownOpenCodeAgent(agent: string | undefined): OpenCodeAgent | undefined {
95
- return agent !== undefined && OPENCODE_AGENTS.has(agent) ? (agent as OpenCodeAgent) : undefined
96
- }
97
-
98
- // Placeholder so the @ai-sdk/openai provider considers auth configured; the
99
- // loader's fetch carries the real subscriptions in the dedicated headers and the
100
- // router authenticates off X-Weave-Router-Key, so this value is never used.
101
- const DUMMY_KEY = "weave-router-oauth"
102
- const USER_AGENT = "weave-router-opencode"
103
-
104
- interface PkceCodes {
105
- verifier: string
106
- challenge: string
107
- }
108
-
109
- function base64UrlEncode(buffer: ArrayBuffer): string {
110
- const bytes = new Uint8Array(buffer)
111
- const binary = String.fromCharCode(...bytes)
112
- return btoa(binary)
113
- .replace(/\+/g, "-")
114
- .replace(/\//g, "_")
115
- .replace(/=+$/, "")
116
- }
117
-
118
- async function generatePKCE(): Promise<PkceCodes> {
119
- // base64url of 32 random bytes → a 43-char verifier drawn uniformly from the
120
- // PKCE unreserved set (RFC 7636 §4.1). Encoding the raw bytes avoids the
121
- // modulo-on-a-CSPRNG bias that mapping bytes onto a 64-char alphabet would
122
- // introduce (and that static analysis flags).
123
- const verifier = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer)
124
- const challenge = base64UrlEncode(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)))
125
- return { verifier, challenge }
126
- }
127
-
128
- interface IdTokenClaims {
129
- chatgpt_account_id?: string
130
- organizations?: Array<{ id: string }>
131
- "https://api.openai.com/auth"?: { chatgpt_account_id?: string }
132
- }
133
-
134
- function parseJwtClaims(token: string): IdTokenClaims | undefined {
135
- const parts = token.split(".")
136
- if (parts.length !== 3) return undefined
137
- try {
138
- return JSON.parse(Buffer.from(parts[1], "base64url").toString())
139
- } catch {
140
- return undefined
141
- }
142
- }
143
-
144
- function extractAccountIdFromClaims(claims: IdTokenClaims): string | undefined {
145
- return (
146
- claims.chatgpt_account_id ||
147
- claims["https://api.openai.com/auth"]?.chatgpt_account_id ||
148
- claims.organizations?.[0]?.id
149
- )
150
- }
151
-
152
- function extractAccountId(tokens: TokenResponse): string | undefined {
153
- if (tokens.id_token) {
154
- const claims = parseJwtClaims(tokens.id_token)
155
- const accountId = claims && extractAccountIdFromClaims(claims)
156
- if (accountId) return accountId
157
- }
158
- if (tokens.access_token) {
159
- const claims = parseJwtClaims(tokens.access_token)
160
- return claims ? extractAccountIdFromClaims(claims) : undefined
161
- }
162
- return undefined
163
- }
164
-
165
- interface TokenResponse {
166
- id_token: string
167
- access_token: string
168
- refresh_token: string
169
- expires_in?: number
170
- }
171
-
172
- function buildAuthorizeUrl(redirectUri: string, pkce: PkceCodes, state: string): string {
173
- const params = new URLSearchParams({
174
- response_type: "code",
175
- client_id: CHATGPT_CLIENT_ID,
176
- redirect_uri: redirectUri,
177
- scope: "openid profile email offline_access",
178
- code_challenge: pkce.challenge,
179
- code_challenge_method: "S256",
180
- id_token_add_organizations: "true",
181
- codex_cli_simplified_flow: "true",
182
- state,
183
- originator: "codex_cli_ts",
184
- })
185
- return `${chatGPTIssuer()}/oauth/authorize?${params.toString()}`
186
- }
187
-
188
- async function exchangeCodeForTokens(code: string, redirectUri: string, pkce: PkceCodes): Promise<TokenResponse> {
189
- const response = await fetch(`${chatGPTIssuer()}/oauth/token`, {
190
- method: "POST",
191
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
192
- body: new URLSearchParams({
193
- grant_type: "authorization_code",
194
- code,
195
- redirect_uri: redirectUri,
196
- client_id: CHATGPT_CLIENT_ID,
197
- code_verifier: pkce.verifier,
198
- }).toString(),
199
- })
200
- if (!response.ok) throw new Error(`Token exchange failed: ${response.status}`)
201
- return response.json() as Promise<TokenResponse>
202
- }
203
-
204
- async function refreshAccessToken(refreshToken: string): Promise<TokenResponse> {
205
- const response = await fetch(`${chatGPTIssuer()}/oauth/token`, {
206
- method: "POST",
207
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
208
- body: new URLSearchParams({
209
- grant_type: "refresh_token",
210
- refresh_token: refreshToken,
211
- client_id: CHATGPT_CLIENT_ID,
212
- }).toString(),
213
- })
214
- if (!response.ok) throw new Error(`Token refresh failed: ${response.status}`)
215
- return response.json() as Promise<TokenResponse>
216
- }
217
-
218
- // ---- Claude (Anthropic) OAuth helpers --------------------------------------
219
-
220
- interface AnthropicTokens {
221
- access: string
222
- refresh: string
223
- expires: number
224
- }
225
-
226
- function buildAnthropicAuthorizeUrl(pkce: PkceCodes): string {
227
- const url = new URL(`${ANTHROPIC_AUTHORIZE_BASE}/oauth/authorize`)
228
- url.searchParams.set("code", "true")
229
- url.searchParams.set("client_id", ANTHROPIC_CLIENT_ID)
230
- url.searchParams.set("response_type", "code")
231
- url.searchParams.set("redirect_uri", ANTHROPIC_REDIRECT_URI)
232
- url.searchParams.set("scope", ANTHROPIC_SCOPE)
233
- url.searchParams.set("code_challenge", pkce.challenge)
234
- url.searchParams.set("code_challenge_method", "S256")
235
- // Claude Code reuses the PKCE verifier as the state value; the manual code is
236
- // returned to the user as "<code>#<state>".
237
- url.searchParams.set("state", pkce.verifier)
238
- return url.toString()
239
- }
240
-
241
- async function exchangeAnthropicCode(code: string, verifier: string): Promise<AnthropicTokens> {
242
- // The manual flow returns "<code>#<state>"; without the separator the state
243
- // would be undefined and the server would 4xx with an opaque error.
244
- if (!code.includes("#")) {
245
- throw new Error(`Expected the pasted code in "code#state" format; got: ${code.trim().slice(0, 24)}…`)
246
- }
247
- const [authCode, state] = code.trim().split("#")
248
- const response = await fetch(anthropicTokenURL(), {
249
- method: "POST",
250
- headers: { "Content-Type": "application/json" },
251
- body: JSON.stringify({
252
- grant_type: "authorization_code",
253
- code: authCode,
254
- state,
255
- client_id: ANTHROPIC_CLIENT_ID,
256
- redirect_uri: ANTHROPIC_REDIRECT_URI,
257
- code_verifier: verifier,
258
- }),
259
- })
260
- if (!response.ok) throw new Error(`Anthropic token exchange failed: ${response.status}`)
261
- const json = (await response.json()) as { access_token: string; refresh_token: string; expires_in?: number }
262
- return { access: json.access_token, refresh: json.refresh_token, expires: Date.now() + (json.expires_in ?? 3600) * 1000 }
263
- }
264
-
265
- async function refreshAnthropicToken(refreshToken: string): Promise<AnthropicTokens> {
266
- const response = await fetch(anthropicTokenURL(), {
267
- method: "POST",
268
- headers: { "Content-Type": "application/json" },
269
- body: JSON.stringify({
270
- grant_type: "refresh_token",
271
- refresh_token: refreshToken,
272
- client_id: ANTHROPIC_CLIENT_ID,
273
- }),
274
- })
275
- if (!response.ok) throw new Error(`Anthropic token refresh failed: ${response.status}`)
276
- const json = (await response.json()) as { access_token: string; refresh_token?: string; expires_in?: number }
277
- return {
278
- access: json.access_token,
279
- // OAuth 2.0 lets the issuer omit a new refresh_token on refresh; keep the
280
- // existing one in that case rather than clearing it.
281
- refresh: json.refresh_token ?? refreshToken,
282
- expires: Date.now() + (json.expires_in ?? 3600) * 1000,
283
- }
284
- }
285
-
286
- // ---- opencode auth-store reader (cross-provider) ---------------------------
287
- // The `weave` loader's getAuth() is scoped to `weave`, and the SDK exposes no
288
- // get-by-id, so the Claude credential stored under `weave-claude` is read from
289
- // opencode's on-disk auth store directly. Path mirrors opencode's Global.Path
290
- // (XDG data home + /opencode/auth.json); overridable for tests.
291
-
292
- interface StoredOAuth {
293
- type: string
294
- access?: string
295
- refresh?: string
296
- expires?: number
297
- accountId?: string
298
- }
299
-
300
- function opencodeAuthFile(): string {
301
- const override = process.env.WEAVE_OPENCODE_AUTH_FILE
302
- if (override) return override
303
- const dataHome = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share")
304
- return join(dataHome, "opencode", "auth.json")
305
- }
306
-
307
- function hasFreshAccess(auth: StoredOAuth): auth is StoredOAuth & { access: string } {
308
- return Boolean(auth.access) && (auth.expires ?? 0) > Date.now() + ACCESS_TOKEN_REFRESH_MARGIN_MS
309
- }
310
-
311
- async function readStoredOAuth(providerID: string): Promise<StoredOAuth | undefined> {
312
- try {
313
- const raw = await readFile(opencodeAuthFile(), "utf8")
314
- const entry = (JSON.parse(raw) as Record<string, StoredOAuth>)[providerID]
315
- if (entry && entry.type === "oauth") return entry
316
- } catch {
317
- // No store yet / unreadable / not logged in — no Claude sub to attach.
318
- }
319
- return undefined
320
- }
321
-
322
- // ---- Browser OAuth loopback server (PKCE, ChatGPT) -------------------------
323
-
324
- function escapeHtml(s: string): string {
325
- return s.replace(/[&<>"']/g, (c) =>
326
- ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] as string,
327
- )
328
- }
329
-
330
- const HTML_SUCCESS = `<!doctype html><html><head><title>Weave Router — authorized</title></head>
331
- <body style="font-family:system-ui;background:#131010;color:#f1ecec;display:flex;justify-content:center;align-items:center;height:100vh;margin:0">
332
- <div style="text-align:center"><h1>Authorization successful</h1><p>You can close this window and return to opencode.</p>
333
- <script>setTimeout(()=>window.close(),2000)</script></div></body></html>`
334
-
335
- const renderOAuthError = (error: string) => `<!doctype html><html><head><title>Weave Router — authorization failed</title></head>
336
- <body style="font-family:system-ui;background:#131010;color:#f1ecec;display:flex;justify-content:center;align-items:center;height:100vh;margin:0">
337
- <div style="text-align:center"><h1 style="color:#fc533a">Authorization failed</h1>
338
- <div style="color:#ff917b;font-family:monospace;margin-top:1rem;padding:1rem;background:#3c140d;border-radius:.5rem">${escapeHtml(error)}</div></div></body></html>`
339
-
340
- interface PendingOAuth {
341
- pkce: PkceCodes
342
- state: string
343
- resolve: (tokens: TokenResponse) => void
344
- reject: (error: Error) => void
345
- }
346
-
347
- let oauthServer: import("http").Server | undefined
348
- let pendingOAuth: PendingOAuth | undefined
349
-
350
- async function startOAuthServer(): Promise<{ redirectUri: string }> {
351
- const redirectUri = `http://localhost:${OAUTH_PORT}/auth/callback`
352
- if (oauthServer) return { redirectUri }
353
- const { createServer } = await import("node:http")
354
- oauthServer = createServer((req, res) => {
355
- const url = new URL(req.url || "/", `http://localhost:${OAUTH_PORT}`)
356
- if (url.pathname !== "/auth/callback") {
357
- res.writeHead(404)
358
- res.end("Not found")
359
- return
360
- }
361
- const code = url.searchParams.get("code")
362
- const state = url.searchParams.get("state")
363
- const error = url.searchParams.get("error_description") || url.searchParams.get("error")
364
- const fail = (status: number, msg: string) => {
365
- pendingOAuth?.reject(new Error(msg))
366
- pendingOAuth = undefined
367
- res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" })
368
- res.end(renderOAuthError(msg))
369
- }
370
- if (error) return fail(200, error)
371
- if (!code) return fail(400, "Missing authorization code")
372
- if (!pendingOAuth || state !== pendingOAuth.state) return fail(400, "Invalid state - potential CSRF attack")
373
- const current = pendingOAuth
374
- pendingOAuth = undefined
375
- exchangeCodeForTokens(code, redirectUri, current.pkce)
376
- .then((tokens) => current.resolve(tokens))
377
- .catch((err) => current.reject(err))
378
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" })
379
- res.end(HTML_SUCCESS)
380
- })
381
- try {
382
- await new Promise<void>((resolve, reject) => {
383
- oauthServer!.listen(OAUTH_PORT, "localhost", resolve)
384
- oauthServer!.on("error", reject)
385
- })
386
- } catch (error) {
387
- oauthServer = undefined
388
- throw error
389
- }
390
- return { redirectUri }
391
- }
392
-
393
- function stopOAuthServer(): void {
394
- oauthServer?.close(() => {})
395
- oauthServer = undefined
396
- }
397
-
398
- function waitForOAuthCallback(pkce: PkceCodes, state: string): Promise<TokenResponse> {
399
- // A new login supersedes any in-flight one: reject the old promise so it
400
- // can't hang or later clobber this flow's state.
401
- pendingOAuth?.reject(new Error("OAuth flow superseded by a new login"))
402
- return new Promise((resolve, reject) => {
403
- let entry: PendingOAuth | undefined
404
- // Each handler clears the shared slot only if it still owns it, so a stale
405
- // timer or callback never nulls out a newer flow's pendingOAuth.
406
- const clearIfOwner = () => {
407
- clearTimeout(timeout)
408
- if (pendingOAuth === entry) pendingOAuth = undefined
409
- }
410
- const timeout = setTimeout(() => {
411
- if (pendingOAuth === entry) {
412
- pendingOAuth = undefined
413
- reject(new Error("OAuth callback timeout - authorization took too long"))
414
- }
415
- }, OAUTH_TIMEOUT_MS)
416
- entry = {
417
- pkce,
418
- state,
419
- resolve: (tokens) => {
420
- clearIfOwner()
421
- resolve(tokens)
422
- },
423
- reject: (error) => {
424
- clearIfOwner()
425
- reject(error)
426
- },
427
- }
428
- pendingOAuth = entry
429
- })
430
- }
431
-
432
- // ---- Request provider: `weave` (Responses, both subs) ----------------------
433
-
434
- function compactTokenCount(n: number): string {
435
- if (n >= 1000) {
436
- const k = n / 1000
437
- return `${k >= 10 ? k.toFixed(0) : k.toFixed(1).replace(/\.0$/, "")}k`
438
- }
439
- return String(n)
440
- }
441
-
442
- function formatCost(cost: number): string {
443
- if (!Number.isFinite(cost) || cost <= 0) return ""
444
- if (cost < 0.001) return "<$0.001"
445
- return `$${cost.toFixed(3).replace(/0+$/, "").replace(/\.$/, "")}`
446
- }
447
-
448
- function formatRoutedToast(routedModelID: string, cost: number, tokens: { input: number; output: number }): string {
449
- const parts = [`→ ${routedModelID}`]
450
- const costLabel = formatCost(cost)
451
- if (costLabel) parts.push(costLabel)
452
- const usage: string[] = []
453
- if (tokens.input > 0) usage.push(`${compactTokenCount(tokens.input)} in`)
454
- if (tokens.output > 0) usage.push(`${compactTokenCount(tokens.output)} out`)
455
- if (usage.length > 0) parts.push(usage.join(" / "))
456
- return parts.join(" · ")
457
- }
458
-
459
- function isCompletedWeaveAssistant(info: Message): info is AssistantMessage {
460
- if (info.role !== "assistant") return false
461
- if (info.providerID !== PROVIDER_ID) return false
462
- if (!info.modelID) return false
463
- return info.time.completed !== undefined
464
- }
465
-
466
- export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> => {
467
- const classifierThreads = new ClassifierThreads()
468
- const pendingRequestMessageIDs = new Map<string, string>()
469
- const routedModelIDsByMessage = new Map<string, string>()
470
- const toastedMessageIDs = new Set<string>()
471
- return {
472
- "chat.message": async (_hookInput, output) => {
473
- rewriteDirectiveParts(output.parts)
474
- },
475
- event: async ({ event }) => {
476
- if (event.type === "session.created") {
477
- await classifierThreads.created(event.properties.info)
478
- return
479
- }
480
- if (event.type === "session.compacted") {
481
- await classifierThreads.compacted(event.properties.sessionID)
482
- return
483
- }
484
- if (event.type !== "message.updated") return
485
- const info = event.properties.info
486
- if (!isCompletedWeaveAssistant(info)) return
487
- if (toastedMessageIDs.has(info.id)) return
488
- toastedMessageIDs.add(info.id)
489
- const routedModelID = routedModelIDsByMessage.get(info.parentID) ?? info.modelID
490
- routedModelIDsByMessage.delete(info.parentID)
491
- for (const [requestID, messageID] of pendingRequestMessageIDs) {
492
- if (messageID === info.parentID) pendingRequestMessageIDs.delete(requestID)
493
- }
494
- try {
495
- await input.client.tui.showToast({
496
- body: {
497
- title: TOAST_TITLE,
498
- message: formatRoutedToast(routedModelID, info.cost, info.tokens),
499
- variant: "info",
500
- duration: TOAST_DURATION_MS,
501
- },
502
- })
503
- } catch {
504
- // Toast is best-effort; a TUI miss must not fail the turn.
505
- }
506
- },
507
- auth: {
508
- provider: PROVIDER_ID,
509
- async loader(getAuth) {
510
- // Coalesce concurrent refreshes (opencode fires parallel turns), one
511
- // in-flight promise per subscription.
512
- let chatgptRefresh: Promise<{ access: string; accountId: string | undefined }> | undefined
513
- let anthropicRefresh: Promise<string | undefined> | undefined
514
-
515
- // Resolve the ChatGPT (Codex) sub from this provider's own slot,
516
- // refreshing + persisting the rotated token on (or just before) expiry.
517
- async function resolveChatGPT(): Promise<{ access: string; accountId?: string } | undefined> {
518
- const current = (await getAuth()) as StoredOAuth
519
- if (current.type !== "oauth") return undefined
520
- // Use a still-valid access token regardless of whether a refresh token
521
- // is present (a partial store could lack it). Only an expired/absent
522
- // access needs a refresh — and that needs the refresh token.
523
- if (hasFreshAccess(current)) {
524
- return { access: current.access, accountId: current.accountId }
525
- }
526
- // Access is expired/absent: a refresh is the only way forward, so
527
- // without a refresh token there's no usable credential.
528
- if (!current.refresh) return undefined
529
- if (!chatgptRefresh) {
530
- chatgptRefresh = refreshAccessToken(current.refresh)
531
- .then(async (tokens) => {
532
- const accountId = extractAccountId(tokens) || current.accountId
533
- await input.client.auth.set({
534
- path: { id: PROVIDER_ID },
535
- body: {
536
- type: "oauth",
537
- refresh: tokens.refresh_token || current.refresh!,
538
- access: tokens.access_token,
539
- expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
540
- ...(accountId && { accountId }),
541
- },
542
- })
543
- return { access: tokens.access_token, accountId }
544
- })
545
- .finally(() => {
546
- chatgptRefresh = undefined
547
- })
548
- }
549
- return chatgptRefresh
550
- }
551
-
552
- // Resolve the Claude sub from the `weave-claude` slot (read off disk),
553
- // refreshing + persisting the rotated token via the auth store. Returns
554
- // undefined when Claude isn't connected.
555
- async function resolveAnthropic(): Promise<string | undefined> {
556
- const current = await readStoredOAuth(ANTHROPIC_PROVIDER_ID)
557
- if (!current) return undefined
558
- if (hasFreshAccess(current)) return current.access
559
- // Access is expired/absent: only a refresh can produce a live token,
560
- // so without a refresh token there's no usable credential to inject —
561
- // returning the stale token would have the router treat a dead Claude
562
- // sub as present instead of falling back to the Weave key. (Mirrors
563
- // resolveChatGPT.)
564
- if (!current.refresh) return undefined
565
- if (!anthropicRefresh) {
566
- anthropicRefresh = refreshAnthropicToken(current.refresh)
567
- .then(async (tokens) => {
568
- await input.client.auth.set({
569
- path: { id: ANTHROPIC_PROVIDER_ID },
570
- body: { type: "oauth", refresh: tokens.refresh, access: tokens.access, expires: tokens.expires },
571
- })
572
- return tokens.access
573
- })
574
- .catch(() => undefined)
575
- .finally(() => {
576
- anthropicRefresh = undefined
577
- })
578
- }
579
- return anthropicRefresh
580
- }
581
-
582
- return {
583
- apiKey: DUMMY_KEY,
584
- async fetch(requestInput: RequestInfo | URL, init?: RequestInit) {
585
- // Preserve the configured headers (X-Weave-Router-Key, X-App, …) and
586
- // attach each connected subscription via its dedicated router header.
587
- // Authorization is left as the @ai-sdk placeholder; the router authes
588
- // off X-Weave-Router-Key and resolves the matching sub per the routed
589
- // model, so neither sub rides in Authorization.
590
- const headers = new Headers(init?.headers as HeadersInit | undefined)
591
-
592
- // Resolve both subs independently and never let one failure (e.g. a
593
- // failed ChatGPT token refresh) drop the other or fail the turn — a
594
- // Claude-routed turn must still get its sub when the ChatGPT refresh
595
- // is down, and vice-versa. Each resolver already persists rotations.
596
- const [chatgpt, anthropic] = await Promise.all([
597
- resolveChatGPT().catch(() => undefined),
598
- resolveAnthropic().catch(() => undefined),
599
- ])
600
- if (chatgpt?.access) {
601
- headers.set(HEADER_OPENAI_SUB, chatgpt.access)
602
- if (chatgpt.accountId) headers.set(HEADER_OPENAI_ACCOUNT_ID, chatgpt.accountId)
603
- }
604
- if (anthropic) headers.set(HEADER_ANTHROPIC_SUB, anthropic)
605
-
606
- const requestID = headers.get(HEADER_OPENCODE_REQUEST_ID)
607
- let routedModelCaptured = false
608
- try {
609
- const response = await fetch(requestInput, { ...init, headers })
610
- const messageID = requestID ? pendingRequestMessageIDs.get(requestID) : undefined
611
- const routedModelID = response.headers.get(HEADER_ROUTER_MODEL)
612
- if (messageID && routedModelID) {
613
- routedModelIDsByMessage.set(messageID, routedModelID)
614
- routedModelCaptured = true
615
- }
616
- return response
617
- } finally {
618
- if (requestID && routedModelCaptured) pendingRequestMessageIDs.delete(requestID)
619
- }
620
- },
621
- }
622
- },
623
- methods: [
624
- {
625
- label: "ChatGPT Pro/Plus — pays for GPT/Codex turns (browser)",
626
- type: "oauth",
627
- authorize: async () => {
628
- const { redirectUri } = await startOAuthServer()
629
- const pkce = await generatePKCE()
630
- const state = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer)
631
- const callbackPromise = waitForOAuthCallback(pkce, state)
632
- return {
633
- url: buildAuthorizeUrl(redirectUri, pkce, state),
634
- instructions: "Complete authorization in your browser. This window will close automatically.",
635
- method: "auto" as const,
636
- callback: async () => {
637
- try {
638
- const tokens = await callbackPromise
639
- return {
640
- type: "success" as const,
641
- refresh: tokens.refresh_token,
642
- access: tokens.access_token,
643
- expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
644
- accountId: extractAccountId(tokens),
645
- }
646
- } finally {
647
- stopOAuthServer()
648
- }
649
- },
650
- }
651
- },
652
- },
653
- {
654
- label: "ChatGPT Pro/Plus — pays for GPT/Codex turns (headless device code)",
655
- type: "oauth",
656
- authorize: async () => {
657
- const deviceResponse = await fetch(`${chatGPTIssuer()}/api/accounts/deviceauth/usercode`, {
658
- method: "POST",
659
- headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
660
- body: JSON.stringify({ client_id: CHATGPT_CLIENT_ID }),
661
- })
662
- if (!deviceResponse.ok) throw new Error("Failed to initiate device authorization")
663
- const deviceData = (await deviceResponse.json()) as {
664
- device_auth_id: string
665
- user_code: string
666
- interval: string
667
- }
668
- const interval = Math.max(parseInt(deviceData.interval) || 5, 1) * 1000
669
- return {
670
- url: `${chatGPTIssuer()}/codex/device`,
671
- instructions: `Enter code: ${deviceData.user_code}`,
672
- method: "auto" as const,
673
- async callback() {
674
- const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
675
- const deadline = Date.now() + OAUTH_TIMEOUT_MS
676
- while (Date.now() < deadline) {
677
- const response = await fetch(`${chatGPTIssuer()}/api/accounts/deviceauth/token`, {
678
- method: "POST",
679
- headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
680
- body: JSON.stringify({
681
- device_auth_id: deviceData.device_auth_id,
682
- user_code: deviceData.user_code,
683
- }),
684
- })
685
- if (response.ok) {
686
- const data = (await response.json()) as { authorization_code: string; code_verifier: string }
687
- const tokenResponse = await fetch(`${chatGPTIssuer()}/oauth/token`, {
688
- method: "POST",
689
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
690
- body: new URLSearchParams({
691
- grant_type: "authorization_code",
692
- code: data.authorization_code,
693
- redirect_uri: `${chatGPTIssuer()}/deviceauth/callback`,
694
- client_id: CHATGPT_CLIENT_ID,
695
- code_verifier: data.code_verifier,
696
- }).toString(),
697
- })
698
- if (!tokenResponse.ok) throw new Error(`Token exchange failed: ${tokenResponse.status}`)
699
- const tokens = (await tokenResponse.json()) as TokenResponse
700
- return {
701
- type: "success" as const,
702
- refresh: tokens.refresh_token,
703
- access: tokens.access_token,
704
- expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
705
- accountId: extractAccountId(tokens),
706
- }
707
- }
708
- if (response.status !== 403 && response.status !== 404) return { type: "failed" as const }
709
- await sleep(interval + OAUTH_POLLING_SAFETY_MARGIN_MS)
710
- }
711
- return { type: "failed" as const }
712
- },
713
- }
714
- },
715
- },
716
- ],
717
- },
718
- // The Codex backend (which the router forwards GPT turns to) keys session
719
- // continuity off these headers; mirror opencode's bundled codex plugin.
720
- // Scoped to our provider so other providers are untouched.
721
- "chat.headers": async (hookInput, output) => {
722
- if (hookInput.model.providerID !== PROVIDER_ID) return
723
- if (hookInput.agent !== "title") {
724
- // OpenCode swallows plugin hook exceptions. A failure must reach the
725
- // router as an invalid ticket, never as an unticketed HMM request.
726
- output.headers[CLASSIFIER_THREAD_HEADER] = CLASSIFIER_UNAVAILABLE_TICKET
727
- try {
728
- const enrolled = await classifierThreads.hasThread(hookInput.sessionID)
729
- if (!enrolled && process.env.WEAVE_OPENCODE_LLM_CLASSIFIER !== "1") {
730
- delete output.headers[CLASSIFIER_THREAD_HEADER]
731
- } else {
732
- if (!hookInput.provider?.options?.baseURL) throw new Error("Weave router origin unavailable")
733
- const routerOrigin = new URL(hookInput.provider.options.baseURL).origin
734
- const configuredHeaders = new Headers(hookInput.provider.options.headers as HeadersInit | undefined)
735
- Object.assign(output.headers, await classifierThreads.header(hookInput.sessionID, routerOrigin,
736
- configuredHeaders.get("X-Weave-Router-Key") ?? "", hookInput.agent))
737
- }
738
- } catch (error) {
739
- console.error("Classifier enrollment blocked this OpenCode request", hookInput.sessionID,
740
- error instanceof Error ? error.message : "unknown failure")
741
- }
742
- }
743
- output.headers["originator"] = "codex_cli_ts"
744
- output.headers["session-id"] = hookInput.sessionID
745
- const messageID = hookInput.message?.id
746
- if (messageID) {
747
- const requestID = crypto.randomUUID()
748
- pendingRequestMessageIDs.set(requestID, messageID)
749
- output.headers[HEADER_OPENCODE_REQUEST_ID] = requestID
750
- }
751
- // Custom agents are user-named; only OpenCode's own lifecycle agents are forwarded.
752
- const agent = knownOpenCodeAgent(hookInput.agent)
753
- if (agent) output.headers[HEADER_OPENCODE_AGENT] = agent
754
- },
755
- "chat.params": async (hookInput, output) => {
756
- if (hookInput.model.providerID !== PROVIDER_ID) return
757
- // Match codex cli: the Codex backend rejects an explicit max output cap.
758
- output.maxOutputTokens = undefined
759
- },
760
- }
761
- }
762
-
763
- // ---- Login-only provider: `weave-claude` (Claude Pro/Max) ------------------
764
- // A second auth hook so the Claude subscription gets its own storage slot
765
- // (opencode keys credentials by provider id). It serves no requests — the
766
- // `weave` loader reads this slot and attaches the token — so it needs no loader.
767
-
768
- export const WeaveClaude: Plugin = async (_input: PluginInput): Promise<Hooks> => {
769
- return {
770
- auth: {
771
- provider: ANTHROPIC_PROVIDER_ID,
772
- methods: [
773
- {
774
- label: "Claude Pro/Max — pays for Claude turns (browser)",
775
- type: "oauth",
776
- authorize: async () => {
777
- const pkce = await generatePKCE()
778
- return {
779
- url: buildAnthropicAuthorizeUrl(pkce),
780
- instructions: "Sign in with your Claude account, then paste the code shown (looks like `code#state`).",
781
- method: "code" as const,
782
- callback: async (code: string) => {
783
- const tokens = await exchangeAnthropicCode(code, pkce.verifier)
784
- return {
785
- type: "success" as const,
786
- refresh: tokens.refresh,
787
- access: tokens.access,
788
- expires: tokens.expires,
789
- }
790
- },
791
- }
792
- },
793
- },
794
- ],
795
- },
796
- }
797
- }
798
-
799
- export default WeaveCodex