@weave-os/router 0.2.21 → 0.2.23

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 CHANGED
@@ -7,7 +7,7 @@ published as a compatibility alias and continues to receive the same releases;
7
7
  it prints a migration warning directing users to `@weave-os/router`.
8
8
 
9
9
  ```bash
10
- npx @weave-os/router # interactive: pick Claude Code / Codex / opencode / pi, then scope
10
+ npx @weave-os/router # open the hosted setup page
11
11
  npx @weave-os/router --claude # skip the picker, target Claude Code
12
12
  npx @weave-os/router --codex # skip the picker, target the OpenAI Codex CLI
13
13
  npx @weave-os/router setup --claude --codex # configure both native clients
@@ -21,29 +21,10 @@ npx @weave-os/router --scope project # per-repo install, commit settings.j
21
21
  npx @weave-os/router --local # self-hosted via docker-compose (localhost:8080)
22
22
  npx @weave-os/router --base-url https://router.acme.internal
23
23
  npx @weave-os/router --email you@example.com # set identity without prompting
24
+ npx @weave-os/router --claude --return-url https://app.example.com/onboarding # continue after a verified install
24
25
  npx @weave-os/router --non-interactive # reads $WEAVE_ROUTER_KEY, no prompts (defaults to claude)
25
26
  ```
26
27
 
27
- Re-running the installer to pick up changes reuses the key already on disk, so
28
- you paste it once and never again — for every client, not just Claude Code.
29
- `update` is the never-prompting form of that (safe for cron; errors instead of
30
- asking when no key can be found):
31
-
32
- ```bash
33
- npx @weave-os/router --claude # reuses the installed key
34
- npx @weave-os/router --codex # same for Codex, opencode, and pi
35
- npx @weave-os/router --claude --rotate-key # ignore it and prompt for a new one
36
- npx @weave-os/router update --claude # non-interactive refresh in place
37
- npx @weave-os/router update --claude --context-window 1m # opt into Claude's 1M local context
38
- ```
39
-
40
- Claude Code normally keeps a 200k local context budget when using a custom
41
- router endpoint. The explicit `--context-window 1m` option selects the
42
- supported `[1m]` model variant, preserves automatic compaction, and records
43
- the prior model so `off` or uninstall can restore it. It is opt-in: longer
44
- histories can increase token usage and cost, and the upstream provider still
45
- needs to support the requested context size.
46
-
47
28
  For Claude Code the installed statusline and `/force-model`, `/router-*` slash
48
29
  commands also refresh themselves in the background about once a week (never
49
30
  overwriting a wrapper you edited). Opt out with `WEAVE_STATUSLINE_UPDATE=0`, or
package/bin.js CHANGED
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
- // Thin wrapper that runs install.sh with the user's arguments.
3
- // Bundled install.sh ships with the npm package so `npx @weave-os/router`
4
- // works offline (modulo the router API ping the installer does).
2
+ // Thin wrapper that runs install.sh with the user's arguments. The canonical
3
+ // no-argument command opens the hosted setup page instead.
5
4
 
6
5
  const { spawnSync } = require("node:child_process");
7
6
  const { existsSync, readFileSync } = require("node:fs");
@@ -12,6 +11,13 @@ const packageName = JSON.parse(
12
11
  readFileSync(path.join(__dirname, "package.json"), "utf8"),
13
12
  ).name;
14
13
 
14
+ const defaultEntrypointURL = "https://router.workweave.ai/start";
15
+
16
+ if (packageName === "@weave-os/router" && args.length === 0) {
17
+ openDefaultEntrypoint(defaultEntrypointURL);
18
+ process.exit(0);
19
+ }
20
+
15
21
  if (packageName === "@workweave/router") {
16
22
  console.error(
17
23
  "warning: @workweave/router is deprecated; use @weave-os/router instead (npx @weave-os/router).",
@@ -66,3 +72,15 @@ function pickBash() {
66
72
  }
67
73
  return null;
68
74
  }
75
+
76
+ function openDefaultEntrypoint(url) {
77
+ const opener = process.platform === "darwin"
78
+ ? ["open", [url]]
79
+ : process.platform === "win32"
80
+ ? ["cmd.exe", ["/c", "start", "", url]]
81
+ : ["xdg-open", [url]];
82
+ const result = spawnSync(opener[0], opener[1], { stdio: "ignore" });
83
+ if (result.error || result.status !== 0) {
84
+ console.log(`Open ${url} in your browser to get started.`);
85
+ }
86
+ }
package/cc-statusline.sh CHANGED
@@ -522,6 +522,7 @@ prices='{
522
522
  "gpt-6-astra": 0.01,
523
523
  "grok-4.5": 0.002,
524
524
  "grok-4.6": 0.002,
525
+ "grok-4.7": 0.002,
525
526
  "minimax/minimax-m2.7": 0.0003,
526
527
  "minimax/minimax-m3": 0.0003,
527
528
  "mistralai/mistral-small-2603": 0.0002,
@@ -603,6 +604,7 @@ prices='{
603
604
  "gpt-6-astra": 0.05,
604
605
  "grok-4.5": 0.006,
605
606
  "grok-4.6": 0.006,
607
+ "grok-4.7": 0.006,
606
608
  "minimax/minimax-m2.7": 0.0012,
607
609
  "minimax/minimax-m3": 0.0012,
608
610
  "mistralai/mistral-small-2603": 0.0006,
@@ -684,6 +686,7 @@ prices='{
684
686
  "gpt-6-astra": 0.1,
685
687
  "grok-4.5": 0.25,
686
688
  "grok-4.6": 0.25,
689
+ "grok-4.7": 0.25,
687
690
  "minimax/minimax-m2.7": 0.2,
688
691
  "minimax/minimax-m3": 0.2,
689
692
  "mistralai/mistral-small-2603": 0.1,
package/install.sh CHANGED
@@ -53,8 +53,9 @@
53
53
  # npx @weave-os/router --local # local router on localhost:8080
54
54
  # npx @weave-os/router --base-url http://localhost:8080 # self-hosted, custom port
55
55
  # npx @weave-os/router --email you@example.com # set the router identity email without prompting
56
+ # npx @weave-os/router --return-url https://example.com # open a URL after a verified install
56
57
  # npx @weave-os/router --non-interactive # require WEAVE_ROUTER_KEY env var (defaults target to claude)
57
- # npx @weave-os/router --quiet # suppress banner, ping check, and trailing tips
58
+ # npx @weave-os/router --quiet # suppress banner, ping check, and trailing tips (return-url still verifies)
58
59
  # npx @weave-os/router --rotate-key # ignore the installed key and prompt for a new one
59
60
  # npx @weave-os/router --uninstall # remove a previous install (delegates to uninstall.sh)
60
61
  #
@@ -121,6 +122,7 @@ base_url=""
121
122
  base_url_explicit="false"
122
123
  email=""
123
124
  email_explicit="false"
125
+ return_url=""
124
126
  non_interactive="false"
125
127
  quiet="false"
126
128
  router_key_header="X-Weave-Router-Key"
@@ -164,6 +166,8 @@ rotate_key="false"
164
166
  # Where $api_key came from: env | disk | prompt. Drives the fallback re-prompt
165
167
  # when /validate rejects a key we read back off disk.
166
168
  api_key_source=""
169
+ # Set by verify_install; a return URL is opened only after both probes pass.
170
+ install_verification_succeeded="false"
167
171
 
168
172
  # ---------- helpers ----------
169
173
 
@@ -1178,7 +1182,8 @@ write_pi_models_config() {
1178
1182
  { id: "gpt-6-astra", name: "GPT-6 Astra (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1179
1183
  { id: "gpt-5.6-sol", name: "GPT-5.6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1180
1184
  { id: "grok-4.5", name: "Grok 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 },
1181
- { id: "grok-4.6", name: "Grok 4.6 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 }
1185
+ { id: "grok-4.6", name: "Grok 4.6 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 },
1186
+ { id: "grok-4.7", name: "Grok 4.7 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 }
1182
1187
  ]
1183
1188
  }
1184
1189
  ')"
@@ -1390,6 +1395,14 @@ while [ $# -gt 0 ]; do
1390
1395
  [ -n "$email" ] || { err "--email requires a value."; exit 2; }
1391
1396
  email_explicit="true"
1392
1397
  ;;
1398
+ --return-url)
1399
+ return_url="${2:-}"; shift 2
1400
+ [ -n "$return_url" ] || { err "--return-url requires a value."; exit 2; }
1401
+ case "$return_url" in
1402
+ http://*|https://*) ;;
1403
+ *) err "--return-url must be an http:// or https:// URL."; exit 2 ;;
1404
+ esac
1405
+ ;;
1393
1406
  --local)
1394
1407
  # Shorthand for local dev: localhost:8080 (matches `wv mr` / `make dev` default PORT).
1395
1408
  base_url="http://localhost:8080"
@@ -1503,6 +1516,11 @@ if [ "$mode" = "setup" ]; then
1503
1516
  [ "$non_interactive" = "true" ] && setup_args+=(--non-interactive)
1504
1517
  [ "$base_url_explicit" = "true" ] && setup_args+=(--base-url "$base_url")
1505
1518
  [ "$email_explicit" = "true" ] && setup_args+=(--email "$email")
1519
+ if [ -n "$return_url" ] && [ "$setup_claude" = "true" ] && [ "$setup_codex" = "true" ]; then
1520
+ err "--return-url with setup requires a single target: use setup --claude or setup --codex."
1521
+ exit 2
1522
+ fi
1523
+ [ -n "$return_url" ] && setup_args+=(--return-url "$return_url")
1506
1524
  [ -n "$install_dir" ] && setup_args+=(--dir "$install_dir")
1507
1525
  [ "$quiet" = "true" ] && setup_args+=(--quiet)
1508
1526
  [ "$rotate_key" = "true" ] && setup_args+=(--rotate-key)
@@ -1511,6 +1529,11 @@ if [ "$mode" = "setup" ]; then
1511
1529
  exit 0
1512
1530
  fi
1513
1531
 
1532
+ if [ -n "$return_url" ] && [ "$mode" != "install" ]; then
1533
+ err "--return-url is supported only for install (or setup with one explicit target)."
1534
+ exit 2
1535
+ fi
1536
+
1514
1537
  # --lsp is a pi-extension feature, so it implies the pi target; combining it
1515
1538
  # with another explicit target is a contradiction, not a preference.
1516
1539
  if [ -n "$lsp_langs" ]; then
@@ -2493,7 +2516,7 @@ apply_claude_context_window() {
2493
2516
  local action="$1" active="$2" state="$settings_dir/.weave-context-window.json" merged tmp
2494
2517
  refuse_if_symlink "$state"
2495
2518
  [ -f "$active" ] || return 0
2496
- if [ "$action" = "install" ] && [ -n "$context_window" ]; then
2519
+ if [ -n "$context_window" ]; then
2497
2520
  tmp="$(mktemp "$settings_dir/.weave-context.XXXXXX")"
2498
2521
  jq --arg managed "$context_managed_model" '{had_model: has("model"), original: .model, managed: $managed}' "$active" >"$tmp"
2499
2522
  chmod 600 "$tmp"
@@ -2501,13 +2524,13 @@ apply_claude_context_window() {
2501
2524
  merged="$(jq --arg model "$context_managed_model" '.model = $model' "$active")"
2502
2525
  else
2503
2526
  [ -f "$state" ] || return 0
2504
- merged="$(jq --slurpfile state "$state" --arg action "$action" '
2527
+ merged="$(jq --slurpfile state "$state" --arg action "$action" --arg context_window "$context_window" '
2505
2528
  $state[0] as $s |
2506
2529
  if $action == "off" then
2507
2530
  if .model == $s.managed then
2508
2531
  if $s.had_model then .model = $s.original else del(.model) end
2509
2532
  else . end
2510
- elif has("model") == $s.had_model and .model == $s.original then .model = $s.managed
2533
+ elif ($action == "install" or $action == "on" or $context_window != "") and has("model") == $s.had_model and .model == $s.original then .model = $s.managed
2511
2534
  else . end
2512
2535
  ' "$active")"
2513
2536
  fi
@@ -2515,7 +2538,7 @@ apply_claude_context_window() {
2515
2538
  printf '%s\n' "$merged" >"$tmp"
2516
2539
  chmod 600 "$tmp"
2517
2540
  mv "$tmp" "$active"
2518
- if [ "$action" = "install" ] && [ -n "$context_window" ]; then
2541
+ if [ -n "$context_window" ]; then
2519
2542
  ok "Claude Code model set to $context_managed_model; automatic compaction stays enabled. Restart Claude Code."
2520
2543
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
2521
2544
  gitignore_add ".claude/.weave-context-window.json"
@@ -3158,7 +3181,7 @@ run_accounts() {
3158
3181
  if [ "$models_json" = "true" ]; then
3159
3182
  printf '%s\n' "$models_http_body"
3160
3183
  else
3161
- printf '%s\n' "$models_http_body" | jq -r '.[] | "\(.id)\t\(.provider)\t\(.external_account_id)\t\(if .enabled then "enabled" else "disabled" end)\t\(if .cooldown_until then "cooldown until " + .cooldown_until else "ready" end)"'
3184
+ printf '%s\n' "$models_http_body" | jq -r '.[] | "\(.id)\t\(.provider)\t\(.external_account_id)" + (if (.display_name // "") != "" then "\t" + .display_name else "" end) + "\t" + (if .enabled then "enabled" else "disabled" end) + "\t" + (if .cooldown_until then "cooldown until " + .cooldown_until else "ready" end)'
3162
3185
  fi
3163
3186
  ;;
3164
3187
  disable|remove)
@@ -3184,6 +3207,47 @@ oauth_base64url() {
3184
3207
  openssl base64 -A | tr '+/' '-_' | tr -d '='
3185
3208
  }
3186
3209
 
3210
+ # open_url_in_browser asks the operating system to open a URL with the user's
3211
+ # default browser. Keep this best-effort: a successful install must not be
3212
+ # rolled back just because a headless shell has no browser opener available.
3213
+ open_url_in_browser() {
3214
+ local url="$1" os
3215
+ os="$(uname -s 2>/dev/null || printf '')"
3216
+ case "$os" in
3217
+ Darwin*)
3218
+ command -v open >/dev/null 2>&1 || return 1
3219
+ open "$url" >/dev/null 2>&1
3220
+ ;;
3221
+ MINGW*|MSYS*|CYGWIN*)
3222
+ # explorer.exe is a direct process launch; cmd.exe /c start would parse
3223
+ # URL query separators such as '&' as shell syntax. Its exit status is
3224
+ # not meaningful: an already-running shell commonly returns 1 after
3225
+ # handing the URL off.
3226
+ command -v explorer.exe >/dev/null 2>&1 || return 1
3227
+ explorer.exe "$url" >/dev/null 2>&1 || true
3228
+ return 0
3229
+ ;;
3230
+ *)
3231
+ command -v xdg-open >/dev/null 2>&1 || return 1
3232
+ xdg-open "$url" >/dev/null 2>&1
3233
+ ;;
3234
+ esac
3235
+ }
3236
+
3237
+ open_return_url_if_verified() {
3238
+ [ "$mode" = "install" ] || return 0
3239
+ [ -n "$return_url" ] || return 0
3240
+ if [ "${install_verification_succeeded:-false}" != "true" ]; then
3241
+ warn "Skipping return URL because router verification did not complete successfully."
3242
+ return 0
3243
+ fi
3244
+ if open_url_in_browser "$return_url"; then
3245
+ info "Opened return URL in your browser: $return_url"
3246
+ else
3247
+ warn "Install succeeded, but no default-browser opener was available. Open this URL to continue: $return_url"
3248
+ fi
3249
+ }
3250
+
3187
3251
  open_oauth_url() {
3188
3252
  local url="$1"
3189
3253
  if command -v open >/dev/null 2>&1; then
@@ -3203,6 +3267,24 @@ jwt_account_id() {
3203
3267
  printf '%s' "$decoded" | jq -r '.chatgpt_account_id // .["https://api.openai.com/auth"].chatgpt_account_id // .organizations[0].id // empty' 2>/dev/null || true
3204
3268
  }
3205
3269
 
3270
+ jwt_account_label() {
3271
+ local token="$1" payload padding decoded
3272
+ payload="$(printf '%s' "$token" | cut -d. -f2 | tr '_-' '/+')"
3273
+ padding=$(( (4 - ${#payload} % 4) % 4 ))
3274
+ while [ "$padding" -gt 0 ]; do payload="${payload}="; padding=$((padding - 1)); done
3275
+ decoded="$(printf '%s' "$payload" | base64 --decode 2>/dev/null || printf '%s' "$payload" | base64 -D 2>/dev/null || true)"
3276
+ printf '%s' "$decoded" | jq -r '
3277
+ def clean: if type == "string" then gsub("[[:cntrl:]]"; " ") | gsub("[[:space:]]+"; " ") | sub("^ +"; "") | sub(" +$"; "") else "" end;
3278
+ (.organizations[0].name // .organizations[0].display_name // .organization.name // "" | clean) as $organization |
3279
+ (.email // .email_address // .["https://api.openai.com/profile"].email // .["https://api.openai.com/auth"].email // "" | clean) as $email |
3280
+ (.name // .preferred_username // "" | clean) as $name |
3281
+ if $organization != "" and $email != "" then ($organization + ": " + $email)
3282
+ elif $email != "" then $email
3283
+ elif $organization != "" then $organization
3284
+ else $name end
3285
+ ' 2>/dev/null || true
3286
+ }
3287
+
3206
3288
  # OAuth issuers rate-limit curl's default user agent, which fails the token
3207
3289
  # exchange (and every later refresh) with a 429 before the request is even
3208
3290
  # read, so identify the installer explicitly.
@@ -3231,7 +3313,7 @@ oauth_post_form() {
3231
3313
  }
3232
3314
 
3233
3315
  run_login_claude() {
3234
- local verifier challenge expected_state authorize_endpoint authorize_url pasted_code auth_code returned_state token_response refresh_token external_account_id body
3316
+ local verifier challenge expected_state authorize_endpoint authorize_url pasted_code auth_code returned_state token_response refresh_token account_uuid organization_uuid account_email organization_name display_name external_account_id body
3235
3317
  verifier="$(openssl rand 32 | oauth_base64url)"
3236
3318
  challenge="$(printf '%s' "$verifier" | openssl dgst -sha256 -binary | oauth_base64url)"
3237
3319
  expected_state="$(openssl rand 32 | oauth_base64url)"
@@ -3253,14 +3335,27 @@ run_login_claude() {
3253
3335
  || { err "Claude token exchange failed."; exit 1; }
3254
3336
  refresh_token="$(printf '%s' "$token_response" | jq -r '.refresh_token // empty')"
3255
3337
  [ -n "$refresh_token" ] || { err "Claude token exchange returned no refresh token."; exit 1; }
3256
- external_account_id="claude-$(openssl rand 12 | oauth_base64url)"
3257
- body="$(jq -nc --arg provider claude --arg account "$external_account_id" --arg token "$refresh_token" '{provider:$provider,external_account_id:$account,refresh_token:$token}')"
3338
+ account_uuid="$(printf '%s' "$token_response" | jq -er '.account.uuid | select(type == "string" and test("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")) | ascii_downcase' 2>/dev/null)" \
3339
+ || { err "Claude token exchange returned no valid account UUID; subscription was not enrolled. Update the installer and try again."; exit 1; }
3340
+ organization_uuid="$(printf '%s' "$token_response" | jq -er '.organization.uuid | select(type == "string" and test("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")) | ascii_downcase' 2>/dev/null)" \
3341
+ || { err "Claude token exchange returned no valid organization UUID; subscription was not enrolled. Update the installer and try again."; exit 1; }
3342
+ account_email="$(printf '%s' "$token_response" | jq -r '.account.email_address // .account.email // empty' 2>/dev/null || true)"
3343
+ organization_name="$(printf '%s' "$token_response" | jq -r '.organization.name // .organization.display_name // empty' 2>/dev/null || true)"
3344
+ display_name="$(jq -nr --arg organization "$organization_name" --arg email "$account_email" '
3345
+ def clean: gsub("[[:cntrl:]]"; " ") | gsub("[[:space:]]+"; " ") | sub("^ +"; "") | sub(" +$"; "");
3346
+ ($organization | clean) as $organization | ($email | clean) as $email |
3347
+ if $organization != "" and $email != "" then ($organization + ": " + $email)
3348
+ elif $email != "" then $email
3349
+ else $organization end
3350
+ ')"
3351
+ external_account_id="${account_uuid}:${organization_uuid}"
3352
+ body="$(jq -nc --arg provider claude --arg account "$external_account_id" --arg token "$refresh_token" --arg label "$display_name" '{provider:$provider,external_account_id:$account,refresh_token:$token} | if $label != "" then .display_name = $label else . end')"
3258
3353
  models_api POST "/v1/subscriptions/accounts" "$body" || models_fail "enrolling Claude subscription"
3259
3354
  ok "Claude subscription enrolled."
3260
3355
  }
3261
3356
 
3262
3357
  run_login_codex() {
3263
- local issuer device_response device_auth_id user_code interval authorization_response authorization_code verifier token_response refresh_token account_id body attempts token_form
3358
+ local issuer device_response device_auth_id user_code interval authorization_response authorization_code verifier token_response refresh_token account_id display_name identity_token body attempts token_form
3264
3359
  issuer="${WEAVE_CODEX_OAUTH_ISSUER:-https://auth.openai.com}"
3265
3360
  device_response="$(oauth_post_json "$issuer/api/accounts/deviceauth/usercode" '{"client_id":"app_EMoamEEZ73f0CkXaXp7hrann"}')" \
3266
3361
  || { err "Could not start Codex device authorization."; exit 1; }
@@ -3293,12 +3388,14 @@ run_login_codex() {
3293
3388
  token_response="$(oauth_post_form "$issuer/oauth/token" "$token_form")" \
3294
3389
  || { err "Codex token exchange failed."; exit 1; }
3295
3390
  refresh_token="$(printf '%s' "$token_response" | jq -r '.refresh_token // empty')"
3296
- account_id="$(jwt_account_id "$(printf '%s' "$token_response" | jq -r '.id_token // .access_token // empty')")"
3391
+ identity_token="$(printf '%s' "$token_response" | jq -r '.id_token // .access_token // empty')"
3392
+ account_id="$(jwt_account_id "$identity_token")"
3393
+ display_name="$(jwt_account_label "$identity_token")"
3297
3394
  if [ -z "$refresh_token" ] || [ -z "$account_id" ]; then
3298
3395
  err "Codex token exchange omitted account identity or refresh credentials."
3299
3396
  exit 1
3300
3397
  fi
3301
- body="$(jq -nc --arg provider codex --arg account "$account_id" --arg token "$refresh_token" '{provider:$provider,external_account_id:$account,refresh_token:$token}')"
3398
+ body="$(jq -nc --arg provider codex --arg account "$account_id" --arg token "$refresh_token" --arg label "$display_name" '{provider:$provider,external_account_id:$account,refresh_token:$token} | if $label != "" then .display_name = $label else . end')"
3302
3399
  models_api POST "/v1/subscriptions/accounts" "$body" || models_fail "enrolling Codex subscription"
3303
3400
  ok "Codex subscription enrolled."
3304
3401
  }
@@ -3350,7 +3447,7 @@ run_router_status() {
3350
3447
  if [ "$(printf '%s' "$models_http_body" | jq 'length')" -eq 0 ]; then
3351
3448
  printf ' none enrolled\n'
3352
3449
  else
3353
- printf '%s\n' "$models_http_body" | jq -r '.[] | " " + .provider + " " + .external_account_id + " " + (if .enabled then "enabled" else "disabled" end) + (if .cooldown_until then " cooldown until " + .cooldown_until else " ready" end)'
3450
+ printf '%s\n' "$models_http_body" | jq -r '.[] | " " + .provider + " " + .external_account_id + (if (.display_name // "") != "" then " [" + .display_name + "]" else "" end) + " " + (if .enabled then "enabled" else "disabled" end) + (if .cooldown_until then " cooldown until " + .cooldown_until else " ready" end)'
3354
3451
  fi
3355
3452
  elif [ "$models_http_status" = "404" ]; then
3356
3453
  printf 'Subscription accounts: server-side pools disabled\n'
@@ -3876,15 +3973,25 @@ rewrite_installed_key() {
3876
3973
  }
3877
3974
 
3878
3975
  verify_install() {
3879
- if [ "$quiet" != "true" ]; then
3880
- if ! spin "Pinging $base_url/health" curl -fsS --max-time 5 "$base_url/health"; then
3976
+ local health_verified="false"
3977
+ install_verification_succeeded="false"
3978
+
3979
+ # --quiet normally skips the health probe, but a return URL is only safe to
3980
+ # open after both probes have actually run and passed.
3981
+ if [ "$quiet" != "true" ] || [ -n "$return_url" ]; then
3982
+ if spin "Pinging $base_url/health" curl -fsS --max-time 5 "$base_url/health"; then
3983
+ health_verified="true"
3984
+ else
3881
3985
  warn "Could not reach $base_url/health within 5s. Settings are written; verify the router is running."
3882
3986
  fi
3883
3987
  fi
3884
3988
 
3885
3989
  [ -n "$api_key" ] || return 0
3886
3990
 
3887
- spin "Validating API key" validate_key && return 0
3991
+ if spin "Validating API key" validate_key; then
3992
+ [ "$health_verified" = "true" ] && install_verification_succeeded="true"
3993
+ return 0
3994
+ fi
3888
3995
 
3889
3996
  # A key we read back off disk can have been revoked or rotated since it was
3890
3997
  # installed, and reusing it silently would leave a broken install behind
@@ -3897,7 +4004,9 @@ verify_install() {
3897
4004
  warn "The router key already installed was rejected (revoked or rotated)."
3898
4005
  prompt_for_key
3899
4006
  rewrite_installed_key "$api_key"
3900
- if ! spin "Validating API key" validate_key; then
4007
+ if spin "Validating API key" validate_key; then
4008
+ [ "$health_verified" = "true" ] && install_verification_succeeded="true"
4009
+ else
3901
4010
  warn "Router rejected the API key (check it matches the dashboard at $base_url)."
3902
4011
  fi
3903
4012
  return 0
@@ -3932,6 +4041,7 @@ announce_done() {
3932
4041
  fi
3933
4042
  printf "%s✓%s %s%sWeave Router installed for %s.%s\n" \
3934
4043
  "$C_GREEN" "$C_RESET" "$C_BOLD" "$C_BRAND" "$1" "$C_RESET"
4044
+ open_return_url_if_verified
3935
4045
  }
3936
4046
 
3937
4047
  # ---------- codex install path (dispatch + exit before the Claude-only writes) ----------
@@ -5380,6 +5490,7 @@ prices='{
5380
5490
  "gpt-6-astra": 0.01,
5381
5491
  "grok-4.5": 0.002,
5382
5492
  "grok-4.6": 0.002,
5493
+ "grok-4.7": 0.002,
5383
5494
  "minimax/minimax-m2.7": 0.0003,
5384
5495
  "minimax/minimax-m3": 0.0003,
5385
5496
  "mistralai/mistral-small-2603": 0.0002,
@@ -5461,6 +5572,7 @@ prices='{
5461
5572
  "gpt-6-astra": 0.05,
5462
5573
  "grok-4.5": 0.006,
5463
5574
  "grok-4.6": 0.006,
5575
+ "grok-4.7": 0.006,
5464
5576
  "minimax/minimax-m2.7": 0.0012,
5465
5577
  "minimax/minimax-m3": 0.0012,
5466
5578
  "mistralai/mistral-small-2603": 0.0006,
@@ -5542,6 +5654,7 @@ prices='{
5542
5654
  "gpt-6-astra": 0.1,
5543
5655
  "grok-4.5": 0.25,
5544
5656
  "grok-4.6": 0.25,
5657
+ "grok-4.7": 0.25,
5545
5658
  "minimax/minimax-m2.7": 0.2,
5546
5659
  "minimax/minimax-m3": 0.2,
5547
5660
  "mistralai/mistral-small-2603": 0.1,
@@ -5927,7 +6040,11 @@ write_claude_settings() {
5927
6040
  chmod 600 "$local_settings_file"
5928
6041
  ok "Router key header written to $local_settings_file"
5929
6042
  fi
5930
- apply_claude_context_window install "$context_settings_file"
6043
+ context_window_action="install"
6044
+ if [ "$mode" = "update" ] && [ ! -f "$settings_dir/.weave-parked.json" ]; then
6045
+ context_window_action="update"
6046
+ fi
6047
+ apply_claude_context_window "$context_window_action" "$context_settings_file"
5931
6048
  }
5932
6049
 
5933
6050
  # write_claude_settings rewrites the full router config live, so a parked
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weave-os/router",
3
- "version": "0.2.21",
3
+ "version": "0.2.23",
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",
@@ -0,0 +1,119 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { VERSION, type ExtensionAPI, type ExtensionContext } from "@mariozechner/pi-coding-agent";
3
+ import { getRole, getRouterBaseUrl, PROVIDER_NAME, providerHeaders, resolveRouterKey } from "./config.js";
4
+
5
+ const ENTRY_TYPE = "weave-classifier-thread";
6
+ const THREAD_FIELD = "weave_classifier_thread";
7
+
8
+ interface ClassifierThread {
9
+ sessionId: string;
10
+ routerOrigin: string;
11
+ newChatId: string;
12
+ threadToken?: string;
13
+ }
14
+
15
+ function isRecord(value: unknown): value is Record<string, unknown> {
16
+ return value !== null && typeof value === "object" && !Array.isArray(value);
17
+ }
18
+
19
+ function notify(ctx: ExtensionContext, message: string) {
20
+ if (ctx.hasUI) ctx.ui.notify(message, "error");
21
+ else process.stderr.write(`${message}\n`);
22
+ }
23
+
24
+ /** Enroll only explicit new sessions; a persisted attempt cannot silently become legacy traffic. */
25
+ export function registerClassifierThread(pi: ExtensionAPI, request: typeof fetch = fetch, version = VERSION): () => boolean {
26
+ let thread: ClassifierThread | undefined;
27
+ let pending: Promise<void> | undefined;
28
+ let generation = 0;
29
+ const [major, minor] = version.split(".").map(Number);
30
+ const supported = major > 0 || (major === 0 && minor >= 83);
31
+
32
+ const restore = (ctx: ExtensionContext) => {
33
+ generation++;
34
+ pending = undefined;
35
+ thread = undefined;
36
+ // All entries, not just the active branch: tree navigation must not erase enrollment.
37
+ for (const entry of ctx.sessionManager.getEntries()) {
38
+ if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE || !isRecord(entry.data)) continue;
39
+ const saved = entry.data;
40
+ if (saved.sessionId !== ctx.sessionManager.getSessionId()) continue;
41
+ if (typeof saved.routerOrigin !== "string" || typeof saved.newChatId !== "string" ||
42
+ (saved.threadToken !== undefined && typeof saved.threadToken !== "string")) {
43
+ thread = { sessionId: ctx.sessionManager.getSessionId(), routerOrigin: "", newChatId: "" };
44
+ return;
45
+ }
46
+ thread = { sessionId: saved.sessionId, routerOrigin: saved.routerOrigin, newChatId: saved.newChatId, threadToken: saved.threadToken };
47
+ }
48
+ };
49
+
50
+ const ensureTicket = async (ctx: ExtensionContext) => {
51
+ if (!thread) return;
52
+ if (thread.sessionId !== ctx.sessionManager.getSessionId() || thread.routerOrigin !== getRouterBaseUrl()) {
53
+ throw new Error("Classifier session or router changed; start a new chat");
54
+ }
55
+ if (thread.threadToken) return;
56
+ if (pending) return pending;
57
+ const enrollment = thread;
58
+ const requestGeneration = generation;
59
+ pending = (async () => {
60
+ const routerKey = resolveRouterKey();
61
+ if (!routerKey) throw new Error("Router key is missing");
62
+ const signals = [AbortSignal.timeout(10_000)];
63
+ if (ctx.signal) signals.push(ctx.signal);
64
+ const response = await request(`${enrollment.routerOrigin}/v1/router/threads`, {
65
+ method: "POST", redirect: "error",
66
+ headers: { ...providerHeaders(getRole(), routerKey), "content-type": "application/json" },
67
+ body: JSON.stringify({ new_chat_id: enrollment.newChatId }), signal: AbortSignal.any(signals),
68
+ });
69
+ if (!response.ok) throw new Error(`Classifier enrollment returned HTTP ${response.status}`);
70
+ const ticket: unknown = await response.json();
71
+ if (!isRecord(ticket) || typeof ticket.thread_token !== "string" || !ticket.thread_token || ticket.thread_token.length > 4096) {
72
+ throw new Error("Invalid classifier enrollment response");
73
+ }
74
+ if (generation !== requestGeneration || ctx.signal?.aborted) throw new Error("Session changed during classifier enrollment");
75
+ enrollment.threadToken = ticket.thread_token;
76
+ pi.appendEntry(ENTRY_TYPE, { ...enrollment });
77
+ })();
78
+ try { await pending; } finally { if (generation === requestGeneration) pending = undefined; }
79
+ };
80
+
81
+ pi.on("session_start", async (event, ctx) => {
82
+ restore(ctx);
83
+ if (!thread && process.env.WEAVE_PI_LLM_CLASSIFIER === "1" && supported &&
84
+ ctx.model?.provider === PROVIDER_NAME && (event.reason === "new" || event.reason === "startup") &&
85
+ !ctx.sessionManager.getHeader()?.parentSession &&
86
+ !ctx.sessionManager.getEntries().some(entry => entry.type === "message" || entry.type === "compaction" || entry.type === "branch_summary")) {
87
+ thread = { sessionId: ctx.sessionManager.getSessionId(), routerOrigin: getRouterBaseUrl(), newChatId: randomUUID() };
88
+ // Persist before I/O so a crash/retry cannot create another server thread.
89
+ pi.appendEntry(ENTRY_TYPE, { ...thread });
90
+ }
91
+ try { await ensureTicket(ctx); } catch {
92
+ notify(ctx, "Classifier enrollment failed. The next request will retry the same enrollment; it will not switch strategies.");
93
+ }
94
+ });
95
+ pi.on("session_tree", (_event, ctx) => restore(ctx));
96
+ pi.on("session_shutdown", () => { generation++; pending = undefined; thread = undefined; });
97
+ pi.on("before_provider_request", async (event, ctx) => {
98
+ if (!thread) return;
99
+ const requestGeneration = generation;
100
+ try {
101
+ if (!supported || ctx.model?.provider !== PROVIDER_NAME || !isRecord(event.payload)) {
102
+ throw new Error("Classifier thread requires the supported Weave provider");
103
+ }
104
+ await ensureTicket(ctx);
105
+ if (generation !== requestGeneration || !thread?.threadToken || ctx.signal?.aborted) throw new Error("Classifier thread changed");
106
+ return { ...event.payload, [THREAD_FIELD]: thread.threadToken };
107
+ } catch {
108
+ // Pi catches extension exceptions; only abort prevents an unticketed dispatch.
109
+ ctx.abort();
110
+ notify(ctx, "Classifier request stopped: enrollment or session identity is unavailable. No fallback request was sent.");
111
+ }
112
+ });
113
+ pi.on("session_before_compact", (_event, ctx) => {
114
+ if (!thread) return;
115
+ notify(ctx, "Classifier chats require complete history. Compaction is unavailable; start a new chat.");
116
+ return { cancel: true };
117
+ });
118
+ return () => thread !== undefined;
119
+ }
@@ -235,6 +235,7 @@ export const WEAVE_MODELS: ProviderModelConfig[] = [
235
235
  model("claude-sonnet-4-6", "Claude Sonnet 4.6 (via Weave Router)", 64000, 1_000_000),
236
236
  model("claude-haiku-4-5", "Claude Haiku 4.5 (via Weave Router)", 32000, 200_000),
237
237
  model("grok-4.6", "Grok 4.6 (via Weave Router)", 131072, 500_000),
238
+ model("grok-4.7", "Grok 4.7 (via Weave Router)", 131072, 500_000),
238
239
  model("qwen/qwen3.8-max", "Qwen 3.8 Max (via Weave Router)", 131072, 1_000_000),
239
240
  ];
240
241
 
@@ -79,6 +79,7 @@ export function registerEscalationCompaction(
79
79
  pi: ExtensionAPI,
80
80
  request: typeof fetch = fetch,
81
81
  version: string = VERSION,
82
+ classifierThreadActive = () => false,
82
83
  ): () => boolean {
83
84
  const [major, minor] = version.split(".").map(Number);
84
85
  if (major === 0 && minor < 83) {
@@ -142,6 +143,7 @@ export function registerEscalationCompaction(
142
143
  };
143
144
 
144
145
  pi.on("before_provider_request", async (event, ctx) => {
146
+ if (classifierThreadActive()) return;
145
147
  if (process.env.WEAVE_PI_ESCALATION_COMPACTION === "0" || isSubagent() || ctx.model?.provider !== PROVIDER_NAME) return;
146
148
  if (!isRecord(event.payload)) return;
147
149
  let payload = sessionToken ? { ...event.payload, weave_session: sessionToken } : event.payload;
@@ -22,6 +22,7 @@
22
22
  import { fileURLToPath } from "node:url";
23
23
  import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
24
24
  import { registerBetaCommand } from "./beta.js";
25
+ import { registerClassifierThread } from "./classifier-thread.js";
25
26
  import { isSubagent } from "./config.js";
26
27
  import { registerCompaction } from "./compaction.js";
27
28
  import { registerEscalationCompaction } from "./escalation.js";
@@ -44,13 +45,14 @@ export default function (pi: ExtensionAPI): void {
44
45
  pi.on("session_start", () => registerWeave(pi));
45
46
 
46
47
  registerMetadata(pi);
48
+ const classifierThreadActive = registerClassifierThread(pi);
47
49
  registerBetaCommand(pi);
48
50
  registerForceModelCommands(pi);
49
51
  registerRoutedModel(pi);
50
52
  if (!isSubagent()) registerWooly(pi);
51
53
  let handoffPending = () => false;
52
- registerCompaction(pi, undefined, () => handoffPending());
53
- handoffPending = registerEscalationCompaction(pi);
54
+ registerCompaction(pi, undefined, () => handoffPending() || classifierThreadActive());
55
+ handoffPending = registerEscalationCompaction(pi, undefined, undefined, classifierThreadActive);
54
56
 
55
57
  if (process.env.WEAVE_NO_SAFETY !== "1") registerSafety(pi);
56
58
 
@@ -7,7 +7,7 @@ export interface ModelPricing {
7
7
  cacheReadMultiplier: number;
8
8
  }
9
9
 
10
- export const PRICING_VERSION = "catalog-sha256:a96c21de7b4ad8ef";
10
+ export const PRICING_VERSION = "catalog-sha256:d1898e95669c5daf";
11
11
 
12
12
  export const MODEL_PRICING: Readonly<Record<string, ModelPricing>> = Object.freeze({
13
13
  "claude-fable-5": { inputUsdPerMillion: 10, outputUsdPerMillion: 50, cacheReadMultiplier: 0.1 },
@@ -66,6 +66,7 @@ export const MODEL_PRICING: Readonly<Record<string, ModelPricing>> = Object.free
66
66
  "gpt-6-astra": { inputUsdPerMillion: 10, outputUsdPerMillion: 50, cacheReadMultiplier: 0.1 },
67
67
  "grok-4.5": { inputUsdPerMillion: 2, outputUsdPerMillion: 6, cacheReadMultiplier: 0.25 },
68
68
  "grok-4.6": { inputUsdPerMillion: 2, outputUsdPerMillion: 6, cacheReadMultiplier: 0.25 },
69
+ "grok-4.7": { inputUsdPerMillion: 2, outputUsdPerMillion: 6, cacheReadMultiplier: 0.25 },
69
70
  "minimax/minimax-m2.7": { inputUsdPerMillion: 0.3, outputUsdPerMillion: 1.2, cacheReadMultiplier: 0.2 },
70
71
  "minimax/minimax-m3": { inputUsdPerMillion: 0.3, outputUsdPerMillion: 1.2, cacheReadMultiplier: 0.2 },
71
72
  "mistralai/mistral-small-2603": { inputUsdPerMillion: 0.2, outputUsdPerMillion: 0.6, cacheReadMultiplier: 0.1 },