@weave-os/router 0.2.18 → 0.2.20
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/README.md +26 -18
- package/cc-statusline.sh +6 -1
- package/codex-toggle.sh +203 -0
- package/install.sh +632 -98
- package/opencode-weave/README.md +85 -13
- package/opencode-weave/package.json +4 -2
- package/opencode-weave/src/directives.ts +72 -0
- package/opencode-weave/src/index.ts +138 -28
- package/package.json +2 -1
- package/pi-router/README.md +69 -3
- package/pi-router/package.json +4 -4
- package/pi-router/src/compaction.ts +2 -2
- package/pi-router/src/escalation.ts +265 -0
- package/pi-router/src/index.ts +8 -4
- package/pi-router/src/ui.ts +14 -2
- package/uninstall.sh +147 -24
package/opencode-weave/README.md
CHANGED
|
@@ -8,7 +8,7 @@ best model, and bills the plan that matches the model it served — ChatGPT pays
|
|
|
8
8
|
for GPT/Codex turns, Claude pays for Claude turns, your Weave key pays for
|
|
9
9
|
everything else.
|
|
10
10
|
|
|
11
|
-
Bundled into `@weave-os/router`; the installer (`--
|
|
11
|
+
Bundled into `@weave-os/router`; the installer (`--opencode`) drops
|
|
12
12
|
`src/index.ts` into the user's opencode plugins dir and writes a single
|
|
13
13
|
Responses-format `weave` provider (plus a login-only `weave-claude` provider)
|
|
14
14
|
into `opencode.json`.
|
|
@@ -49,15 +49,30 @@ scoped to its own provider, so the two logins live in two slots:
|
|
|
49
49
|
**Claude** login. Its token is read from opencode's on-disk auth store by the
|
|
50
50
|
`weave` loader (the SDK exposes no get-by-id).
|
|
51
51
|
|
|
52
|
-
With neither connected, `weave` is a plain router provider
|
|
53
|
-
|
|
54
|
-
|
|
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.
|
|
55
|
+
|
|
56
|
+
## Router directives
|
|
57
|
+
|
|
58
|
+
OpenCode is a plugin, not a Codex skill runner. The plugin's `chat.message` hook
|
|
59
|
+
rewrites `$rf` / `$router-feedback`, `$fm` / `$force-model`, `$ufm` /
|
|
60
|
+
`$unforce-model`, and `$router-session` (slash forms too) into the leading-space
|
|
61
|
+
`/…` prompts the router already parses. Local toggles (`router-on` / `router-off`
|
|
62
|
+
/ `router-status` / `disable-routing`) stay CLI-only — this installer does not
|
|
63
|
+
own a per-session config flip the way Claude Code and Codex do.
|
|
55
64
|
|
|
56
65
|
## Login
|
|
57
66
|
|
|
58
|
-
`opencode auth login` → **Weave Router** → *ChatGPT Pro/Plus*
|
|
59
|
-
headless device code) and/or **Weave Router — Claude plan** →
|
|
60
|
-
(browser; paste the `code#state` shown after authorizing).
|
|
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).
|
|
70
|
+
|
|
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.
|
|
61
76
|
|
|
62
77
|
## Env overrides (self-host + tests)
|
|
63
78
|
|
|
@@ -70,9 +85,66 @@ headless device code) and/or **Weave Router — Claude plan** → *Claude Pro/Ma
|
|
|
70
85
|
|
|
71
86
|
## Verification
|
|
72
87
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
88
|
+
The required CI contract pins **OpenCode and `@opencode-ai/plugin` 1.18.27**.
|
|
89
|
+
The CLI install reads that pin from `package.json`; the direct Responses tests
|
|
90
|
+
use **`@ai-sdk/openai` 3.0.84**, matching the
|
|
91
|
+
[pinned OpenCode dependencies](https://github.com/anomalyco/opencode/blob/v1.18.27/packages/opencode/package.json).
|
|
92
|
+
Neither required dependency floats. The separate weekly/manual
|
|
93
|
+
[latest compatibility workflow](../../.github/workflows/opencode_latest.yml)
|
|
94
|
+
is not a merge gate.
|
|
95
|
+
|
|
96
|
+
From the router repository root (Node, Bun, Python 3.11+, and jq required):
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
npm ci --prefix install/opencode-weave --ignore-scripts
|
|
100
|
+
npm run --prefix install/opencode-weave typecheck
|
|
101
|
+
bun test install/opencode-weave/test/
|
|
102
|
+
make test-install
|
|
103
|
+
npm install --global opencode-ai@1.18.27
|
|
104
|
+
bash install/pi-router/test/opencode_smoke.sh
|
|
105
|
+
go test ./internal/proxy ./internal/translate -count=1
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`OPENCODE_BIN` selects an already-installed CLI. To explicitly test another
|
|
109
|
+
version, set `OPENCODE_EXPECTED_VERSION` to its exact version; the smoke otherwise
|
|
110
|
+
rejects anything other than the supported pin. The driver gives each command
|
|
111
|
+
60 seconds, kills its process group on timeout, limits mock requests per session,
|
|
112
|
+
and isolates HOME, XDG directories, provider selection, and credentials. Package
|
|
113
|
+
bootstrap may use the network; inference and OAuth tests never use real credentials
|
|
114
|
+
or real providers.
|
|
115
|
+
|
|
116
|
+
| Layer | Contract |
|
|
117
|
+
|---|---|
|
|
118
|
+
| Bun plugin tests | All four subscription combinations; expiry, refresh failure isolation, late login; header/session continuity; no secrets logged |
|
|
119
|
+
| Pinned Responses SDK fixtures | Streaming and non-streaming text/usage, two tool calls, upstream errors, malformed/unknown events, truncated streams, absent usage |
|
|
120
|
+
| 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
|
+
| 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 |
|
|
123
|
+
| Installer/package | Install/toggle/uninstall, packed npm `--opencode` entrypoint; existing Claude/Codex/Pi installer coverage |
|
|
124
|
+
| Go proxy/translation | Native and translated Responses history hygiene, actionable tool-output commands, Codex feedback-skill preservation, wire lifecycle and usage |
|
|
125
|
+
|
|
126
|
+
The lifecycle observer is a **test-only** `chat.headers` hook recording OpenCode's
|
|
127
|
+
actual `input.agent`, not a prompt heuristic or a router-policy change. A synthetic
|
|
128
|
+
high-usage response triggers automatic compaction without a huge prompt. Title
|
|
129
|
+
generation uses the configured local `small_model`; task execution uses the actual
|
|
130
|
+
`task` tool and a child session. No separate classifier/probe invocation was
|
|
131
|
+
observed in these headless flows. Tool-less SDK fixtures cover that wire shape
|
|
132
|
+
without claiming a classifier fingerprint. Non-streaming requests are direct SDK
|
|
133
|
+
fixtures: the tested CLI flows use streaming.
|
|
134
|
+
|
|
135
|
+
The pinned SDK silently ignores an ill-shaped known event, treats an unfinished
|
|
136
|
+
stream as `other`, and tolerates unknown event types. It also requires usage on a
|
|
137
|
+
streaming `response.completed`: missing usage produces `other` rather than `stop`
|
|
138
|
+
(and can cause CLI continuation), while non-streaming missing usage remains
|
|
139
|
+
unknown token counts. These are explicit compatibility observations, **not** claims
|
|
140
|
+
of clean failure or successful completion. The normal CLI cases require both a
|
|
141
|
+
successful terminal event and exact usage, so removing completion/usage fails them.
|
|
142
|
+
|
|
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.
|
|
148
|
+
See the current [CLI](https://opencode.ai/docs/cli/),
|
|
149
|
+
[plugin](https://opencode.ai/docs/plugins/), and
|
|
150
|
+
[server](https://opencode.ai/docs/server/) references when updating the pin.
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
{
|
|
2
|
-
"name": "@
|
|
2
|
+
"name": "@weave-os/router-opencode-extension",
|
|
3
3
|
"private": true,
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "The opencode
|
|
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.",
|
|
6
6
|
"scripts": {
|
|
7
|
+
"test": "bun test test/",
|
|
7
8
|
"typecheck": "tsc --project tsconfig.json"
|
|
8
9
|
},
|
|
9
10
|
"peerDependencies": {
|
|
10
11
|
"@opencode-ai/plugin": "*"
|
|
11
12
|
},
|
|
12
13
|
"devDependencies": {
|
|
14
|
+
"@ai-sdk/openai": "3.0.84",
|
|
13
15
|
"@opencode-ai/plugin": "1.18.27",
|
|
14
16
|
"@types/bun": "1.3.14",
|
|
15
17
|
"@types/node": "24.13.3",
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewrite OpenCode user text so Weave Router prompt directives reach the
|
|
3
|
+
* same parser Codex and pi already hit. OpenCode is not a skill runner: `$rf`
|
|
4
|
+
* would otherwise go to the LLM. The router already accepts both `/name` and
|
|
5
|
+
* `$name` on the wire; rewriting `$…` to the leading-space `/…` form matches
|
|
6
|
+
* the Codex emit.sh contract and keeps aliases out of model context.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const FORCE_MODEL = /^(?:\$|\/)(?:force-model|fm)(?:\s+|$)/i
|
|
10
|
+
const UNFORCE_MODEL = /^(?:\$|\/)(?:unforce-model|ufm)\s*$/i
|
|
11
|
+
const ROUTER_FEEDBACK = /^(?:\$|\/)(?:router-feedback|rf)(?:\s|$)/i
|
|
12
|
+
const ROUTER_SESSION = /^(?:\$|\/)router-session\s*$/i
|
|
13
|
+
|
|
14
|
+
export type RouterDirective =
|
|
15
|
+
| { kind: "force-model"; model: string }
|
|
16
|
+
| { kind: "unforce-model" }
|
|
17
|
+
| { kind: "router-feedback"; payload: string }
|
|
18
|
+
| { kind: "router-session" }
|
|
19
|
+
|
|
20
|
+
export function parseRouterDirective(text: string): RouterDirective | undefined {
|
|
21
|
+
const line = text.trim()
|
|
22
|
+
if (!line) return undefined
|
|
23
|
+
|
|
24
|
+
if (UNFORCE_MODEL.test(line) || line === "$ufm" || line === "/ufm") {
|
|
25
|
+
return { kind: "unforce-model" }
|
|
26
|
+
}
|
|
27
|
+
if (ROUTER_SESSION.test(line)) {
|
|
28
|
+
return { kind: "router-session" }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const force = line.match(/^(?:\$|\/)(?:force-model|fm)\s+(\S[\s\S]*)$/i)
|
|
32
|
+
if (force) {
|
|
33
|
+
const model = force[1].trim()
|
|
34
|
+
if (model) return { kind: "force-model", model }
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
if (FORCE_MODEL.test(line)) return undefined
|
|
38
|
+
|
|
39
|
+
const feedback = line.match(/^(?:\$|\/)(?:router-feedback|rf)(?:\s+([\s\S]*))?$/i)
|
|
40
|
+
if (feedback && ROUTER_FEEDBACK.test(line)) {
|
|
41
|
+
return { kind: "router-feedback", payload: (feedback[1] ?? "").trim() }
|
|
42
|
+
}
|
|
43
|
+
return undefined
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function rewriteRouterDirective(text: string): string | undefined {
|
|
47
|
+
const directive = parseRouterDirective(text)
|
|
48
|
+
if (!directive) return undefined
|
|
49
|
+
switch (directive.kind) {
|
|
50
|
+
case "force-model":
|
|
51
|
+
return ` /force-model ${directive.model}`
|
|
52
|
+
case "unforce-model":
|
|
53
|
+
return " /unforce-model"
|
|
54
|
+
case "router-feedback":
|
|
55
|
+
return directive.payload ? ` /router-feedback ${directive.payload}` : " /router-feedback"
|
|
56
|
+
case "router-session":
|
|
57
|
+
return " /router-session"
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function rewriteDirectiveParts<T extends { type: string; text?: string }>(parts: T[]): boolean {
|
|
62
|
+
let rewritten = false
|
|
63
|
+
for (const part of parts) {
|
|
64
|
+
if (part.type !== "text" || typeof part.text !== "string") continue
|
|
65
|
+
const next = rewriteRouterDirective(part.text)
|
|
66
|
+
if (next === undefined) continue
|
|
67
|
+
part.text = next
|
|
68
|
+
rewritten = true
|
|
69
|
+
break
|
|
70
|
+
}
|
|
71
|
+
return rewritten
|
|
72
|
+
}
|
|
@@ -29,15 +29,16 @@
|
|
|
29
29
|
* - provider `weave-claude` : login-only; owns the Claude login. Its token is
|
|
30
30
|
* read from opencode's on-disk auth store by the
|
|
31
31
|
* `weave` loader (the SDK has no get-by-id).
|
|
32
|
-
* Connecting
|
|
33
|
-
*
|
|
34
|
-
* Weave key pays) — the loader simply doesn't run.
|
|
32
|
+
* Connecting either account activates that subscription independently. With
|
|
33
|
+
* neither connected, `weave` is a plain router provider and the Weave key pays.
|
|
35
34
|
*/
|
|
36
35
|
|
|
37
36
|
import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin"
|
|
37
|
+
import type { AssistantMessage, Message } from "@opencode-ai/sdk"
|
|
38
38
|
import { readFile } from "node:fs/promises"
|
|
39
39
|
import { homedir } from "node:os"
|
|
40
40
|
import { join } from "node:path"
|
|
41
|
+
import { rewriteDirectiveParts } from "./directives.ts"
|
|
41
42
|
|
|
42
43
|
// ---- ChatGPT (Codex) OAuth -------------------------------------------------
|
|
43
44
|
const CHATGPT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
|
|
@@ -45,7 +46,9 @@ const CHATGPT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
|
|
|
45
46
|
// bundled codex plugin's `options.issuer`).
|
|
46
47
|
const CHATGPT_ISSUER = process.env.WEAVE_CODEX_OAUTH_ISSUER ?? "https://auth.openai.com"
|
|
47
48
|
const OAUTH_PORT = 1455
|
|
49
|
+
const OAUTH_TIMEOUT_MS = 5 * 60 * 1000
|
|
48
50
|
const OAUTH_POLLING_SAFETY_MARGIN_MS = 3000
|
|
51
|
+
const ACCESS_TOKEN_REFRESH_MARGIN_MS = 60 * 1000
|
|
49
52
|
|
|
50
53
|
// ---- Claude (Anthropic) OAuth ----------------------------------------------
|
|
51
54
|
// Canonical Claude Pro/Max OAuth (the same flow Claude Code uses): a manual
|
|
@@ -64,6 +67,9 @@ const ANTHROPIC_SCOPE = "org:create_api_key user:profile user:inference"
|
|
|
64
67
|
// opencode's bundled provider plugins, which rewrite the upstream off the router.
|
|
65
68
|
const PROVIDER_ID = "weave"
|
|
66
69
|
const ANTHROPIC_PROVIDER_ID = "weave-claude"
|
|
70
|
+
const HEADER_ROUTER_MODEL = "x-router-model"
|
|
71
|
+
const TOAST_TITLE = "Weave Router"
|
|
72
|
+
const TOAST_DURATION_MS = 6000
|
|
67
73
|
|
|
68
74
|
// Dedicated router subscription headers. Must match the constants in
|
|
69
75
|
// internal/server/middleware/auth.go so the router stashes each sub and resolves
|
|
@@ -72,6 +78,18 @@ const HEADER_OPENAI_SUB = "X-Weave-OpenAI-Subscription"
|
|
|
72
78
|
const HEADER_OPENAI_ACCOUNT_ID = "X-Weave-OpenAI-Account-ID"
|
|
73
79
|
const HEADER_ANTHROPIC_SUB = "X-Weave-Anthropic-Subscription"
|
|
74
80
|
|
|
81
|
+
// Lifecycle metadata for turn classification only (title/subagent/compaction
|
|
82
|
+
// pin safety). Must match internal/requestcontext.OpenCodeAgentHeader; the
|
|
83
|
+
// router ignores it for auth, billing, and provider eligibility.
|
|
84
|
+
const HEADER_OPENCODE_AGENT = "X-Weave-OpenCode-Agent"
|
|
85
|
+
const HEADER_OPENCODE_REQUEST_ID = "X-Weave-OpenCode-Request-ID"
|
|
86
|
+
type OpenCodeAgent = "build" | "title" | "explore" | "compaction"
|
|
87
|
+
const OPENCODE_AGENTS: ReadonlySet<string> = new Set<OpenCodeAgent>(["build", "title", "explore", "compaction"])
|
|
88
|
+
|
|
89
|
+
function knownOpenCodeAgent(agent: string | undefined): OpenCodeAgent | undefined {
|
|
90
|
+
return agent !== undefined && OPENCODE_AGENTS.has(agent) ? (agent as OpenCodeAgent) : undefined
|
|
91
|
+
}
|
|
92
|
+
|
|
75
93
|
// Placeholder so the @ai-sdk/openai provider considers auth configured; the
|
|
76
94
|
// loader's fetch carries the real subscriptions in the dedicated headers and the
|
|
77
95
|
// router authenticates off X-Weave-Router-Key, so this value is never used.
|
|
@@ -281,6 +299,10 @@ function opencodeAuthFile(): string {
|
|
|
281
299
|
return join(dataHome, "opencode", "auth.json")
|
|
282
300
|
}
|
|
283
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
|
+
|
|
284
306
|
async function readStoredOAuth(providerID: string): Promise<StoredOAuth | undefined> {
|
|
285
307
|
try {
|
|
286
308
|
const raw = await readFile(opencodeAuthFile(), "utf8")
|
|
@@ -351,10 +373,15 @@ async function startOAuthServer(): Promise<{ redirectUri: string }> {
|
|
|
351
373
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" })
|
|
352
374
|
res.end(HTML_SUCCESS)
|
|
353
375
|
})
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
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
|
+
}
|
|
358
385
|
return { redirectUri }
|
|
359
386
|
}
|
|
360
387
|
|
|
@@ -380,7 +407,7 @@ function waitForOAuthCallback(pkce: PkceCodes, state: string): Promise<TokenResp
|
|
|
380
407
|
pendingOAuth = undefined
|
|
381
408
|
reject(new Error("OAuth callback timeout - authorization took too long"))
|
|
382
409
|
}
|
|
383
|
-
},
|
|
410
|
+
}, OAUTH_TIMEOUT_MS)
|
|
384
411
|
entry = {
|
|
385
412
|
pkce,
|
|
386
413
|
state,
|
|
@@ -399,14 +426,73 @@ function waitForOAuthCallback(pkce: PkceCodes, state: string): Promise<TokenResp
|
|
|
399
426
|
|
|
400
427
|
// ---- Request provider: `weave` (Responses, both subs) ----------------------
|
|
401
428
|
|
|
429
|
+
function compactTokenCount(n: number): string {
|
|
430
|
+
if (n >= 1000) {
|
|
431
|
+
const k = n / 1000
|
|
432
|
+
return `${k >= 10 ? k.toFixed(0) : k.toFixed(1).replace(/\.0$/, "")}k`
|
|
433
|
+
}
|
|
434
|
+
return String(n)
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function formatCost(cost: number): string {
|
|
438
|
+
if (!Number.isFinite(cost) || cost <= 0) return ""
|
|
439
|
+
if (cost < 0.001) return "<$0.001"
|
|
440
|
+
return `$${cost.toFixed(3).replace(/0+$/, "").replace(/\.$/, "")}`
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function formatRoutedToast(routedModelID: string, cost: number, tokens: { input: number; output: number }): string {
|
|
444
|
+
const parts = [`→ ${routedModelID}`]
|
|
445
|
+
const costLabel = formatCost(cost)
|
|
446
|
+
if (costLabel) parts.push(costLabel)
|
|
447
|
+
const usage: string[] = []
|
|
448
|
+
if (tokens.input > 0) usage.push(`${compactTokenCount(tokens.input)} in`)
|
|
449
|
+
if (tokens.output > 0) usage.push(`${compactTokenCount(tokens.output)} out`)
|
|
450
|
+
if (usage.length > 0) parts.push(usage.join(" / "))
|
|
451
|
+
return parts.join(" · ")
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function isCompletedWeaveAssistant(info: Message): info is AssistantMessage {
|
|
455
|
+
if (info.role !== "assistant") return false
|
|
456
|
+
if (info.providerID !== PROVIDER_ID) return false
|
|
457
|
+
if (!info.modelID) return false
|
|
458
|
+
return info.time.completed !== undefined
|
|
459
|
+
}
|
|
460
|
+
|
|
402
461
|
export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> => {
|
|
462
|
+
const pendingRequestMessageIDs = new Map<string, string>()
|
|
463
|
+
const routedModelIDsByMessage = new Map<string, string>()
|
|
464
|
+
const toastedMessageIDs = new Set<string>()
|
|
403
465
|
return {
|
|
466
|
+
"chat.message": async (_hookInput, output) => {
|
|
467
|
+
rewriteDirectiveParts(output.parts)
|
|
468
|
+
},
|
|
469
|
+
event: async ({ event }) => {
|
|
470
|
+
if (event.type !== "message.updated") return
|
|
471
|
+
const info = event.properties.info
|
|
472
|
+
if (!isCompletedWeaveAssistant(info)) return
|
|
473
|
+
if (toastedMessageIDs.has(info.id)) return
|
|
474
|
+
toastedMessageIDs.add(info.id)
|
|
475
|
+
const routedModelID = routedModelIDsByMessage.get(info.parentID) ?? info.modelID
|
|
476
|
+
routedModelIDsByMessage.delete(info.parentID)
|
|
477
|
+
for (const [requestID, messageID] of pendingRequestMessageIDs) {
|
|
478
|
+
if (messageID === info.parentID) pendingRequestMessageIDs.delete(requestID)
|
|
479
|
+
}
|
|
480
|
+
try {
|
|
481
|
+
await input.client.tui.showToast({
|
|
482
|
+
body: {
|
|
483
|
+
title: TOAST_TITLE,
|
|
484
|
+
message: formatRoutedToast(routedModelID, info.cost, info.tokens),
|
|
485
|
+
variant: "info",
|
|
486
|
+
duration: TOAST_DURATION_MS,
|
|
487
|
+
},
|
|
488
|
+
})
|
|
489
|
+
} catch {
|
|
490
|
+
// Toast is best-effort; a TUI miss must not fail the turn.
|
|
491
|
+
}
|
|
492
|
+
},
|
|
404
493
|
auth: {
|
|
405
494
|
provider: PROVIDER_ID,
|
|
406
495
|
async loader(getAuth) {
|
|
407
|
-
const auth = await getAuth()
|
|
408
|
-
if (auth.type !== "oauth") return {}
|
|
409
|
-
|
|
410
496
|
// Coalesce concurrent refreshes (opencode fires parallel turns), one
|
|
411
497
|
// in-flight promise per subscription.
|
|
412
498
|
let chatgptRefresh: Promise<{ access: string; accountId: string | undefined }> | undefined
|
|
@@ -420,7 +506,7 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
420
506
|
// Use a still-valid access token regardless of whether a refresh token
|
|
421
507
|
// is present (a partial store could lack it). Only an expired/absent
|
|
422
508
|
// access needs a refresh — and that needs the refresh token.
|
|
423
|
-
if (
|
|
509
|
+
if (hasFreshAccess(current)) {
|
|
424
510
|
return { access: current.access, accountId: current.accountId }
|
|
425
511
|
}
|
|
426
512
|
// Access is expired/absent: a refresh is the only way forward, so
|
|
@@ -455,7 +541,7 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
455
541
|
async function resolveAnthropic(): Promise<string | undefined> {
|
|
456
542
|
const current = await readStoredOAuth(ANTHROPIC_PROVIDER_ID)
|
|
457
543
|
if (!current) return undefined
|
|
458
|
-
if (
|
|
544
|
+
if (hasFreshAccess(current)) return current.access
|
|
459
545
|
// Access is expired/absent: only a refresh can produce a live token,
|
|
460
546
|
// so without a refresh token there's no usable credential to inject —
|
|
461
547
|
// returning the stale token would have the router treat a dead Claude
|
|
@@ -471,10 +557,7 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
471
557
|
})
|
|
472
558
|
return tokens.access
|
|
473
559
|
})
|
|
474
|
-
|
|
475
|
-
// (possibly stale) token; an expired Claude turn the router can't
|
|
476
|
-
// bill to the plan falls through to the Weave key on its end.
|
|
477
|
-
.catch(() => current.access)
|
|
560
|
+
.catch(() => undefined)
|
|
478
561
|
.finally(() => {
|
|
479
562
|
anthropicRefresh = undefined
|
|
480
563
|
})
|
|
@@ -506,7 +589,20 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
506
589
|
}
|
|
507
590
|
if (anthropic) headers.set(HEADER_ANTHROPIC_SUB, anthropic)
|
|
508
591
|
|
|
509
|
-
|
|
592
|
+
const requestID = headers.get(HEADER_OPENCODE_REQUEST_ID)
|
|
593
|
+
let routedModelCaptured = false
|
|
594
|
+
try {
|
|
595
|
+
const response = await fetch(requestInput, { ...init, headers })
|
|
596
|
+
const messageID = requestID ? pendingRequestMessageIDs.get(requestID) : undefined
|
|
597
|
+
const routedModelID = response.headers.get(HEADER_ROUTER_MODEL)
|
|
598
|
+
if (messageID && routedModelID) {
|
|
599
|
+
routedModelIDsByMessage.set(messageID, routedModelID)
|
|
600
|
+
routedModelCaptured = true
|
|
601
|
+
}
|
|
602
|
+
return response
|
|
603
|
+
} finally {
|
|
604
|
+
if (requestID && routedModelCaptured) pendingRequestMessageIDs.delete(requestID)
|
|
605
|
+
}
|
|
510
606
|
},
|
|
511
607
|
}
|
|
512
608
|
},
|
|
@@ -524,14 +620,17 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
524
620
|
instructions: "Complete authorization in your browser. This window will close automatically.",
|
|
525
621
|
method: "auto" as const,
|
|
526
622
|
callback: async () => {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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()
|
|
535
634
|
}
|
|
536
635
|
},
|
|
537
636
|
}
|
|
@@ -558,8 +657,9 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
558
657
|
instructions: `Enter code: ${deviceData.user_code}`,
|
|
559
658
|
method: "auto" as const,
|
|
560
659
|
async callback() {
|
|
561
|
-
const sleep = (ms: number) => new Promise((
|
|
562
|
-
|
|
660
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
661
|
+
const deadline = Date.now() + OAUTH_TIMEOUT_MS
|
|
662
|
+
while (Date.now() < deadline) {
|
|
563
663
|
const response = await fetch(`${CHATGPT_ISSUER}/api/accounts/deviceauth/token`, {
|
|
564
664
|
method: "POST",
|
|
565
665
|
headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
|
|
@@ -594,6 +694,7 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
594
694
|
if (response.status !== 403 && response.status !== 404) return { type: "failed" as const }
|
|
595
695
|
await sleep(interval + OAUTH_POLLING_SAFETY_MARGIN_MS)
|
|
596
696
|
}
|
|
697
|
+
return { type: "failed" as const }
|
|
597
698
|
},
|
|
598
699
|
}
|
|
599
700
|
},
|
|
@@ -607,6 +708,15 @@ export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> =>
|
|
|
607
708
|
if (hookInput.model.providerID !== PROVIDER_ID) return
|
|
608
709
|
output.headers["originator"] = "codex_cli_ts"
|
|
609
710
|
output.headers["session-id"] = hookInput.sessionID
|
|
711
|
+
const messageID = hookInput.message?.id
|
|
712
|
+
if (messageID) {
|
|
713
|
+
const requestID = crypto.randomUUID()
|
|
714
|
+
pendingRequestMessageIDs.set(requestID, messageID)
|
|
715
|
+
output.headers[HEADER_OPENCODE_REQUEST_ID] = requestID
|
|
716
|
+
}
|
|
717
|
+
// Custom agents are user-named; only OpenCode's own lifecycle agents are forwarded.
|
|
718
|
+
const agent = knownOpenCodeAgent(hookInput.agent)
|
|
719
|
+
if (agent) output.headers[HEADER_OPENCODE_AGENT] = agent
|
|
610
720
|
},
|
|
611
721
|
"chat.params": async (hookInput, output) => {
|
|
612
722
|
if (hookInput.model.providerID !== PROVIDER_ID) return
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weave-os/router",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.20",
|
|
4
4
|
"description": "One-command installer that points Claude Code, Codex, opencode, or pi at the Weave Router. For pi it also ships the routing extension, loaded via pi.extensions.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"weave-router": "bin.js",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"uninstall.sh",
|
|
21
21
|
"cc-statusline.sh",
|
|
22
22
|
"codex-status.sh",
|
|
23
|
+
"codex-toggle.sh",
|
|
23
24
|
"registry.sh",
|
|
24
25
|
"directives.tsv",
|
|
25
26
|
"commands/",
|
package/pi-router/README.md
CHANGED
|
@@ -18,12 +18,15 @@ That writes `~/.pi/agent/models.json` (the `weave` provider), adds
|
|
|
18
18
|
`npm:@weave-os/router` to `~/.pi/agent/settings.json` `packages`, and stores
|
|
19
19
|
the key in `~/.pi/agent/.weave_router_key`. pi auto-installs `@weave-os/router`
|
|
20
20
|
from npm on next start and loads this extension via its `pi.extensions` field.
|
|
21
|
+
Plain `pi` then connects to the installed endpoint, normally
|
|
22
|
+
`https://router.workweave.ai`; it does not start a local Python proxy.
|
|
21
23
|
|
|
22
24
|
## What it does
|
|
23
25
|
|
|
24
26
|
- **Loom experience on stock pi.** Replaces pi's startup header through the
|
|
25
|
-
public extension API
|
|
26
|
-
|
|
27
|
+
public extension API and keeps pi's own runtime/footer intact. Wooly is hidden
|
|
28
|
+
by default; `/wooly` toggles the orange terminal animation for the current
|
|
29
|
+
session. Wooly is visual only: there is no
|
|
27
30
|
dialogue box, narration, coaching request, or separate Loom runtime.
|
|
28
31
|
- **Automatic model selection.** All pi traffic flows through the router, which
|
|
29
32
|
selects the model per request. You don't pick a model — the router does.
|
|
@@ -83,7 +86,7 @@ from npm on next start and loads this extension via its `pi.extensions` field.
|
|
|
83
86
|
|
|
84
87
|
| Variable | Default | Purpose |
|
|
85
88
|
|---|---|---|
|
|
86
|
-
| `WEAVE_ROUTER_URL` | `
|
|
89
|
+
| `WEAVE_ROUTER_URL` | installed `models.json` endpoint, normally hosted | Override router base URL (children inherit it); an unconfigured extension falls back to `http://localhost:8080` |
|
|
87
90
|
| `WEAVE_ROUTER_KEY` | — | Router key (else read from `.weave_router_key`) |
|
|
88
91
|
| `WEAVE_ROUTER_KEY_FILE` | `<agentDir>/.weave_router_key` | Override key file path |
|
|
89
92
|
| `WEAVE_USER_EMAIL` / `WEAVE_USER_NAME` | from `git config` | Identity headers for attribution |
|
|
@@ -94,6 +97,7 @@ from npm on next start and loads this extension via its `pi.extensions` field.
|
|
|
94
97
|
| `WEAVE_ROUTING_ALPHA` / `…_SPEED_WEIGHT` / `…_OUTPUT_COST_RATIO` / `…_EXPECTED_OUTPUT_TOKENS` | role preset | Override individual routing knobs (main process only — children always use their role preset) |
|
|
95
98
|
| `WEAVE_NO_SAFETY` | unset | `1` disables the catastrophic-bash gate |
|
|
96
99
|
| `WEAVE_PI_AUTO_COMPACTION` | unset | `0` disables the routed tool-loop compaction safeguard |
|
|
100
|
+
| `WEAVE_PI_ESCALATION_COMPACTION` | enabled | `0` disables preparation and compaction before upward complexity model changes; requires Pi 0.83+ and the matching router deployment |
|
|
97
101
|
| `WEAVE_PI_NO_LSP` | unset | `1` disables the `lsp` tool, the server pool, and the subagent broker |
|
|
98
102
|
| `WEAVE_PI_LSP_IDLE_MS` | `300000` | Idle window before an unused language server is shut down |
|
|
99
103
|
| `WEAVE_PI_LSP_REQUEST_TIMEOUT_MS` | `15000` | Per-request budget once a server is warm |
|
|
@@ -106,6 +110,68 @@ Internal: `WEAVE_PI_SUBAGENT=1`, `WEAVE_PI_SUBAGENT_ID`, `WEAVE_PI_LSP_BROKER`,
|
|
|
106
110
|
and `WEAVE_PI_LSP_BROKER_TOKEN` are set by `dispatch` on child processes; don't
|
|
107
111
|
set them yourself.
|
|
108
112
|
|
|
113
|
+
## Escalation compaction
|
|
114
|
+
|
|
115
|
+
Escalation compaction is enabled by default on Pi 0.83 or newer. Older Pi
|
|
116
|
+
versions warn at startup and continue routing without escalation compaction.
|
|
117
|
+
The router requires the same
|
|
118
|
+
`ROUTER_PI_HANDOFF_SECRET` (at least 32 bytes) on every replica. Set
|
|
119
|
+
`WEAVE_PI_ESCALATION_COMPACTION=0` to opt out. An enabled client stops
|
|
120
|
+
with a visible error if preparation is unavailable; it never falls back to
|
|
121
|
+
silently sending the full unreserved request.
|
|
122
|
+
|
|
123
|
+
`POST /v1/route/handoff` uses the authenticated Messages middleware and serving
|
|
124
|
+
route selection, including session pins and confidence guards. It stops before
|
|
125
|
+
provider dispatch and returns a signed continuation ticket valid for ten
|
|
126
|
+
minutes. Preparation can update routing pins; it is not a side-effect-free
|
|
127
|
+
preview. The ticket is bound to the key, installation, session, strategy,
|
|
128
|
+
requested model, tools and reasoning configuration. Dispatch rechecks current
|
|
129
|
+
model eligibility and explicit force state. Expired or stale tickets return
|
|
130
|
+
409; a new user turn prepares again. Model-selection tickets remain in memory
|
|
131
|
+
and are never saved in the Pi transcript.
|
|
132
|
+
|
|
133
|
+
Preparation also returns a signed thread-continuity token (`session_token`).
|
|
134
|
+
Pi saves it as a session entry and sends it as `weave_session` on preparation,
|
|
135
|
+
summary and continuation requests. It preserves the original first-message
|
|
136
|
+
digest across compaction and process restarts, and binds it to the API key,
|
|
137
|
+
installation, client session and metadata identity. A `pi:` prefix alone never
|
|
138
|
+
bypasses the first-message discriminator. This token has no model selection or
|
|
139
|
+
credentials and lasts for the conversation; signing-secret rotation invalidates
|
|
140
|
+
it. Every request still requires normal authentication. Deploy the router before
|
|
141
|
+
using the updated extension, which requires this field in preparation responses.
|
|
142
|
+
|
|
143
|
+
The main Pi session compacts when the observed class increases through
|
|
144
|
+
`low → medium → high → maximum`, the served model changes, and estimated context
|
|
145
|
+
is at least 32,768 tokens. Unknown classes and the initial turn establish a
|
|
146
|
+
baseline. Utility turns, forced models, subagents, subscription bypass, native
|
|
147
|
+
server tools and non-authoritative routing retain their existing behavior.
|
|
148
|
+
|
|
149
|
+
A separate ticket directs summarization to the previously served model without
|
|
150
|
+
repinning the session. The summary request preserves the original system,
|
|
151
|
+
tools, thinking settings and message prefix, appending a checkpoint instruction
|
|
152
|
+
so existing provider caches can be reused. Pi owns the compaction boundary and
|
|
153
|
+
retained recent messages; the original transcript remains on disk. Its normal
|
|
154
|
+
summary generation can use separate summaries for a split turn. Compaction
|
|
155
|
+
failure stops the handoff and leaves the transcript available. New user input,
|
|
156
|
+
session navigation or model selection cancels a pending continuation.
|
|
157
|
+
|
|
158
|
+
The continuation carries the selected model ticket, so the shortened history
|
|
159
|
+
is not reclassified. Summarization still costs tokens and adds latency; actual
|
|
160
|
+
cache hits and net savings require a provider-backed measurement. The client
|
|
161
|
+
savings display does not yet include these auxiliary summary calls.
|
|
162
|
+
|
|
163
|
+
Offline validation:
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
bash install/pi-router/test/e2e.sh
|
|
167
|
+
python3 install/pi-router/test/handoff-e2e.py
|
|
168
|
+
go test ./internal/proxy ./internal/api/anthropic ./internal/server
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Development dependencies alias the legacy Pi module names to Pi 0.83. The
|
|
172
|
+
TypeScript `pi-ai` path targets its compatibility entrypoint, matching Pi's
|
|
173
|
+
extension loader; this preserves the runtime's shared provider registry.
|
|
174
|
+
|
|
109
175
|
## Billing
|
|
110
176
|
|
|
111
177
|
Routing through the router switches pi from Claude **subscription OAuth** to
|
package/pi-router/package.json
CHANGED
|
@@ -14,10 +14,10 @@
|
|
|
14
14
|
"typebox": "*"
|
|
15
15
|
},
|
|
16
16
|
"devDependencies": {
|
|
17
|
-
"@mariozechner/pi-agent-core": "0.
|
|
18
|
-
"@mariozechner/pi-ai": "0.
|
|
19
|
-
"@mariozechner/pi-coding-agent": "0.
|
|
20
|
-
"@mariozechner/pi-tui": "0.
|
|
17
|
+
"@mariozechner/pi-agent-core": "npm:@earendil-works/pi-agent-core@0.83.0",
|
|
18
|
+
"@mariozechner/pi-ai": "npm:@earendil-works/pi-ai@0.83.0",
|
|
19
|
+
"@mariozechner/pi-coding-agent": "npm:@earendil-works/pi-coding-agent@0.83.0",
|
|
20
|
+
"@mariozechner/pi-tui": "npm:@earendil-works/pi-tui@0.83.0",
|
|
21
21
|
"@types/node": "24.13.3",
|
|
22
22
|
"typebox": "1.3.25",
|
|
23
23
|
"typescript": "5.9.3"
|
|
@@ -85,7 +85,7 @@ function latestCompactionId(ctx: ExtensionContext): string | undefined {
|
|
|
85
85
|
return undefined;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
export function registerCompaction(pi: ExtensionAPI, schedule: Schedule = (callback) => setTimeout(callback, 0)): void {
|
|
88
|
+
export function registerCompaction(pi: ExtensionAPI, schedule: Schedule = (callback) => setTimeout(callback, 0), handoffPending = () => false): void {
|
|
89
89
|
let highWaterTokens = 0;
|
|
90
90
|
let lastTurnTokens = 0;
|
|
91
91
|
let repairedContinuation = false;
|
|
@@ -136,7 +136,7 @@ export function registerCompaction(pi: ExtensionAPI, schedule: Schedule = (callb
|
|
|
136
136
|
});
|
|
137
137
|
|
|
138
138
|
pi.on("agent_end", (_event: AgentEndEvent, ctx: ExtensionContext) => {
|
|
139
|
-
if (process.env.WEAVE_PI_AUTO_COMPACTION === "0" || compactionScheduled) return;
|
|
139
|
+
if (process.env.WEAVE_PI_AUTO_COMPACTION === "0" || compactionScheduled || handoffPending()) return;
|
|
140
140
|
const registeredWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow ?? 0;
|
|
141
141
|
const contextWindow = servedContextWindow ?? registeredWindow;
|
|
142
142
|
if (contextWindow <= COMPACTION_RESERVE_TOKENS) return;
|