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