@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.
@@ -1,57 +1,35 @@
1
- # opencode Weave subscription plugin
1
+ # Legacy opencode Weave integration
2
2
 
3
- Lets a caller's own **AI subscriptions** pay for their **opencode** turns, routed
4
- through the Weave Router. A subscription is a **credential scoped to the model
5
- family it can pay for**, not a provider you pick: you connect your ChatGPT
6
- (Codex) and/or Claude (Pro/Max) plan once, the router routes every request to the
7
- best model, and bills the plan that matches the model it served — ChatGPT pays
8
- for GPT/Codex turns, Claude pays for Claude turns, your Weave key pays for
9
- everything else.
3
+ This source is bundled and installed for OpenCode's lifecycle, classifier, and
4
+ directive hooks. Subscription enrollment now happens in the router with
5
+ `npx @weave-os/router login claude` or `npx @weave-os/router login codex`;
6
+ requests must not carry subscription headers.
10
7
 
11
- Bundled into `@weave-os/router`; the installer (`--opencode`) drops
12
- `src/index.ts` into the user's opencode plugins dir and writes a single
13
- Responses-format `weave` provider (plus a login-only `weave-claude` provider)
14
- into `opencode.json`.
8
+ The plugin is loaded by new installs, but it does not own subscription
9
+ enrollment or transport subscription credentials.
15
10
 
16
- ## Why a plugin (config alone can't do it)
11
+ The installer writes only the Responses-format `weave` provider into
12
+ `opencode.json`.
17
13
 
18
- opencode removed built-in subscription auth in 1.3.0 and binds OAuth to its own
19
- first-party providers, so a custom router provider can't reuse it. And
20
- subscription tokens expire hourly — a static `options.headers` string can't
21
- refresh them, nor carry two subscriptions whose tokens rotate independently.
14
+ ## Why this source remains
15
+
16
+ Older manually-installed copies may also load this module for lifecycle and
17
+ directive hooks. It intentionally contains no OAuth login, token refresh, or
18
+ subscription-header transport.
22
19
 
23
20
  ## Wire shape it produces
24
21
 
25
- opencode talks to one Responses-format `weave` provider; the plugin's loader
26
- attaches whichever subscriptions are connected to **every** request via the
27
- router's dedicated headers:
22
+ opencode talks to one Responses-format `weave` provider. Subscription enrollment
23
+ is managed by the router (`npx @weave-os/router login claude`), not by request
24
+ headers from this plugin:
28
25
 
29
26
  | | |
30
27
  |---|---|
31
28
  | `POST {router}/v1/responses` | Responses wire format (opencode's default for an `@ai-sdk/openai` provider) |
32
- | `X-Weave-OpenAI-Subscription: <ChatGPT JWT>` | pays GPT/Codex turns, refreshed on expiry |
33
- | `X-Weave-OpenAI-Account-ID: <id>` | paired account id (required by the Codex backend) |
34
- | `X-Weave-Anthropic-Subscription: <sk-ant-oat token>` | pays Claude turns, refreshed on expiry |
35
29
  | `X-Weave-Router-Key: rk_…` | from `opencode.json` `options.headers` — the router authenticates off this |
36
30
 
37
- The router routes each request across every model the caller's subs + key can pay
38
- for and resolves the subscription matching the chosen provider, so a sub is
39
- never billed for a request outside its family.
40
-
41
- ## Two storage slots, one request provider
42
-
43
- opencode stores one credential per provider id and the loader's `getAuth()` is
44
- scoped to its own provider, so the two logins live in two slots:
45
-
46
- - **`weave`** — the request provider. Owns the **ChatGPT** login and the loader
47
- that attaches both subscriptions. Connecting ChatGPT activates sub-routing.
48
- - **`weave-claude`** — login-only (no models, serves no requests). Owns the
49
- **Claude** login. Its token is read from opencode's on-disk auth store by the
50
- `weave` loader (the SDK exposes no get-by-id).
51
-
52
- With neither connected, `weave` is a plain router provider and the Weave key
53
- pays. Either login activates its matching subscription independently, so a
54
- Claude-only setup pays Claude turns from that plan without requiring ChatGPT.
31
+ The router routes each request across the models available to the managed
32
+ installation and its configured credentials.
55
33
 
56
34
  ## Router directives
57
35
 
@@ -62,26 +40,28 @@ rewrites `$rf` / `$router-feedback`, `$fm` / `$force-model`, `$ufm` /
62
40
  / `router-status` / `disable-routing`) stay CLI-only — this installer does not
63
41
  own a per-session config flip the way Claude Code and Codex do.
64
42
 
65
- ## Login
43
+ ## Enrollment
44
+
45
+ Enroll subscriptions through the managed router rather than OpenCode:
66
46
 
67
- `opencode auth login` → **Weave Router — Codex plan** → *ChatGPT Pro/Plus*
68
- (browser or headless device code) and/or **Weave Router — Claude plan** →
69
- *Claude Pro/Max* (browser; paste the `code#state` shown after authorizing).
47
+ ```sh
48
+ npx @weave-os/router login claude # or: npx @weave-os/router login codex
49
+ ```
70
50
 
71
- These logins populate OpenCode's provider-keyed `auth.json`, which is how this
72
- plugin reads and forwards the subscription credentials. The standalone
73
- `npx @weave-os/router login codex|claude` commands enroll server-side
74
- subscription accounts instead; they do not populate OpenCode's auth store and
75
- are not a replacement for these plugin logins.
51
+ The router stores and refreshes the enrollment server-side; OpenCode does not
52
+ need to carry subscription credentials in request headers.
76
53
 
77
54
  ## Env overrides (self-host + tests)
78
55
 
79
- - `WEAVE_CODEX_OAUTH_ISSUER` — OpenAI auth issuer.
80
- - `WEAVE_ANTHROPIC_OAUTH_AUTHORIZE` / `WEAVE_ANTHROPIC_OAUTH_TOKEN` — Anthropic
81
- OAuth authorize host / token endpoint.
82
- - `WEAVE_OPENCODE_AUTH_FILE` — path to opencode's `auth.json` (the `weave`
83
- loader reads the `weave-claude` slot from here; defaults to
84
- `$XDG_DATA_HOME/opencode/auth.json`).
56
+ - `WEAVE_OPENCODE_LLM_CLASSIFIER=1` — enroll only sessions created while this
57
+ plugin is running. The plugin stores a separate handshake UUID and router
58
+ ticket for each parent/child session under OpenCode's data directory. An
59
+ enrollment failure or missing new-session event blocks inference while the
60
+ opt-in is set; resume an older session with the opt-in unset. Classifier
61
+ sessions cannot compact or change router origins; start
62
+ a new session instead. Requires a router deployment with the exact release
63
+ and installation explicitly allowlisted. Deploy the router's non-retryable
64
+ client-failure response before enabling this opt-in on developer machines.
85
65
 
86
66
  ## Verification
87
67
 
@@ -115,11 +95,11 @@ or real providers.
115
95
 
116
96
  | Layer | Contract |
117
97
  |---|---|
118
- | Bun plugin tests | All four subscription combinations; expiry, refresh failure isolation, late login; header/session continuity; no secrets logged |
98
+ | Bun integration tests | Router/lifecycle header continuity, directive rewriting, and no subscription/account header injection |
119
99
  | Pinned Responses SDK fixtures | Streaming and non-streaming text/usage, two tool calls, upstream errors, malformed/unknown events, truncated streams, absent usage |
120
100
  | Installed real CLI | Exact `/v1/responses`, `auto`, `X-App`, router key, nonempty session IDs, parsed text, usage, completion, two executed tools and matching tool results |
121
101
  | Real lifecycle hooks | Main `build`, title `title`, task child `explore`, and automatic `compaction` followed by resumed `build`; parent/child session boundaries |
122
- | Real plugin loader | Both providers' OAuth methods visible through `opencode serve` → `/provider/auth`, even without an OAuth store |
102
+ | Real plugin loader | Routing hooks remain loadable when explicitly installed as a legacy plugin |
123
103
  | Installer/package | Install/toggle/uninstall, packed npm `--opencode` entrypoint; existing Claude/Codex/Pi installer coverage |
124
104
  | Go proxy/translation | Native and translated Responses history hygiene, actionable tool-output commands, Codex feedback-skill preservation, wire lifecycle and usage |
125
105
 
@@ -140,11 +120,9 @@ unknown token counts. These are explicit compatibility observations, **not** cla
140
120
  of clean failure or successful completion. The normal CLI cases require both a
141
121
  successful terminal event and exact usage, so removing completion/usage fails them.
142
122
 
143
- The plugin intentionally uses the
144
- [legacy all-export loader](https://github.com/anomalyco/opencode/blob/v1.18.27/packages/opencode/src/plugin/index.ts):
145
- all exported values are plugin functions, `default === WeaveCodex` is deduplicated,
146
- and `WeaveClaude` registers separately. Converting the default to a V1 plugin
147
- object would bypass those named exports; the loader tests guard against that.
123
+ The source intentionally keeps the
124
+ [legacy all-export loader](https://github.com/anomalyco/opencode/blob/v1.18.27/packages/opencode/src/plugin/index.ts)
125
+ shape required by the pinned OpenCode version.
148
126
  See the current [CLI](https://opencode.ai/docs/cli/),
149
127
  [plugin](https://opencode.ai/docs/plugins/), and
150
128
  [server](https://opencode.ai/docs/server/) references when updating the pin.
@@ -2,7 +2,7 @@
2
2
  "name": "@weave-os/router-opencode-extension",
3
3
  "private": true,
4
4
  "type": "module",
5
- "description": "The opencode subscription auth plugin bundled into @weave-os/router. NOT published separately: src/ is copied into the @weave-os/router package at prepack and dropped into the user's opencode plugin directory by install.sh --opencode. Lets a caller's own ChatGPT and Claude subscriptions pay for matching opencode turns routed through the Weave Router. This manifest marks the sources as ESM and declares the opencode peer dependency for local typecheck.",
5
+ "description": "OpenCode lifecycle, classifier, and directive hooks for @weave-os/router; managed subscription enrollment belongs to the router.",
6
6
  "scripts": {
7
7
  "test": "bun test test/",
8
8
  "typecheck": "tsc --project tsconfig.json"
@@ -0,0 +1,145 @@
1
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"
2
+ import { homedir } from "node:os"
3
+ import { dirname, join } from "node:path"
4
+ import type { Session } from "@opencode-ai/sdk"
5
+
6
+ const SESSION_ID = /^[a-zA-Z0-9_-]{1,128}$/
7
+ export const CLASSIFIER_THREAD_HEADER = "X-Weave-Classifier-Thread"
8
+ export const CLASSIFIER_UNAVAILABLE_TICKET = "weave-classifier-unavailable"
9
+
10
+ interface SavedThread {
11
+ sessionID: string
12
+ newChatID: string
13
+ routerOrigin?: string
14
+ threadToken?: string
15
+ compacted?: boolean
16
+ }
17
+
18
+ function threadDirectory(): string {
19
+ const authFile = process.env.WEAVE_OPENCODE_AUTH_FILE ??
20
+ join(process.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share"), "opencode", "auth.json")
21
+ return join(dirname(authFile), "weave-classifier-threads")
22
+ }
23
+
24
+ function threadPath(sessionID: string): string {
25
+ if (!SESSION_ID.test(sessionID)) throw new Error("Invalid OpenCode session identity")
26
+ return join(threadDirectory(), `${sessionID}.json`)
27
+ }
28
+
29
+ async function readThread(sessionID: string): Promise<SavedThread | undefined> {
30
+ let saved: string
31
+ try {
32
+ saved = await readFile(threadPath(sessionID), "utf8")
33
+ } catch (error) {
34
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
35
+ throw error
36
+ }
37
+ const parsed: unknown = JSON.parse(saved)
38
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Invalid classifier enrollment state")
39
+ const thread = parsed as Partial<SavedThread>
40
+ if (thread.sessionID !== sessionID || typeof thread.newChatID !== "string" ||
41
+ !/^[0-9a-f-]{36}$/.test(thread.newChatID) ||
42
+ (thread.routerOrigin !== undefined && typeof thread.routerOrigin !== "string") ||
43
+ (thread.threadToken !== undefined && (typeof thread.threadToken !== "string" || !thread.threadToken || thread.threadToken.length > 4096)) ||
44
+ (thread.compacted !== undefined && typeof thread.compacted !== "boolean")) {
45
+ throw new Error("Invalid classifier enrollment state")
46
+ }
47
+ return thread as SavedThread
48
+ }
49
+
50
+ async function replaceThread(thread: SavedThread): Promise<void> {
51
+ const destination = threadPath(thread.sessionID)
52
+ const temporary = `${destination}.${crypto.randomUUID()}.tmp`
53
+ await writeFile(temporary, JSON.stringify(thread), { flag: "wx", mode: 0o600 })
54
+ try {
55
+ await rename(temporary, destination)
56
+ } catch (error) {
57
+ await unlink(temporary)
58
+ throw error
59
+ }
60
+ }
61
+
62
+ /** The session-created event is the only enrollment authority; a short request is not. */
63
+ export class ClassifierThreads {
64
+ private creations = new Map<string, Promise<void>>()
65
+ private handshakes = new Map<string, Promise<string | undefined>>()
66
+
67
+ async hasThread(sessionID: string): Promise<boolean> {
68
+ await this.creations.get(sessionID)
69
+ return (await readThread(sessionID)) !== undefined
70
+ }
71
+
72
+ created(session: Session): Promise<void> {
73
+ if (process.env.WEAVE_OPENCODE_LLM_CLASSIFIER !== "1") return Promise.resolve()
74
+ const sessionID = session.id
75
+ if (this.creations.has(sessionID)) return this.creations.get(sessionID)!
76
+ const creation = (async () => {
77
+ const path = threadPath(sessionID)
78
+ await mkdir(threadDirectory(), { recursive: true, mode: 0o700 })
79
+ try {
80
+ await writeFile(path, JSON.stringify({ sessionID, newChatID: crypto.randomUUID() }), { flag: "wx", mode: 0o600 })
81
+ } catch (error) {
82
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
83
+ await readThread(sessionID)
84
+ }
85
+ })()
86
+ this.creations.set(sessionID, creation)
87
+ return creation
88
+ }
89
+
90
+ compacted(sessionID: string): Promise<void> {
91
+ return this.updateCompacted(sessionID)
92
+ }
93
+
94
+ private async updateCompacted(sessionID: string): Promise<void> {
95
+ await this.creations.get(sessionID)
96
+ await this.handshakes.get(sessionID)?.catch(() => undefined)
97
+ const thread = await readThread(sessionID)
98
+ if (thread) await replaceThread({ ...thread, compacted: true })
99
+ }
100
+
101
+ async header(sessionID: string, routerOrigin: string, routerKey: string, agent?: string): Promise<Record<string, string>> {
102
+ await this.creations.get(sessionID)
103
+ if (agent === "title" || agent === "compaction") {
104
+ const ticket = await this.resolveTicket(sessionID, routerOrigin, routerKey, agent)
105
+ return ticket ? { [CLASSIFIER_THREAD_HEADER]: ticket } : {}
106
+ }
107
+ if (this.handshakes.has(sessionID)) {
108
+ const ticket = await this.handshakes.get(sessionID)!
109
+ return ticket ? { [CLASSIFIER_THREAD_HEADER]: ticket } : {}
110
+ }
111
+ const handshake = this.resolveTicket(sessionID, routerOrigin, routerKey, agent)
112
+ this.handshakes.set(sessionID, handshake)
113
+ try {
114
+ const ticket = await handshake
115
+ return ticket ? { [CLASSIFIER_THREAD_HEADER]: ticket } : {}
116
+ } finally {
117
+ if (this.handshakes.get(sessionID) === handshake) this.handshakes.delete(sessionID)
118
+ }
119
+ }
120
+
121
+ private async resolveTicket(sessionID: string, routerOrigin: string, routerKey: string, agent?: string): Promise<string | undefined> {
122
+ const thread = await readThread(sessionID)
123
+ if (!thread) return undefined
124
+ if (thread.compacted || (thread.routerOrigin && thread.routerOrigin !== routerOrigin)) {
125
+ throw new Error("Classifier session cannot continue after compaction or router change")
126
+ }
127
+ if (agent === "title") return undefined
128
+ if (agent === "compaction") throw new Error("Classifier sessions require complete history; compaction is unavailable")
129
+ if (thread.threadToken) return thread.threadToken
130
+ if (!routerKey) throw new Error("Classifier enrollment requires a router key")
131
+ const response = await fetch(`${routerOrigin}/v1/router/threads`, {
132
+ method: "POST", redirect: "error", signal: AbortSignal.timeout(10_000),
133
+ headers: { "X-Weave-Router-Key": routerKey, "X-App": "opencode", "Content-Type": "application/json" },
134
+ body: JSON.stringify({ new_chat_id: thread.newChatID }),
135
+ })
136
+ if (!response.ok) throw new Error(`Classifier enrollment returned HTTP ${response.status}`)
137
+ const ticket: unknown = await response.json()
138
+ if (ticket === null || typeof ticket !== "object" || !("thread_token" in ticket) ||
139
+ typeof ticket.thread_token !== "string" || !ticket.thread_token || ticket.thread_token.length > 4096) {
140
+ throw new Error("Invalid classifier enrollment response")
141
+ }
142
+ await replaceThread({ ...thread, routerOrigin, threadToken: ticket.thread_token })
143
+ return ticket.thread_token
144
+ }
145
+ }