@weave-os/router 0.2.24 → 0.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/uninstall.sh CHANGED
@@ -265,6 +265,171 @@ if { [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi
265
265
  exit 1
266
266
  fi
267
267
 
268
+ # ---------- lifecycle report ----------
269
+ #
270
+ # report_uninstall_event tells this install's router that the uninstall is
271
+ # happening, so it can log and export a lifecycle event. It runs before the
272
+ # key and config are removed (afterwards there is nothing left to
273
+ # authenticate with) and is strictly best-effort: the POST is detached with a
274
+ # short timeout, output discarded, and no failure changes the uninstall.
275
+ # uninstall.sh is served standalone, so the config readers install.sh already
276
+ # has are reduced here to the one field each: the endpoint and key of the
277
+ # managed provider block. A file git tracks is a checkout's, not this user's
278
+ # install, and never supplies a key; a checkout-supplied endpoint never
279
+ # receives one (same gates as install.sh's key_source_is_own and
280
+ # models_endpoint_is_trusted).
281
+ HOSTED_BASE_URL="https://router.workweave.ai"
282
+ ROUTER_KEY_HEADER="X-Weave-Router-Key"
283
+
284
+ uninstall_json_get() {
285
+ [ -f "$1" ] || return 0
286
+ jq -r "${2} // empty" "$1" 2>/dev/null || true
287
+ }
288
+
289
+ # uninstall_file_is_own mirrors key_source_is_own: only a project-scoped file
290
+ # is reachable by a repo, and one git tracks is not this user's install.
291
+ uninstall_file_is_own() {
292
+ local f="$1"
293
+ [ -f "$f" ] || return 1
294
+ [ -L "$f" ] && return 1
295
+ [ "$scope" = "project" ] && [ -z "$install_dir" ] || return 0
296
+ command -v git >/dev/null 2>&1 || return 1
297
+ git -C "$(dirname "$f")" ls-files --error-unmatch -- "$f" >/dev/null 2>&1 && return 1
298
+ return 0
299
+ }
300
+
301
+ uninstall_file_is_tracked() {
302
+ command -v git >/dev/null 2>&1 || return 1
303
+ git -C "$(dirname "$1")" ls-files --error-unmatch -- "$1" >/dev/null 2>&1
304
+ }
305
+
306
+ # uninstall_claude_key_from FILE prints the router key header value out of a
307
+ # Claude Code settings-shaped file ({"env":{"ANTHROPIC_CUSTOM_HEADERS":…}}).
308
+ uninstall_claude_key_from() {
309
+ uninstall_json_get "$1" '.env.ANTHROPIC_CUSTOM_HEADERS' \
310
+ | sed -n "s/^[[:space:]]*${ROUTER_KEY_HEADER}:[[:space:]]*//p" | head -n 1 | tr -d '[:space:]'
311
+ }
312
+
313
+ # report_uninstall_event HARNESS ENDPOINT KEY — fire the detached POST. The
314
+ # whole body runs in a subshell with errexit off so no setup failure can
315
+ # escape into the uninstall that still has files to remove.
316
+ report_uninstall_event() {
317
+ local harness="$1" endpoint="${2%/}" key="$3"
318
+ (
319
+ set +e
320
+ headers="" body=""
321
+ [ -n "$endpoint" ] && [ -n "$key" ] || exit 0
322
+ command -v curl >/dev/null 2>&1 || exit 0
323
+ headers="$(mktemp)" || exit 0
324
+ chmod 600 "$headers" || { rm -f "$headers"; exit 0; }
325
+ printf '%s: %s\n' "$ROUTER_KEY_HEADER" "$key" >"$headers" || { rm -f "$headers"; exit 0; }
326
+ body="$(printf '{"action":"uninstall","harness":"%s"}' "$harness")"
327
+ (
328
+ trap 'rm -f "$headers"' EXIT
329
+ curl -sS --max-time 2 -X POST -H 'Content-Type: application/json' \
330
+ --header "@$headers" --data-binary "$body" -o /dev/null \
331
+ "$endpoint/v1/client-events"
332
+ ) >/dev/null 2>&1 </dev/null &
333
+ ) >/dev/null 2>&1 || true
334
+ return 0
335
+ }
336
+
337
+ # report_claude_uninstall_event reads the endpoint and key the way install.sh's
338
+ # resolve_installed_endpoint / read_installed_key do for Claude Code: the
339
+ # parked sidecar first (while toggled off it holds both), then the settings
340
+ # files. Endpoint and key from the same file are self-consistent; otherwise the
341
+ # endpoint must be the hosted default, vouched for by the private
342
+ # WEAVE_ROUTER_BASE_URL marker beside the key, or live in a file git does not
343
+ # track.
344
+ report_claude_uninstall_event() {
345
+ local parked candidate endpoint="" base_src="" key="" key_src="" found marked
346
+ parked="$(dirname "$settings_file")/.weave-parked.json"
347
+ for candidate in "$parked" "$settings_file" "$local_settings_file"; do
348
+ if [ -z "$candidate" ] || [ ! -f "$candidate" ] || [ -L "$candidate" ]; then continue; fi
349
+ found="$(uninstall_json_get "$candidate" '.env.ANTHROPIC_BASE_URL')"
350
+ case "$found" in ""|https://api.anthropic.com*|http://api.anthropic.com*) continue ;; esac
351
+ endpoint="${found%/}"; base_src="$candidate"
352
+ break
353
+ done
354
+ [ -n "$endpoint" ] || return 0
355
+ for candidate in "$local_settings_file" "$settings_file" "$parked"; do
356
+ if [ -z "$candidate" ] || [ ! -f "$candidate" ] || [ -L "$candidate" ]; then continue; fi
357
+ key="$(uninstall_claude_key_from "$candidate")"
358
+ [ -n "$key" ] && { key_src="$candidate"; break; }
359
+ done
360
+ [ -n "$key" ] || return 0
361
+ local trusted="false"
362
+ if [ "$endpoint" = "${HOSTED_BASE_URL%/}" ] || [ "$base_src" = "$key_src" ]; then
363
+ trusted="true"
364
+ elif [ -n "$local_settings_file" ] && [ -f "$local_settings_file" ] && [ ! -L "$local_settings_file" ]; then
365
+ marked="$(uninstall_json_get "$local_settings_file" '.env.WEAVE_ROUTER_BASE_URL')"
366
+ if [ "${marked%/}" = "$endpoint" ]; then
367
+ uninstall_file_is_tracked "$local_settings_file" || trusted="true"
368
+ fi
369
+ fi
370
+ if [ "$trusted" != "true" ]; then
371
+ command -v git >/dev/null 2>&1 || return 0
372
+ uninstall_file_is_tracked "$base_src" && return 0
373
+ fi
374
+ report_uninstall_event claude_code "$endpoint" "$key"
375
+ }
376
+
377
+ # report_codex_uninstall_event reads base_url and the key header out of the
378
+ # [model_providers.weave] table wherever it sits (Codex's serializer drops the
379
+ # managed markers and may move the header into a subtable).
380
+ report_codex_uninstall_event() {
381
+ local f="$1" endpoint key
382
+ uninstall_file_is_own "$f" || return 0
383
+ endpoint="$(awk '
384
+ /^[[:space:]]*\[/ {
385
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*\][[:space:]]*(#.*)?$/)
386
+ next
387
+ }
388
+ in_provider && match($0, /^[[:space:]]*base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
389
+ line = substr($0, RSTART, RLENGTH)
390
+ sub(/^.*=[[:space:]]*"/, "", line)
391
+ sub(/"$/, "", line)
392
+ print line
393
+ exit
394
+ }
395
+ ' "$f" 2>/dev/null || true)"
396
+ endpoint="${endpoint%/}"; endpoint="${endpoint%/v1}"
397
+ key="$(awk '
398
+ /^[[:space:]]*\[/ {
399
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/)
400
+ next
401
+ }
402
+ in_provider && match($0, /"?X-Weave-Router-Key"?[[:space:]]*=[[:space:]]*"[^"]*"/) {
403
+ hdr = substr($0, RSTART, RLENGTH)
404
+ sub(/^.*=[[:space:]]*"/, "", hdr)
405
+ sub(/"$/, "", hdr)
406
+ print hdr
407
+ exit
408
+ }
409
+ ' "$f" 2>/dev/null || true)"
410
+ report_uninstall_event codex "$endpoint" "$key"
411
+ }
412
+
413
+ report_opencode_uninstall_event() {
414
+ local f="$1" endpoint key
415
+ uninstall_file_is_own "$f" || return 0
416
+ endpoint="$(uninstall_json_get "$f" '.provider.weave.options.baseURL')"
417
+ endpoint="${endpoint%/}"; endpoint="${endpoint%/v1}"
418
+ key="$(uninstall_json_get "$f" '.provider.weave.options.headers["X-Weave-Router-Key"]')"
419
+ report_uninstall_event opencode "$endpoint" "$key"
420
+ }
421
+
422
+ report_pi_uninstall_event() {
423
+ local models="$1" key_file="$2" endpoint key=""
424
+ uninstall_file_is_own "$models" || return 0
425
+ endpoint="$(uninstall_json_get "$models" '.providers.weave.baseUrl')"
426
+ if uninstall_file_is_own "$key_file"; then
427
+ key="$(tr -d '[:space:]' <"$key_file" 2>/dev/null || true)"
428
+ fi
429
+ [ -n "$key" ] || key="$(uninstall_json_get "$models" '.providers.weave.headers["X-Weave-Router-Key"]')"
430
+ report_uninstall_event pi "$endpoint" "$key"
431
+ }
432
+
268
433
  # Markers must stay in sync with install.sh. Keep verbatim.
269
434
  WEAVE_CODEX_BEGIN_MARKER="# >>> weave-router managed (do not edit between markers) >>>"
270
435
  WEAVE_CODEX_END_MARKER="# <<< weave-router managed <<<"
@@ -499,26 +664,38 @@ if [ "$target" = "opencode" ]; then
499
664
  opencode_direct_model="$(jq -r '.direct_model // empty' "$opencode_parked" 2>/dev/null || true)"
500
665
  fi
501
666
 
502
- # Canonicalize the plugin path exactly as install.sh did (`cd … && pwd`) so
503
- # the `plugin` array entry matches on removal — a raw "$opencode_dir/…" string
504
- # can differ (symlinks, trailing slash) and leave the entry behind.
667
+ # Older installers registered a v1 plugin in opencode.json and copied its
668
+ # sources into .weave/. Remove those exact legacy registrations and assets.
505
669
  if [ -d "$opencode_dir" ]; then
506
- opencode_plugin="$(cd "$opencode_dir" && pwd)/.weave/opencode-weave.ts"
670
+ opencode_plugin_dir="$(cd "$opencode_dir" && pwd)/.weave"
507
671
  else
508
- opencode_plugin="$opencode_dir/.weave/opencode-weave.ts"
672
+ opencode_plugin_dir="$opencode_dir/.weave"
509
673
  fi
674
+
675
+ report_opencode_uninstall_event "$opencode_config_file" || true
510
676
  if [ -f "$opencode_config_file" ]; then
511
- # Strip every managed provider (`weave`, the login-only `weave-claude`, and
512
- # the legacy `weave-codex` from pre-upgrade installs), the managed plugin
513
- # entry from the `plugin` array, and restore the direct model parked during
677
+ # Strip every managed provider (`weave`, `weave-claude`, and the legacy
678
+ # `weave-codex` from pre-upgrade installs), remove any stale legacy plugin
679
+ # registration, and restore the direct model parked during
514
680
  # install. Other providers, direct models selected while routing was off,
515
681
  # other plugins, and unrelated keys are preserved.
516
- cleaned="$(jq --arg plugin "$opencode_plugin" --arg direct_model "$opencode_direct_model" '
682
+ cleaned="$(jq --arg direct_model "$opencode_direct_model" '
517
683
  (if .provider.weave then del(.provider.weave) else . end)
518
684
  | (if .provider["weave-claude"] then del(.provider["weave-claude"]) else . end)
519
685
  | (if .provider["weave-codex"] then del(.provider["weave-codex"]) else . end)
520
686
  | (if (.provider // {}) == {} then del(.provider) else . end)
521
- | (if (.plugin | type) == "array" then .plugin -= [$plugin] else . end)
687
+ | (if (.providers | type) == "object"
688
+ then .providers |= del(.weave, ."weave-codex", ."weave-claude")
689
+ else .
690
+ end)
691
+ | (if (.providers | type) == "object" and (.providers | length) == 0
692
+ then del(.providers)
693
+ else .
694
+ end)
695
+ | (if (.plugin | type) == "array"
696
+ then .plugin |= map(select((tostring | test("(^|/)opencode-weave\\.ts$")) | not))
697
+ else .
698
+ end)
522
699
  | (if (.plugin | type) == "array" and (.plugin | length) == 0 then del(.plugin) else . end)
523
700
  | (if (.model // "" | tostring | (startswith("weave/") or startswith("weave-claude/") or startswith("weave-codex/")))
524
701
  then (if $direct_model != "" then .model = $direct_model else del(.model) end)
@@ -539,24 +716,18 @@ if [ "$target" = "opencode" ]; then
539
716
  info "No opencode config at $opencode_config_file (already uninstalled?)"
540
717
  fi
541
718
 
542
- # Drop the bundled subscription plugin (no secrets; the config holds the key,
543
- # opencode's own auth store holds the ChatGPT/Claude tokens). Remove the
544
- # .weave/ dir only if it's left empty so we don't clobber an unrelated user dir.
545
- if [ -f "$opencode_plugin" ]; then
546
- refuse_if_symlink "$opencode_plugin"
547
- rm -f "$opencode_plugin"
548
- opencode_directives="$(dirname "$opencode_plugin")/directives.ts"
549
- if [ -f "$opencode_directives" ]; then
550
- refuse_if_symlink "$opencode_directives"
551
- rm -f "$opencode_directives"
552
- fi
553
- opencode_classifier="$(dirname "$opencode_plugin")/classifier-thread.ts"
554
- if [ -f "$opencode_classifier" ]; then
555
- refuse_if_symlink "$opencode_classifier"
556
- rm -f "$opencode_classifier"
719
+ refuse_if_symlink "$opencode_plugin_dir"
720
+ legacy_opencode_assets_removed=false
721
+ for opencode_asset in opencode-weave.ts directives.ts classifier-thread.ts; do
722
+ refuse_if_symlink "$opencode_plugin_dir/$opencode_asset"
723
+ if [ -f "$opencode_plugin_dir/$opencode_asset" ]; then
724
+ rm -f "$opencode_plugin_dir/$opencode_asset"
725
+ legacy_opencode_assets_removed=true
557
726
  fi
558
- rmdir "$opencode_dir/.weave" 2>/dev/null || true
559
- ok "Removed $opencode_plugin"
727
+ done
728
+ rmdir "$opencode_plugin_dir" 2>/dev/null || true
729
+ if [ "$legacy_opencode_assets_removed" = "true" ]; then
730
+ ok "Removed legacy opencode plugin files"
560
731
  fi
561
732
 
562
733
  # Drop the toggle parked sidecar after its prior model has been restored.
@@ -665,6 +836,7 @@ if [ "$target" = "pi" ]; then
665
836
  refuse_if_symlink "$pi_settings_file"
666
837
  refuse_if_symlink "$pi_key_file"
667
838
 
839
+ report_pi_uninstall_event "$pi_models_file" "$pi_key_file" || true
668
840
  # models.json: drop provider.weave; remove the file if nothing else remains.
669
841
  # Other providers/models the user added are preserved.
670
842
  if [ -f "$pi_models_file" ]; then
@@ -781,6 +953,7 @@ if [ "$target" = "codex" ]; then
781
953
  # exits before strip_codex_block, so one symlinked helper left the config
782
954
  # wired to a router the uninstall had just been asked to remove.
783
955
 
956
+ report_codex_uninstall_event "$codex_config_file" || true
784
957
  if [ -f "$codex_config_file" ]; then
785
958
  strip_codex_block "$codex_config_file"
786
959
  # If the file now contains only whitespace/comments, leave it: the user
@@ -1000,6 +1173,8 @@ if claude_statusline_router_owned \
1000
1173
  statusline_file_owned="true"
1001
1174
  fi
1002
1175
 
1176
+ report_claude_uninstall_event || true
1177
+
1003
1178
  if [ -f "$settings_file" ]; then
1004
1179
  # Only remove keys we actually installed: scrub our env vars, and only
1005
1180
  # delete `statusLine` / `apiKeyHelper` when they point at scripts this
@@ -1013,7 +1188,8 @@ if [ -f "$settings_file" ]; then
1013
1188
  | (if $statusline_setting_owned == "true" then del(.statusLine) else . end)
1014
1189
  | (if (.apiKeyHelper // "" | tostring | endswith("weave-key.sh"))
1015
1190
  then del(.apiKeyHelper) else . end)
1016
- | (if ((.attribution.commit == "Co-Authored-By: Weave Router <router@workweave.ai>"
1191
+ | (if ((.attribution.commit == "Co-Authored-By: Weave Router <router@weaveos.com>"
1192
+ or .attribution.commit == "Co-Authored-By: Weave Router <router@workweave.ai>"
1017
1193
  or .attribution.commit == "Co-Authored-By: Weave Router <noreply@workweave.ai>")
1018
1194
  and .attribution.pr == "🤖 Generated with [Weave Router](https://router.workweave.ai)")
1019
1195
  then del(.attribution) else . end)
@@ -1,159 +0,0 @@
1
- # opencode Weave subscription plugin
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.
10
-
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`.
15
-
16
- ## Why a plugin (config alone can't do it)
17
-
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.
22
-
23
- ## Wire shape it produces
24
-
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:
28
-
29
- | | |
30
- |---|---|
31
- | `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
- | `X-Weave-Router-Key: rk_…` | from `opencode.json` `options.headers` — the router authenticates off this |
36
-
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.
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.
64
-
65
- ## Login
66
-
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.
76
-
77
- ## Env overrides (self-host + tests)
78
-
79
- - `WEAVE_OPENCODE_LLM_CLASSIFIER=1` — enroll only sessions created while this
80
- plugin is running. The plugin stores a separate handshake UUID and router
81
- ticket for each parent/child session under OpenCode's data directory. An
82
- enrollment failure or missing new-session event blocks inference while the
83
- opt-in is set; resume an older session with the opt-in unset. Classifier
84
- sessions cannot compact or change router origins; start
85
- a new session instead. Requires a router deployment with the exact release
86
- and installation explicitly allowlisted. Deploy the router's non-retryable
87
- client-failure response before enabling this opt-in on developer machines.
88
- - `WEAVE_CODEX_OAUTH_ISSUER` — OpenAI auth issuer.
89
- - `WEAVE_ANTHROPIC_OAUTH_AUTHORIZE` / `WEAVE_ANTHROPIC_OAUTH_TOKEN` — Anthropic
90
- OAuth authorize host / token endpoint.
91
- - `WEAVE_OPENCODE_AUTH_FILE` — path to opencode's `auth.json` (the `weave`
92
- loader reads the `weave-claude` slot from here; defaults to
93
- `$XDG_DATA_HOME/opencode/auth.json`).
94
-
95
- ## Verification
96
-
97
- The required CI contract pins **OpenCode and `@opencode-ai/plugin` 1.18.27**.
98
- The CLI install reads that pin from `package.json`; the direct Responses tests
99
- use **`@ai-sdk/openai` 3.0.84**, matching the
100
- [pinned OpenCode dependencies](https://github.com/anomalyco/opencode/blob/v1.18.27/packages/opencode/package.json).
101
- Neither required dependency floats. The separate weekly/manual
102
- [latest compatibility workflow](../../.github/workflows/opencode_latest.yml)
103
- is not a merge gate.
104
-
105
- From the router repository root (Node, Bun, Python 3.11+, and jq required):
106
-
107
- ```bash
108
- npm ci --prefix install/opencode-weave --ignore-scripts
109
- npm run --prefix install/opencode-weave typecheck
110
- bun test install/opencode-weave/test/
111
- make test-install
112
- npm install --global opencode-ai@1.18.27
113
- bash install/pi-router/test/opencode_smoke.sh
114
- go test ./internal/proxy ./internal/translate -count=1
115
- ```
116
-
117
- `OPENCODE_BIN` selects an already-installed CLI. To explicitly test another
118
- version, set `OPENCODE_EXPECTED_VERSION` to its exact version; the smoke otherwise
119
- rejects anything other than the supported pin. The driver gives each command
120
- 60 seconds, kills its process group on timeout, limits mock requests per session,
121
- and isolates HOME, XDG directories, provider selection, and credentials. Package
122
- bootstrap may use the network; inference and OAuth tests never use real credentials
123
- or real providers.
124
-
125
- | Layer | Contract |
126
- |---|---|
127
- | Bun plugin tests | All four subscription combinations; expiry, refresh failure isolation, late login; header/session continuity; no secrets logged |
128
- | Pinned Responses SDK fixtures | Streaming and non-streaming text/usage, two tool calls, upstream errors, malformed/unknown events, truncated streams, absent usage |
129
- | 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 |
130
- | Real lifecycle hooks | Main `build`, title `title`, task child `explore`, and automatic `compaction` followed by resumed `build`; parent/child session boundaries |
131
- | Real plugin loader | Both providers' OAuth methods visible through `opencode serve` → `/provider/auth`, even without an OAuth store |
132
- | Installer/package | Install/toggle/uninstall, packed npm `--opencode` entrypoint; existing Claude/Codex/Pi installer coverage |
133
- | Go proxy/translation | Native and translated Responses history hygiene, actionable tool-output commands, Codex feedback-skill preservation, wire lifecycle and usage |
134
-
135
- The lifecycle observer is a **test-only** `chat.headers` hook recording OpenCode's
136
- actual `input.agent`, not a prompt heuristic or a router-policy change. A synthetic
137
- high-usage response triggers automatic compaction without a huge prompt. Title
138
- generation uses the configured local `small_model`; task execution uses the actual
139
- `task` tool and a child session. No separate classifier/probe invocation was
140
- observed in these headless flows. Tool-less SDK fixtures cover that wire shape
141
- without claiming a classifier fingerprint. Non-streaming requests are direct SDK
142
- fixtures: the tested CLI flows use streaming.
143
-
144
- The pinned SDK silently ignores an ill-shaped known event, treats an unfinished
145
- stream as `other`, and tolerates unknown event types. It also requires usage on a
146
- streaming `response.completed`: missing usage produces `other` rather than `stop`
147
- (and can cause CLI continuation), while non-streaming missing usage remains
148
- unknown token counts. These are explicit compatibility observations, **not** claims
149
- of clean failure or successful completion. The normal CLI cases require both a
150
- successful terminal event and exact usage, so removing completion/usage fails them.
151
-
152
- The plugin intentionally uses the
153
- [legacy all-export loader](https://github.com/anomalyco/opencode/blob/v1.18.27/packages/opencode/src/plugin/index.ts):
154
- all exported values are plugin functions, `default === WeaveCodex` is deduplicated,
155
- and `WeaveClaude` registers separately. Converting the default to a V1 plugin
156
- object would bypass those named exports; the loader tests guard against that.
157
- See the current [CLI](https://opencode.ai/docs/cli/),
158
- [plugin](https://opencode.ai/docs/plugins/), and
159
- [server](https://opencode.ai/docs/server/) references when updating the pin.
@@ -1,20 +0,0 @@
1
- {
2
- "name": "@weave-os/router-opencode-extension",
3
- "private": true,
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.",
6
- "scripts": {
7
- "test": "bun test test/",
8
- "typecheck": "tsc --project tsconfig.json"
9
- },
10
- "peerDependencies": {
11
- "@opencode-ai/plugin": "*"
12
- },
13
- "devDependencies": {
14
- "@ai-sdk/openai": "3.0.84",
15
- "@opencode-ai/plugin": "1.18.27",
16
- "@types/bun": "1.3.14",
17
- "@types/node": "24.13.3",
18
- "typescript": "5.9.3"
19
- }
20
- }
@@ -1,145 +0,0 @@
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
- }