@weave-os/router 0.2.28 → 0.2.30

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/install.sh CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bash
2
2
  #
3
- # Weave Router installer for Claude Code, Codex, opencode, and pi.
3
+ # Weave Router installer for Claude Code, Codex, opencode, pi, and GitHub Copilot CLI.
4
4
  #
5
5
  # Configures Claude Code (default), the OpenAI Codex CLI (`--codex`),
6
6
  # opencode (`--opencode`), or pi (`--pi`) to permanently route through the
@@ -36,16 +36,18 @@
36
36
  # <dir>/.pi/ (run: PI_CODING_AGENT_DIR=<dir>/.pi pi) (with --pi)
37
37
  #
38
38
  # Usage:
39
- # npx @weave-os/router # interactive picker (Claude Code, Codex, opencode)
40
- # npx @weave-os/router --claude # skip the picker, target Claude Code
41
- # npx @weave-os/router --codex # skip the picker, target Codex
39
+ # npx @weave-os/router # open the hosted setup page to get a key
40
+ # npx @weave-os/router --claude # install for Claude Code
41
+ # npx @weave-os/router --codex # install for Codex
42
42
  # npx @weave-os/router setup --claude --codex # configure both native clients
43
43
  # npx @weave-os/router login claude # enroll Claude Pro/Max
44
44
  # npx @weave-os/router login codex # enroll ChatGPT Pro/Plus
45
45
  # npx @weave-os/router accounts list # inspect enrolled accounts
46
46
  # npx @weave-os/router status # router + native client status
47
- # npx @weave-os/router --opencode # skip the picker, target opencode
48
- # npx @weave-os/router --pi # skip the picker, target pi
47
+ # npx @weave-os/router --opencode # install for opencode
48
+ # npx @weave-os/router --pi # install for pi
49
+ # npx @weave-os/router --copilot # add Weave Router to GitHub Copilot CLI's /model picker
50
+ # npx @weave-os/router --copilot --wire openai # same, over the OpenAI Responses API
49
51
  # npx @weave-os/router --pi --lsp go,typescript # also install language servers for pi's lsp tool
50
52
  # (go/typescript/python/rust; needs that language's toolchain)
51
53
  # npx @weave-os/router --scope project # commit-with-team install
@@ -53,9 +55,10 @@
53
55
  # npx @weave-os/router --local # local router on localhost:8080
54
56
  # npx @weave-os/router --base-url http://localhost:8080 # self-hosted, custom port
55
57
  # 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
58
+ # npx @weave-os/router --return-url https://example.com # open a URL after a verified install (or WEAVE_ROUTER_RETURN_URL)
57
59
  # npx @weave-os/router --non-interactive # require WEAVE_ROUTER_KEY env var (defaults target to claude)
58
60
  # npx @weave-os/router --quiet # suppress banner, ping check, and trailing tips (return-url still verifies)
61
+ # npx @weave-os/router --claude --no-attribution # don't credit Weave Router in Claude Code commits/PRs (kept on reinstall)
59
62
  # npx @weave-os/router --rotate-key # ignore the installed key and prompt for a new one
60
63
  # npx @weave-os/router --uninstall # remove a previous install (delegates to uninstall.sh)
61
64
  #
@@ -89,7 +92,8 @@
89
92
  # the same lists the router dashboard's settings page renders. The endpoint and
90
93
  # router key both come from the install already on disk, so nothing is prompted
91
94
  # and no key is ever passed on the command line:
92
- # npx @weave-os/router models --claude # every model, with its on/off state
95
+ # npx @weave-os/router models # every model, for the installed client
96
+ # npx @weave-os/router models --claude # same, for one client
93
97
  # npx @weave-os/router models disable gpt-5.6 --claude # take a model out of rotation
94
98
  # npx @weave-os/router models enable gpt-5.6 --claude # put it back
95
99
  # npx @weave-os/router models providers --claude # same, one row per provider
@@ -102,6 +106,7 @@
102
106
  # it rather than editing.
103
107
 
104
108
  set -euo pipefail
109
+ export PATH="$PATH:$HOME/.weave/bin"
105
110
 
106
111
  # ---------- defaults ----------
107
112
 
@@ -125,6 +130,7 @@ email_explicit="false"
125
130
  return_url=""
126
131
  non_interactive="false"
127
132
  quiet="false"
133
+ attribution="true"
128
134
  router_key_header="X-Weave-Router-Key"
129
135
  # Target tool whose config we patch. "claude" (default) writes Claude Code
130
136
  # settings.json; "codex" writes ~/.codex/config.toml; "opencode" merges a
@@ -136,6 +142,10 @@ router_key_header="X-Weave-Router-Key"
136
142
  # prompt for the choice.
137
143
  target="claude"
138
144
  target_explicit="false"
145
+ # Wire format the Copilot CLI provider speaks to the router: anthropic
146
+ # (/v1/messages) or openai (/v1/responses).
147
+ copilot_wire="anthropic"
148
+ copilot_wire_explicit="false"
139
149
 
140
150
  # Operation mode. "install" (default) writes/refreshes config. "update" is a
141
151
  # never-prompting install that reuses the key already on disk. "off"/"on"/
@@ -154,6 +164,7 @@ setup_codex="false"
154
164
  # `set -u` would not. --json switches the output to the raw API payload.
155
165
  models_args=""
156
166
  models_json="false"
167
+ models_auto_target="false"
157
168
 
158
169
  # --lsp <langs>: comma-separated languages whose language servers to install
159
170
  # for the pi extension's `lsp` tool (pi target only). Empty = don't install any.
@@ -167,6 +178,11 @@ rotate_key="false"
167
178
  api_key_source=""
168
179
  # Set by verify_install; a return URL is opened only after both probes pass.
169
180
  install_verification_succeeded="false"
181
+ # Set by verify_install: valid | rejected | unverified (router unreachable),
182
+ # or empty when there was no key to check.
183
+ key_verdict=""
184
+ # Holds the HTTP status of the last /validate probe ("000" when unreachable).
185
+ validate_status_file=""
170
186
 
171
187
  # ---------- helpers ----------
172
188
 
@@ -214,6 +230,7 @@ uninstall_cmd() {
214
230
  codex) cmd="$cmd --codex" ;;
215
231
  opencode) cmd="$cmd --opencode" ;;
216
232
  pi) cmd="$cmd --pi" ;;
233
+ copilot) cmd="$cmd --copilot" ;;
217
234
  esac
218
235
  [ "$scope" = "project" ] && cmd="$cmd --scope project"
219
236
  [ -n "$install_dir" ] && cmd="$cmd --dir $(printf '%q' "$install_dir")"
@@ -228,6 +245,25 @@ print_uninstall_hint() {
228
245
  "$C_BOLD" "$C_RESET" "$C_CYAN" "$(uninstall_cmd)" "$C_RESET"
229
246
  }
230
247
 
248
+ # offer_launch asks to start the client named in $1 (command in the remaining
249
+ # args) so a working interactive install ends in the product. The client runs
250
+ # as a child, not via exec, so the EXIT trap still removes the temp files.
251
+ offer_launch() {
252
+ local label="$1"; shift
253
+ [ "${WEAVE_SETUP_DEFER_LAUNCH:-}" != "1" ] && [ "$non_interactive" = "false" ] && [ "$quiet" != "true" ] \
254
+ && [ -t 0 ] && [ -t 1 ] && command -v "${!#}" >/dev/null 2>&1 || return 0
255
+ local answer=""
256
+ printf "\n%sStart %s now?%s [Y/n] " "$C_BOLD" "$label" "$C_RESET" >/dev/tty
257
+ read -r answer </dev/tty || answer="n"
258
+ case "$answer" in
259
+ ""|y|Y|yes|Yes) ;;
260
+ *) return 0 ;;
261
+ esac
262
+ local launch_status=0
263
+ "$@" </dev/tty || launch_status=$?
264
+ exit "$launch_status"
265
+ }
266
+
231
267
  # ---------- banner ----------
232
268
  #
233
269
  # Print the WEAVE wordmark in brand orange. Skipped under --quiet or when
@@ -240,6 +276,7 @@ print_banner() {
240
276
  codex) target_label="Codex installer" ;;
241
277
  opencode) target_label="opencode installer" ;;
242
278
  pi) target_label="pi installer" ;;
279
+ copilot) target_label="GitHub Copilot CLI installer" ;;
243
280
  *) target_label="Claude Code installer" ;;
244
281
  esac
245
282
  printf '\n'
@@ -263,6 +300,7 @@ SPIN_FRAMES='⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏'
263
300
  SPIN_INTERVAL=0.08
264
301
  spin_pid=""
265
302
  spin_log=""
303
+ jq_download_tmp=""
266
304
 
267
305
  _spin_cleanup() {
268
306
  # Kill any active spinner child and restore the cursor. Called from the
@@ -273,12 +311,19 @@ _spin_cleanup() {
273
311
  wait "$spin_pid" 2>/dev/null || true
274
312
  fi
275
313
  spin_pid=""
314
+ if [ -n "$jq_download_tmp" ]; then
315
+ rm -f "$jq_download_tmp" 2>/dev/null || true
316
+ jq_download_tmp=""
317
+ fi
276
318
  if [ "$tty_out" = "true" ]; then
277
319
  printf '\033[?25h' # show cursor
278
320
  fi
279
321
  if [ -n "$spin_log" ]; then
280
322
  rm -f "$spin_log" 2>/dev/null || true
281
323
  fi
324
+ if [ -n "${validate_status_file:-}" ]; then
325
+ rm -f "$validate_status_file" 2>/dev/null || true
326
+ fi
282
327
  # Also restore stty echo in case we died mid-keypaste prompt. macOS
283
328
  # `[ -r /dev/tty ]` returns true even when the underlying device errors
284
329
  # on open (ENXIO "Device not configured") under `curl | sh` and CI, so
@@ -342,16 +387,82 @@ spin() {
342
387
  fi
343
388
  }
344
389
 
390
+ # usage is the short, task-grouped help. The comment block at the top of this
391
+ # file is the full reference.
345
392
  usage() {
346
- # Print the leading comment block (lines 2..just-before `set -euo`), stripping
347
- # the leading `# `. awk avoids GNU `head -n -<N>`, which BSD head on macOS
348
- # rejects with "illegal line count -- -N". Banner sits above so `--help`
349
- # gets the same wordmark as a fresh install run.
350
393
  print_banner
351
- awk 'NR<2 { next } /^set -euo/ { exit } { sub(/^# ?/, ""); print }' "$0"
394
+ local npx="npx $npm_package_name"
395
+ cat <<USAGE
396
+ Set up
397
+ $npx open the setup page to get a key
398
+ $npx --claude | --codex install for Claude Code or Codex
399
+ $npx setup --claude --codex install for both (one key prompt)
400
+ $npx --opencode | --pi install for opencode or pi
401
+ $npx --copilot add Weave Router to Copilot CLI's /model picker
402
+
403
+ Every day
404
+ $npx status is each tool routed, signed in, working?
405
+ $npx off --claude go direct to Anthropic (on --claude to undo)
406
+ $npx models which models the router can pick
407
+ $npx update --claude refresh an install without prompting
408
+
409
+ Accounts
410
+ $npx login claude | codex use your Claude or ChatGPT subscription
411
+ $npx accounts list show enrolled subscriptions
412
+
413
+ Options
414
+ --scope project | --dir <path> install for a repo or a throwaway dir
415
+ --base-url <url> | --local self-hosted or local router
416
+ --rotate-key replace the saved key
417
+ --no-attribution don't credit Weave Router in commits
418
+ --uninstall remove the router from every tool
419
+
420
+ Full reference: https://github.com/weave-os/router/blob/main/install/README.md
421
+ USAGE
352
422
  exit "${1:-0}"
353
423
  }
354
424
 
425
+ ensure_jq() {
426
+ command -v jq >/dev/null 2>&1 && return 0
427
+ local asset checksum destination temporary actual_checksum
428
+ case "$(uname -s):$(uname -m)" in
429
+ Darwin:arm64) asset=jq-macos-arm64; checksum=a9fe3ea2f86dfc72f6728417521ec9067b343277152b114f4e98d8cb0e263603 ;;
430
+ Darwin:x86_64) asset=jq-macos-amd64; checksum=e80dbe0d2a2597e3c11c404f03337b981d74b4a8504b70586c354b7697a7c27f ;;
431
+ Linux:x86_64) asset=jq-linux-amd64; checksum=020468de7539ce70ef1bceaf7cde2e8c4f2ca6c3afb84642aabc5c97d9fc2a0d ;;
432
+ Linux:aarch64|Linux:arm64) asset=jq-linux-arm64; checksum=6bc62f25981328edd3cfcfe6fe51b073f2d7e7710d7ef7fcdac28d4e384fc3d4 ;;
433
+ MINGW*:x86_64|MSYS*:x86_64|CYGWIN*:x86_64) asset=jq-windows-amd64.exe; checksum=23cb60a1354eed6bcc8d9b9735e8c7b388cd1fdcb75726b93bc299ef22dd9334 ;;
434
+ *) err "Automatic jq installation is unavailable for $(uname -s)/$(uname -m). Install jq and retry."; exit 1 ;;
435
+ esac
436
+ require_cmd curl "curl is required to download jq."
437
+ destination="$HOME/.weave/bin"
438
+ mkdir -p "$destination"
439
+ temporary="$(mktemp "$destination/.jq.XXXXXX")"
440
+ jq_download_tmp="$temporary"
441
+ info "Downloading jq 1.8.1 ($asset)."
442
+ if ! curl --fail --location --silent --show-error --connect-timeout 15 --max-time 120 \
443
+ "https://github.com/jqlang/jq/releases/download/jq-1.8.1/$asset" -o "$temporary"; then
444
+ err "Could not download jq. Check access to github.com or install jq and retry."
445
+ exit 1
446
+ fi
447
+ if command -v sha256sum >/dev/null 2>&1; then
448
+ actual_checksum="$(sha256sum "$temporary" | awk '{print $1}')"
449
+ else
450
+ require_cmd shasum "shasum or sha256sum is required to verify jq."
451
+ actual_checksum="$(shasum -a 256 "$temporary" | awk '{print $1}')"
452
+ fi
453
+ if [ "$actual_checksum" != "$checksum" ]; then
454
+ err "Downloaded jq failed checksum verification. Retry or install jq manually."
455
+ exit 1
456
+ fi
457
+ chmod 755 "$temporary"
458
+ case "$asset" in
459
+ *.exe) mv -f "$temporary" "$destination/jq.exe" ;;
460
+ *) mv -f "$temporary" "$destination/jq" ;;
461
+ esac
462
+ jq_download_tmp=""
463
+ jq --version >/dev/null
464
+ }
465
+
355
466
  require_cmd() {
356
467
  local cmd="$1" hint="$2"
357
468
  if ! command -v "$cmd" >/dev/null 2>&1; then
@@ -407,6 +518,17 @@ claude_statusline_configured() {
407
518
  jq -e 'has("statusLine") and (.statusLine != null)' "$settings_path" >/dev/null 2>&1
408
519
  }
409
520
 
521
+ # Git Bash rewrites $HOME's /c/... form to C:/... in arguments to native
522
+ # executables such as jq.exe, so the stored command can use either form.
523
+ statusline_commands_match() {
524
+ local first_mixed second_mixed
525
+ [ "$1" = "$2" ] && return 0
526
+ command -v cygpath >/dev/null 2>&1 || return 1
527
+ first_mixed="$(cygpath -m -- "$1" 2>/dev/null)" && [ -n "$first_mixed" ] || return 1
528
+ second_mixed="$(cygpath -m -- "$2" 2>/dev/null)" && [ -n "$second_mixed" ] || return 1
529
+ [ "$first_mixed" = "$second_mixed" ]
530
+ }
531
+
410
532
  # claude_statusline_router_owned reports whether a settings entry points at the
411
533
  # router's statusline. Existing scripts prove ownership with the marker; when a
412
534
  # script is missing, the adjacent ownership marker proves that the router wrote
@@ -415,7 +537,7 @@ claude_statusline_router_owned() {
415
537
  local settings_path="$1" expected_command="$2" script_path="$3" ownership_marker_path="$4" configured_command
416
538
  [ -f "$settings_path" ] || return 1
417
539
  configured_command="$(jq -r '.statusLine.command // empty' "$settings_path" 2>/dev/null || true)"
418
- [ "$configured_command" = "$expected_command" ] || return 1
540
+ statusline_commands_match "$configured_command" "$expected_command" || return 1
419
541
  if [ -f "$script_path" ]; then
420
542
  if grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$script_path" 2>/dev/null; then
421
543
  return 0
@@ -508,6 +630,10 @@ resolve_user_email() {
508
630
  printf '%s' "$candidate"
509
631
  return
510
632
  fi
633
+ if [ "${WEAVE_SETUP_IDENTITY_RESOLVED:-}" = "1" ]; then
634
+ normalize_email "${WEAVE_SETUP_SHARED_EMAIL:-}"
635
+ return
636
+ fi
511
637
  if [ -n "${WEAVE_USER_EMAIL:-}" ]; then
512
638
  candidate="$(normalize_email "$WEAVE_USER_EMAIL")"
513
639
  if [ -z "$candidate" ]; then
@@ -867,10 +993,20 @@ TOML
867
993
  type = "command"
868
994
  command = "${esc_status}"
869
995
 
996
+ [[hooks.UserPromptSubmit]]
997
+ [[hooks.UserPromptSubmit.hooks]]
998
+ type = "command"
999
+ command = "${esc_status}"
1000
+
870
1001
  [[hooks.Stop]]
871
1002
  [[hooks.Stop.hooks]]
872
1003
  type = "command"
873
1004
  command = "${esc_status}"
1005
+
1006
+ [[hooks.PreCompact]]
1007
+ [[hooks.PreCompact.hooks]]
1008
+ type = "command"
1009
+ command = "${esc_status}"
874
1010
  TOML
875
1011
  )${directive_hook_block}"
876
1012
  if [ "${WEAVE_CAPTURE_LLM_CLASSIFIER:-}" = "1" ]; then
@@ -882,10 +1018,6 @@ matcher = "spawn_agent"
882
1018
  type = "command"
883
1019
  command = "${esc_status}"
884
1020
 
885
- [[hooks.PreCompact]]
886
- [[hooks.PreCompact.hooks]]
887
- type = "command"
888
- command = "${esc_status}"
889
1021
  TOML
890
1022
  )"
891
1023
  fi
@@ -1232,9 +1364,12 @@ write_pi_models_config() {
1232
1364
  { id: "claude-sonnet-5-5", name: "Claude Sonnet 5.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 128000 },
1233
1365
  { id: "claude-opus-4-7", name: "Claude Opus 4.7 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 64000 },
1234
1366
  { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 64000 },
1367
+ { id: "claude-haiku-5-5", name: "Claude Haiku 5.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 128000 },
1235
1368
  { id: "claude-haiku-4-5", name: "Claude Haiku 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 200000, maxTokens: 32000 },
1236
1369
  { id: "gpt-6-astra", name: "GPT-6 Astra (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1237
1370
  { id: "gpt-6-sol", name: "GPT-6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1371
+ { id: "gpt-6.1-sol", name: "GPT-6.1 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1372
+ { id: "gpt-6.1-terra", name: "GPT-6.1 Terra (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1238
1373
  { id: "gpt-6-luna", name: "GPT-6 Luna (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1239
1374
  { id: "gpt-5.6-sol", name: "GPT-5.6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1240
1375
  { id: "grok-4.5", name: "Grok 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 },
@@ -1377,6 +1512,146 @@ resolve_user_name() {
1377
1512
  printf '%s' "$candidate"
1378
1513
  }
1379
1514
 
1515
+ # write_copilot_providers merges a managed `weave` provider and its `weave/auto`
1516
+ # model into GitHub Copilot CLI's providers.json. Copilot lists providers.json
1517
+ # models in /model next to the GitHub-hosted ones, so nothing replaces
1518
+ # Copilot's own endpoint (unlike COPILOT_PROVIDER_BASE_URL, which switches the
1519
+ # whole CLI into single-provider BYOK mode). Other providers and models are kept.
1520
+ # The router authenticates off X-Weave-Router-Key, so no apiKey is set: Copilot
1521
+ # would forward it as x-api-key / Authorization, which the router reads as BYOK.
1522
+ # chmod 600 — the headers hold the key.
1523
+ #
1524
+ # Usage: write_copilot_providers <providers_file> <base_url> <api_key> [user_email] [user_name]
1525
+ write_copilot_providers() {
1526
+ local config_file="$1" block_url="$2" block_key="$3" block_email="${4:-}" block_name="${5:-}"
1527
+ local provider model merged
1528
+ provider="$(jq -n \
1529
+ --arg url "$block_url" \
1530
+ --arg wire "$copilot_wire" \
1531
+ --arg key "$block_key" \
1532
+ --arg email "$block_email" \
1533
+ --arg name "$block_name" '
1534
+ {
1535
+ name: "weave",
1536
+ headers: (
1537
+ {"X-Weave-Router-Key": $key, "X-App": "copilot"}
1538
+ | (if $email != "" then . + {"X-Weave-User-Email": $email} else . end)
1539
+ | (if $name != "" then . + {"X-Weave-User-Name": $name } else . end)
1540
+ )
1541
+ }
1542
+ + (if $wire == "openai"
1543
+ then {type: "openai", baseUrl: ($url + "/v1"), wireApi: "responses"}
1544
+ else {type: "anthropic", baseUrl: $url} end)
1545
+ ')"
1546
+ # modelId names a well-known Copilot model so the CLI applies its tool-use
1547
+ # and prompting defaults; the router still picks the real model every turn.
1548
+ model="$(jq -n --arg wire "$copilot_wire" '
1549
+ {
1550
+ id: "auto",
1551
+ provider: "weave",
1552
+ name: "Weave Router",
1553
+ modelId: (if $wire == "openai" then "gpt-5.4" else "claude-sonnet-4" end),
1554
+ maxPromptTokens: 400000,
1555
+ maxOutputTokens: 32000
1556
+ }
1557
+ ')"
1558
+ if [ -f "$config_file" ]; then
1559
+ merged="$(jq --argjson provider "$provider" --argjson model "$model" '
1560
+ .providers = ([(.providers // [])[] | select(.name != "weave")] + [$provider])
1561
+ | .models = ([(.models // [])[] | select(.provider != "weave")] + [$model])
1562
+ ' "$config_file")"
1563
+ else
1564
+ merged="$(jq -n --argjson provider "$provider" --argjson model "$model" \
1565
+ '{providers: [$provider], models: [$model]}')"
1566
+ fi
1567
+ (umask 077 && printf '%s\n' "$merged" >"$config_file")
1568
+ chmod 600 "$config_file"
1569
+ }
1570
+
1571
+ # set_copilot_default_model makes weave/auto Copilot's default model and parks
1572
+ # whatever default was there before, so off/uninstall can put it back.
1573
+ set_copilot_default_model() {
1574
+ local current="" direct="" merged
1575
+ if [ -f "$copilot_settings_file" ]; then
1576
+ current="$(jq -r '.model // empty' "$copilot_settings_file" 2>/dev/null || true)"
1577
+ fi
1578
+ if [ -f "$copilot_parked_file" ]; then
1579
+ direct="$(jq -r '.direct_model // empty' "$copilot_parked_file" 2>/dev/null || true)"
1580
+ fi
1581
+ case "$current" in ""|weave/*) ;; *) direct="$current" ;; esac
1582
+ jq -n --arg direct "$direct" '{direct_model: $direct, router_model: "weave/auto"}' >"$copilot_parked_file"
1583
+ chmod 600 "$copilot_parked_file"
1584
+ if [ -f "$copilot_settings_file" ]; then
1585
+ merged="$(jq '.model = "weave/auto"' "$copilot_settings_file")"
1586
+ else
1587
+ merged="$(jq -n '{model: "weave/auto"}')"
1588
+ fi
1589
+ printf '%s\n' "$merged" >"$copilot_settings_file"
1590
+ }
1591
+
1592
+ # copilot_skill_names lists the router directives installed as Copilot skills.
1593
+ # Copilot exposes ~/.copilot/skills/<name> as /<name>, so Codex's skill bodies
1594
+ # are reused with the sigil and client names rewritten. Codex-only toggles and
1595
+ # skills that depend on Codex session state are excluded.
1596
+ copilot_skill_names() {
1597
+ weave_registry_skill_assets codex | grep -vxE 'disable-routing|router-session|router-models|models' || true
1598
+ }
1599
+
1600
+ # install_copilot_skills installs each router directive as a Copilot skill.
1601
+ install_copilot_skills() {
1602
+ local canonical candidate skill_src dst_dir dst_file emit_src scope_args body installed=""
1603
+ scope_args=""
1604
+ [ -n "$install_dir" ] && scope_args=" --dir $(printf '%q' "$install_dir")"
1605
+ while IFS= read -r canonical; do
1606
+ [ -n "$canonical" ] || continue
1607
+ skill_src=""
1608
+ for candidate in \
1609
+ "$script_dir/codex-skills/$canonical/SKILL.md" \
1610
+ "$script_dir/../codex-skills/$canonical/SKILL.md"
1611
+ do
1612
+ [ -f "$candidate" ] || continue
1613
+ skill_src="$candidate"
1614
+ break
1615
+ done
1616
+ [ -n "$skill_src" ] || continue
1617
+ grep -Fq "<!-- weave-router managed $canonical skill -->" "$skill_src" || continue
1618
+ dst_dir="$copilot_dir/skills/$canonical"
1619
+ dst_file="$dst_dir/SKILL.md"
1620
+ if [ -L "$copilot_dir/skills" ] || [ -L "$dst_dir" ] || [ -L "$dst_file" ] || [ -L "$dst_dir/scripts" ] || [ -L "$dst_dir/scripts/emit.sh" ]; then
1621
+ warn "Copilot skill path contains a symlink; leaving /$canonical untouched."
1622
+ continue
1623
+ fi
1624
+ if [ -e "$dst_file" ] && { [ ! -f "$dst_file" ] || ! grep -Fq "<!-- weave-router managed $canonical skill -->" "$dst_file"; }; then
1625
+ warn "A user-owned Copilot $canonical skill already exists at $dst_file; leaving it untouched."
1626
+ continue
1627
+ fi
1628
+ mkdir -p "$dst_dir"
1629
+ body="$(<"$skill_src")"
1630
+ body="${body//\{\{SCOPE\}\}/$scope_args}"
1631
+ # shellcheck disable=SC2016 # literal backticks and $ in the sed patterns
1632
+ printf '%s\n' "$body" | sed \
1633
+ -e 's/`\$\([a-z][a-z-]*\)/`\/\1/g' \
1634
+ -e 's/(or \$\([a-z][a-z-]*\))/(or \/\1)/g' \
1635
+ -e 's/--codex/--copilot/g' \
1636
+ -e 's/`codex` launch/`copilot` launch/g' \
1637
+ -e 's/Codex/Copilot CLI/g' >"$dst_file"
1638
+ emit_src="${skill_src%/SKILL.md}/scripts/emit.sh"
1639
+ if [ -f "$emit_src" ]; then
1640
+ mkdir -p "$dst_dir/scripts"
1641
+ cp "$emit_src" "$dst_dir/scripts/emit.sh"
1642
+ chmod +x "$dst_dir/scripts/emit.sh"
1643
+ fi
1644
+ installed="${installed:+$installed }/$canonical"
1645
+ done <<EOF
1646
+ $(copilot_skill_names)
1647
+ EOF
1648
+ if [ -n "$installed" ]; then
1649
+ ok "Copilot skills installed: $installed"
1650
+ else
1651
+ skip "Copilot skills not installed (no skill files next to this installer; use the npx installer for /force-model and friends)."
1652
+ fi
1653
+ }
1654
+
1380
1655
  # ---------- uninstall delegation ----------
1381
1656
  #
1382
1657
  # `--uninstall` flips this script into a thin shim for uninstall.sh: the
@@ -1471,6 +1746,9 @@ while [ $# -gt 0 ]; do
1471
1746
  --quiet)
1472
1747
  quiet="true"; shift
1473
1748
  ;;
1749
+ --no-attribution)
1750
+ attribution="false"; shift
1751
+ ;;
1474
1752
  --rotate-key)
1475
1753
  rotate_key="true"; shift
1476
1754
  ;;
@@ -1488,6 +1766,14 @@ while [ $# -gt 0 ]; do
1488
1766
  --pi)
1489
1767
  target="pi"; target_explicit="true"; shift
1490
1768
  ;;
1769
+ --copilot)
1770
+ target="copilot"; target_explicit="true"; shift
1771
+ ;;
1772
+ --wire)
1773
+ copilot_wire="${2:-}"; shift 2
1774
+ [ "$copilot_wire" = "anthropic" ] || [ "$copilot_wire" = "openai" ] || { err "--wire must be 'anthropic' or 'openai'."; exit 2; }
1775
+ copilot_wire_explicit="true"
1776
+ ;;
1491
1777
  --lsp)
1492
1778
  lsp_langs="${2:-}"; shift 2
1493
1779
  [ -n "$lsp_langs" ] || { err "--lsp requires a comma-separated language list (go,typescript,python,rust)."; exit 2; }
@@ -1579,9 +1865,36 @@ if [ "$mode" = "setup" ]; then
1579
1865
  [ -n "$return_url" ] && setup_args+=(--return-url "$return_url")
1580
1866
  [ -n "$install_dir" ] && setup_args+=(--dir "$install_dir")
1581
1867
  [ "$quiet" = "true" ] && setup_args+=(--quiet)
1868
+ [ "$attribution" = "false" ] && setup_args+=(--no-attribution)
1582
1869
  [ "$rotate_key" = "true" ] && setup_args+=(--rotate-key)
1583
- [ "$setup_claude" = "true" ] && bash "$0" "${setup_args[@]}" --claude
1584
- [ "$setup_codex" = "true" ] && bash "$0" "${setup_args[@]}" --codex
1870
+ # With both clients, the Claude run leaves its key and identity in a private
1871
+ # handoff file so the Codex run doesn't ask again. The key travels by file
1872
+ # and environment, never argv.
1873
+ setup_handoff=""
1874
+ shared_key=""
1875
+ shared_email=""
1876
+ identity_resolved=""
1877
+ if [ "$setup_claude" = "true" ] && [ "$setup_codex" = "true" ]; then
1878
+ setup_handoff="$(mktemp -t weave-setup.XXXXXX)"
1879
+ chmod 600 "$setup_handoff"
1880
+ fi
1881
+ if [ "$setup_claude" = "true" ]; then
1882
+ WEAVE_SETUP_HANDOFF_FILE="$setup_handoff" WEAVE_SETUP_DEFER_LAUNCH="${setup_handoff:+1}" bash "$0" "${setup_args[@]}" --claude \
1883
+ || { setup_status=$?; [ -z "$setup_handoff" ] || rm -f "$setup_handoff"; exit "$setup_status"; }
1884
+ fi
1885
+ if [ -n "$setup_handoff" ]; then
1886
+ if [ -s "$setup_handoff" ]; then
1887
+ identity_resolved="1"
1888
+ { IFS= read -r shared_key || true; IFS= read -r shared_email || true; } <"$setup_handoff"
1889
+ fi
1890
+ rm -f "$setup_handoff"
1891
+ fi
1892
+ if [ "$setup_codex" = "true" ]; then
1893
+ WEAVE_SETUP_SHARED_KEY="$shared_key" WEAVE_SETUP_SHARED_EMAIL="$shared_email" \
1894
+ WEAVE_SETUP_IDENTITY_RESOLVED="$identity_resolved" WEAVE_SETUP_DEFER_LAUNCH="${setup_handoff:+1}" \
1895
+ bash "$0" "${setup_args[@]}" --codex
1896
+ fi
1897
+ [ -z "$shared_key" ] || [ -n "$install_dir" ] || offer_launch "Claude Code" claude
1585
1898
  exit 0
1586
1899
  fi
1587
1900
 
@@ -1589,6 +1902,15 @@ if [ -n "$return_url" ] && [ "$mode" != "install" ]; then
1589
1902
  err "--return-url is supported only for install (or setup with one explicit target)."
1590
1903
  exit 2
1591
1904
  fi
1905
+ # The Windows PowerShell command passes the URL by env: npx.cmd re-parses
1906
+ # arguments through cmd.exe, which splits a URL at '&'.
1907
+ if [ -z "$return_url" ] && [ "$mode" = "install" ] && [ -n "${WEAVE_ROUTER_RETURN_URL:-}" ]; then
1908
+ return_url="$WEAVE_ROUTER_RETURN_URL"
1909
+ case "$return_url" in
1910
+ http://*|https://*) ;;
1911
+ *) err "WEAVE_ROUTER_RETURN_URL must be an http:// or https:// URL."; exit 2 ;;
1912
+ esac
1913
+ fi
1592
1914
 
1593
1915
  # --lsp is a pi-extension feature, so it implies the pi target; combining it
1594
1916
  # with another explicit target is a contradiction, not a preference.
@@ -1619,6 +1941,11 @@ if [ "$mode" = "login" ]; then
1619
1941
  esac
1620
1942
  elif [ "$mode" = "accounts" ] || [ "$mode" = "status" ]; then
1621
1943
  target_explicit="true"
1944
+ elif [ "$mode" = "models" ] && [ "$target_explicit" != "true" ]; then
1945
+ # Model selection belongs to the installation, not the client, so any
1946
+ # installed client's endpoint and key will do: Claude Code, then Codex.
1947
+ models_auto_target="true"
1948
+ target_explicit="true"
1622
1949
  fi
1623
1950
 
1624
1951
  # Toggle verbs only flip config install.sh already wrote: no key, no identity,
@@ -1632,7 +1959,7 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ]; then
1632
1959
  if [ "$mode" = "models" ]; then
1633
1960
  err "'models' requires an explicit client: --claude or --codex."
1634
1961
  else
1635
- err "'$mode' requires an explicit client: --claude, --codex, or --opencode."
1962
+ err "'$mode' requires an explicit client: --claude, --codex, --opencode, or --copilot."
1636
1963
  fi
1637
1964
  exit 2
1638
1965
  fi
@@ -1679,6 +2006,17 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ] && [ "$target" = "pi" ];
1679
2006
  exit 2
1680
2007
  fi
1681
2008
 
2009
+ if [ "$copilot_wire_explicit" = "true" ] && [ "$target" != "copilot" ]; then
2010
+ err "--wire only applies to --copilot."
2011
+ exit 2
2012
+ fi
2013
+ # Copilot CLI reads providers.json from the user's COPILOT_HOME only, and the
2014
+ # file holds the router key in plain text, so there is no project scope.
2015
+ if [ "$target" = "copilot" ] && [ "$scope" = "project" ]; then
2016
+ err "--copilot installs in user scope only (Copilot CLI has no project-level providers.json). Drop --scope project, or use --dir for a throwaway COPILOT_HOME."
2017
+ exit 2
2018
+ fi
2019
+
1682
2020
  if [ -z "$base_url" ]; then
1683
2021
  base_url="$DEFAULT_BASE_URL"
1684
2022
  fi
@@ -1699,13 +2037,15 @@ if [ "$target_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ -r
1699
2037
  printf " %s2)%s Codex %s— patches ~/.codex/config.toml (or <repo>/.codex/)%s\n" "$C_BRAND" "$C_RESET" "$C_DIM" "$C_RESET"
1700
2038
  printf " %s3)%s opencode %s— patches ~/.config/opencode/opencode.json (or <repo>/opencode.json)%s\n" "$C_BRAND" "$C_RESET" "$C_DIM" "$C_RESET"
1701
2039
  printf " %s4)%s pi %s— patches ~/.pi/agent/models.json + settings.json (or <repo>/.pi/)%s\n" "$C_BRAND" "$C_RESET" "$C_DIM" "$C_RESET"
1702
- printf "Choose %s[1/2/3/4]%s (default %s1%s): " "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET"
2040
+ printf " %s5)%s Copilot CLI %s— adds weave/auto to ~/.copilot/providers.json (/model picker)%s\n" "$C_BRAND" "$C_RESET" "$C_DIM" "$C_RESET"
2041
+ printf "Choose %s[1/2/3/4/5]%s (default %s1%s): " "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET"
1703
2042
  read -r target_choice </dev/tty || target_choice=""
1704
2043
  case "${target_choice:-1}" in
1705
2044
  1|""|claude|c|C) target="claude" ;;
1706
2045
  2|codex|x|X) target="codex" ;;
1707
2046
  3|opencode|o|O) target="opencode" ;;
1708
2047
  4|pi|p|P) target="pi" ;;
2048
+ 5|copilot|g|G) target="copilot" ;;
1709
2049
  *) err "Invalid choice: $target_choice."; exit 2 ;;
1710
2050
  esac
1711
2051
  fi
@@ -1715,6 +2055,11 @@ fi
1715
2055
  # not a bare "Install scope:" line. Target prompt above already finalized
1716
2056
  # $target, so the banner's per-target label reflects the user's choice.
1717
2057
  # Toggle verbs stay terse — skip the banner so `status` prints one clean line.
2058
+ if [ "$target" = "copilot" ] && [ "$scope" = "project" ]; then
2059
+ err "--copilot installs in user scope only (Copilot CLI has no project-level providers.json). Drop --scope project, or use --dir for a throwaway COPILOT_HOME."
2060
+ exit 2
2061
+ fi
2062
+
1718
2063
  [ "$mode" = "install" ] && print_banner
1719
2064
 
1720
2065
  # ---------- interactive scope prompt ----------
@@ -1724,7 +2069,7 @@ fi
1724
2069
  # they keep the user-scope default unless the caller explicitly selects a
1725
2070
  # project scope. Non-interactive installs (CI, `curl | sh --non-interactive`)
1726
2071
  # silently use the "user" default.
1727
- if [ "$mode" = "install" ] && [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ -r /dev/tty ]; then
2072
+ if [ "$mode" = "install" ] && [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ "$target" != "copilot" ] && [ -r /dev/tty ]; then
1728
2073
  # Per-target paths so the prompt text matches what actually gets written.
1729
2074
  case "$target" in
1730
2075
  codex)
@@ -1815,9 +2160,9 @@ fi
1815
2160
  # payloads with jq regardless of which client's config supplied the endpoint,
1816
2161
  # so require it there too rather than dying mid-render on `jq: command not
1817
2162
  # found`. Installing Codex itself still needs no jq.
1818
- if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] \
2163
+ if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] || [ "$target" = "copilot" ] \
1819
2164
  || { [ "$mode" = "models" ] && [ "$target" = "codex" ]; }; then
1820
- require_cmd jq "macOS: 'brew install jq' · Debian/Ubuntu: 'sudo apt install jq'"
2165
+ ensure_jq
1821
2166
  fi
1822
2167
  # curl is used by the install/update paths' health/validate probes and by every
1823
2168
  # `models` call. The on/off toggles only ping the router best-effort after a
@@ -1858,6 +2203,12 @@ case "$target" in
1858
2203
  warn "Continuing — models.json/settings.json will be written and take effect once pi is installed."
1859
2204
  fi
1860
2205
  ;;
2206
+ copilot)
2207
+ if ! command -v copilot >/dev/null 2>&1; then
2208
+ warn "'copilot' not found on PATH. Install with 'npm install -g @github/copilot', then re-run this script."
2209
+ warn "Continuing — providers.json will be written and take effect once Copilot CLI is installed."
2210
+ fi
2211
+ ;;
1861
2212
  esac
1862
2213
  fi
1863
2214
 
@@ -1876,6 +2227,7 @@ WEAVE_REGISTRY_DATA=$(cat <<'WEAVE_REGISTRY_EOF'
1876
2227
  # canonical|aliases|capability|claude|codex|opencode|pi|cursor|adapter
1877
2228
  # aliases are comma-separated; client columns are yes/no. adapter is the native asset kind.
1878
2229
  force-model|fm|prompt|yes|yes|yes|yes|manual|command,skill
2230
+ force-parent||prompt|yes|yes|yes|yes|manual|command,skill
1879
2231
  unforce-model|ufm|prompt|yes|yes|yes|yes|manual|command,skill
1880
2232
  router-feedback|rf|prompt|yes|yes|yes|no|manual|command,skill
1881
2233
  router-off||local-toggle|yes|yes|no|no|manual|command,skill
@@ -2135,6 +2487,23 @@ elif [ "$target" = "pi" ]; then
2135
2487
  fi
2136
2488
 
2137
2489
  mkdir -p "$pi_dir"
2490
+ elif [ "$target" = "copilot" ]; then
2491
+ # Copilot CLI reads $COPILOT_HOME (default ~/.copilot). --dir is a throwaway
2492
+ # COPILOT_HOME, launched with COPILOT_HOME=<dir>/.copilot.
2493
+ if [ -n "$install_dir" ]; then
2494
+ copilot_dir="$install_dir/.copilot"
2495
+ else
2496
+ copilot_dir="${COPILOT_HOME:-$settings_base/.copilot}"
2497
+ fi
2498
+ copilot_providers_file="$copilot_dir/providers.json"
2499
+ copilot_settings_file="$copilot_dir/settings.json"
2500
+ copilot_parked_file="$copilot_dir/.weave-parked.json"
2501
+ # providers.json holds the router key, so never write it through a link.
2502
+ refuse_if_symlink "$copilot_dir"
2503
+ refuse_if_symlink "$copilot_providers_file"
2504
+ refuse_if_symlink "$copilot_settings_file"
2505
+ refuse_if_symlink "$copilot_parked_file"
2506
+ mkdir -p "$copilot_dir"
2138
2507
  else
2139
2508
  # opencode discovers config in this order: $XDG_CONFIG_HOME/opencode/opencode.json
2140
2509
  # (or ~/.config/opencode/opencode.json) for user scope, and opencode.json /
@@ -2309,6 +2678,14 @@ read_pi_key() {
2309
2678
  printf '%s' "$key"
2310
2679
  }
2311
2680
 
2681
+ # read_copilot_key prints the router key from the managed `weave` provider in
2682
+ # Copilot CLI's providers.json, or nothing.
2683
+ read_copilot_key() {
2684
+ key_source_is_own "$copilot_providers_file" || return 0
2685
+ jq -r '[(.providers // [])[] | select(.name == "weave") | .headers["X-Weave-Router-Key"] // empty][0] // empty' \
2686
+ "$copilot_providers_file" 2>/dev/null || true
2687
+ }
2688
+
2312
2689
  # read_installed_key prints the router key this install already has on disk, or
2313
2690
  # nothing, for whichever client is being installed. Reading it back is what makes
2314
2691
  # a re-run painless — see the token-handling section below. Defined up here
@@ -2327,6 +2704,7 @@ models_config_file_for_target() {
2327
2704
  codex) printf '%s' "$codex_config_file" ;;
2328
2705
  opencode) printf '%s' "$opencode_config_file" ;;
2329
2706
  pi) printf '%s' "$pi_models_file" ;;
2707
+ copilot) printf '%s' "$copilot_providers_file" ;;
2330
2708
  esac
2331
2709
  }
2332
2710
 
@@ -2362,6 +2740,7 @@ read_installed_key() {
2362
2740
  codex) read_codex_key "$codex_config_file" ;;
2363
2741
  opencode) read_opencode_key "$opencode_config_file" ;;
2364
2742
  pi) read_pi_key ;;
2743
+ copilot) read_copilot_key ;;
2365
2744
  esac
2366
2745
  }
2367
2746
 
@@ -2477,6 +2856,13 @@ resolve_installed_endpoint() {
2477
2856
  found="$(json_get "$pi_models_file" '.providers.weave.baseUrl')"
2478
2857
  fi
2479
2858
  ;;
2859
+ copilot)
2860
+ if key_source_is_own "$copilot_providers_file"; then
2861
+ found="$(jq -r '[(.providers // [])[] | select(.name == "weave") | .baseUrl // empty][0] // empty' "$copilot_providers_file" 2>/dev/null || true)"
2862
+ fi
2863
+ found="${found%/}"
2864
+ found="${found%/v1}"
2865
+ ;;
2480
2866
  esac
2481
2867
  printf '%s' "${found%/}"
2482
2868
  }
@@ -2618,7 +3004,7 @@ prepare_claude_context_window() {
2618
3004
  model="${model:-sonnet}"
2619
3005
  case "$model" in
2620
3006
  *'[1m]') context_window=""; return 0 ;;
2621
- sonnet|opus|fable|claude-sonnet-4-6|claude-sonnet-5|claude-sonnet-5-5|claude-opus-4-6|claude-opus-4-7|claude-opus-4-8|claude-opus-5|claude-opus-5-5|claude-fable-5|claude-fable-5-1) ;;
3007
+ sonnet|opus|fable|claude-sonnet-4-6|claude-sonnet-5|claude-sonnet-5-5|claude-haiku-5-5|claude-opus-4-6|claude-opus-4-7|claude-opus-4-8|claude-opus-5|claude-opus-5-5|claude-fable-5|claude-fable-5-1) ;;
2622
3008
  *) err "Cannot assert 1M support for '$model'. Select a supported Sonnet/Opus/Fable model first; leaving it unchanged."; return 1 ;;
2623
3009
  esac
2624
3010
  context_managed_model="${model}[1m]"
@@ -2813,21 +3199,28 @@ toggle_claude() {
2813
3199
  esac
2814
3200
  }
2815
3201
 
2816
- toggle_codex() {
2817
- local f="$codex_config_file" state="absent" tmp
2818
- if [ -f "$f" ]; then
2819
- state="$(awk '
2820
- /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*\]/ { has_weave = 1 }
2821
- /^[[:space:]]*\[/ { in_section = 1 }
2822
- !in_section && /^[[:space:]]*model_provider[[:space:]]*=[[:space:]]*"weave"[[:space:]]*$/ { active_weave = 1 }
2823
- !in_section && /^[[:space:]]*model_provider[[:space:]]*=/ { has_active_provider = 1 }
2824
- END {
2825
- if (!has_weave) print "absent"
2826
- else if (active_weave) print "on"
2827
- else print (has_active_provider ? "absent" : "off")
2828
- }
2829
- ' "$f")"
3202
+ codex_routing_state() {
3203
+ local f="$codex_config_file"
3204
+ if [ ! -f "$f" ]; then
3205
+ printf 'absent\n'
3206
+ return 0
2830
3207
  fi
3208
+ awk '
3209
+ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*\]/ { has_weave = 1 }
3210
+ /^[[:space:]]*\[/ { in_section = 1 }
3211
+ !in_section && /^[[:space:]]*model_provider[[:space:]]*=[[:space:]]*"weave"[[:space:]]*$/ { active_weave = 1 }
3212
+ !in_section && /^[[:space:]]*model_provider[[:space:]]*=/ { has_active_provider = 1 }
3213
+ END {
3214
+ if (!has_weave) print "absent"
3215
+ else if (active_weave) print "on"
3216
+ else print (has_active_provider ? "absent" : "off")
3217
+ }
3218
+ ' "$f"
3219
+ }
3220
+
3221
+ toggle_codex() {
3222
+ local f="$codex_config_file" state tmp
3223
+ state="$(codex_routing_state)"
2831
3224
 
2832
3225
  case "$mode" in
2833
3226
  status)
@@ -2989,6 +3382,64 @@ toggle_opencode() {
2989
3382
  esac
2990
3383
  }
2991
3384
 
3385
+ # toggle_copilot flips Copilot CLI's default model between weave/auto and the
3386
+ # model it had before. The weave provider stays in providers.json either way,
3387
+ # so weave/auto remains selectable from /model while off.
3388
+ toggle_copilot() {
3389
+ local current="" direct="" has_weave="false" on="false" merged
3390
+ if [ -f "$copilot_settings_file" ]; then
3391
+ current="$(json_get "$copilot_settings_file" '.model')"
3392
+ fi
3393
+ if [ -f "$copilot_parked_file" ]; then
3394
+ direct="$(json_get "$copilot_parked_file" '.direct_model')"
3395
+ fi
3396
+ if [ -f "$copilot_providers_file" ] \
3397
+ && [ "$(jq -r '[(.providers // [])[] | select(.name == "weave")] | length > 0' "$copilot_providers_file" 2>/dev/null || true)" = "true" ]; then
3398
+ has_weave="true"
3399
+ fi
3400
+ case "$current" in weave/*) on="true" ;; esac
3401
+
3402
+ case "$mode" in
3403
+ status)
3404
+ if [ "$on" = "true" ]; then
3405
+ ok "Copilot CLI: ${C_BOLD}on${C_RESET} — default model is $current (via the Weave Router)."
3406
+ elif [ "$has_weave" = "true" ]; then
3407
+ ok "Copilot CLI: ${C_BOLD}off${C_RESET} — weave/auto is still in /model. Run 'on --copilot' to make it the default."
3408
+ else
3409
+ info "Copilot CLI: not configured for the router. Run the installer first."
3410
+ fi
3411
+ ;;
3412
+ off)
3413
+ if [ "$on" != "true" ]; then
3414
+ if [ "$has_weave" = "true" ]; then ok "Copilot CLI is already off — nothing to do."; else info "Copilot CLI isn't configured for the router. Run the installer first."; fi
3415
+ return 0
3416
+ fi
3417
+ if [ -n "$direct" ]; then
3418
+ merged="$(jq --arg model "$direct" '.model = $model' "$copilot_settings_file")"
3419
+ else
3420
+ merged="$(jq 'del(.model)' "$copilot_settings_file")"
3421
+ fi
3422
+ printf '%s\n' "$merged" >"$copilot_settings_file"
3423
+ if [ -n "$direct" ]; then
3424
+ ok "Copilot CLI is ${C_BOLD}off${C_RESET} — default model restored to $direct. weave/auto stays in /model."
3425
+ else
3426
+ ok "Copilot CLI is ${C_BOLD}off${C_RESET} — back to Copilot's default model. weave/auto stays in /model."
3427
+ fi
3428
+ report_client_event off
3429
+ ;;
3430
+ on)
3431
+ if [ "$on" = "true" ]; then ok "Copilot CLI is already on — nothing to do."; return 0; fi
3432
+ if [ "$has_weave" != "true" ]; then
3433
+ warn "Copilot CLI isn't configured for the router. Run the installer first."
3434
+ return 0
3435
+ fi
3436
+ set_copilot_default_model
3437
+ ok "Copilot CLI is ${C_BOLD}on${C_RESET} (default model weave/auto via the Weave Router). Takes effect on your next copilot run."
3438
+ report_client_event on
3439
+ ;;
3440
+ esac
3441
+ }
3442
+
2992
3443
  # ---------- model selection ----------
2993
3444
  #
2994
3445
  # `models` reads and edits the installation's model/provider selection through
@@ -3006,7 +3457,7 @@ toggle_opencode() {
3006
3457
  # Public, unauthed catalog of everything the router can route to. Mounted in
3007
3458
  # both deployment modes, so it is the one listing that always works.
3008
3459
  MODELS_CATALOG_PATH="/v1/router/models"
3009
- MODELS_DASHBOARD_URL="https://router.workweave.ai/dashboard/settings"
3460
+ MODELS_DASHBOARD_URL="https://router.workweave.ai/models"
3010
3461
 
3011
3462
  # Set by models_api on every call.
3012
3463
  models_http_status=""
@@ -3052,19 +3503,36 @@ models_api_error() {
3052
3503
  # models_fail turns the status left by models_api into a message that says what
3053
3504
  # to do next, then exits. $1 names the attempted operation.
3054
3505
  models_fail() {
3055
- local what="$1" detail
3506
+ local what="$1" detail repair_command
3056
3507
  detail="$(models_api_error)"
3508
+ case "$detail" in
3509
+ subscription_owner_unavailable|subscription_accounts_unavailable|subscription_account_update_failed|subscription_account_delete_failed)
3510
+ err "The router couldn't finish ${what} just now. Nothing changed; try again in a minute."
3511
+ return ;;
3512
+ subscription_account_not_found)
3513
+ err "No enrolled account has that id. Run 'npx $npm_package_name accounts list' to see the ids."
3514
+ return ;;
3515
+ subscription_account_rejected)
3516
+ err "The router didn't accept that sign-in. Run 'npx $npm_package_name login claude' or 'login codex' again."
3517
+ return ;;
3518
+ esac
3057
3519
  case "$models_http_status" in
3058
3520
  ""|000)
3059
3521
  err "Could not reach the router at $base_url. Is it running?"
3060
3522
  ;;
3061
3523
  401|403)
3062
- # 403 with a message is the ROUTER_EXCLUDED_MODELS/PROVIDERS env pin,
3063
- # which is actionable on its own; a bare 401/403 is a key problem.
3064
- if [ -n "$detail" ]; then
3524
+ # Preserve policy errors; invalid_key needs local setup instructions.
3525
+ if [ -n "$detail" ] && [ "$detail" != "invalid_key" ]; then
3065
3526
  err "$detail"
3066
3527
  else
3067
- err "The router rejected this installation's key. Re-run 'npx $npm_package_name --$target --rotate-key' to install a current one."
3528
+ err "Weave Router is not set up with a valid API key for $target in the $scope scope."
3529
+ printf ' The router at %s rejected the Router API key for this install (HTTP %s).\n' "$base_url" "$models_http_status" >&2
3530
+ repair_command="npx $npm_package_name --$target --scope $scope --rotate-key --base-url $(printf '%q' "$base_url")"
3531
+ [ -n "$install_dir" ] && repair_command="$repair_command --dir $(printf '%q' "$install_dir")"
3532
+ printf " Run '%s' and paste the complete rk_... key from %s, then retry this command.\n" "$repair_command" "$base_url" >&2
3533
+ if [ -n "${WEAVE_ROUTER_KEY:-}" ]; then
3534
+ printf ' WEAVE_ROUTER_KEY is set and overrides saved keys; replace or unset it before retrying.\n' >&2
3535
+ fi
3068
3536
  fi
3069
3537
  ;;
3070
3538
  404)
@@ -3075,11 +3543,15 @@ models_fail() {
3075
3543
  "$C_DIM" "$C_RESET" >&2
3076
3544
  ;;
3077
3545
  *)
3078
- if [ -n "$detail" ]; then
3079
- err "$what failed (HTTP $models_http_status): $detail"
3080
- else
3081
- err "$what failed (HTTP $models_http_status)."
3082
- fi
3546
+ case "$detail" in
3547
+ "")
3548
+ case "$models_http_status" in
3549
+ 5*) err "The router had a problem with ${what} (HTTP $models_http_status). Try again in a minute; 'npx $npm_package_name status' shows whether it's reachable." ;;
3550
+ *) err "$what failed (HTTP $models_http_status)." ;;
3551
+ esac
3552
+ ;;
3553
+ *) err "$what failed (HTTP $models_http_status): $detail" ;;
3554
+ esac
3083
3555
  ;;
3084
3556
  esac
3085
3557
  exit 1
@@ -3148,6 +3620,7 @@ models_list_catalog() {
3148
3620
  return 0
3149
3621
  fi
3150
3622
  printf "%s%sWeave Router %s%s %s· %s%s\n" "$C_BOLD" "$C_BRAND" "$what" "$C_RESET" "$C_DIM" "$base_url" "$C_RESET"
3623
+ printf "Your organization picks which of these are on in the Weave dashboard: %s%s%s\n" "$C_BOLD" "$MODELS_DASHBOARD_URL" "$C_RESET"
3151
3624
  printf "%severything this router can route to%s\n\n" "$C_DIM" "$C_RESET"
3152
3625
  if [ "$what" = "providers" ]; then
3153
3626
  printf '%s' "$models_http_body" | jq -r '[.models[].provider] | unique[] | " " + .'
@@ -3158,9 +3631,7 @@ models_list_catalog() {
3158
3631
  (.[] | " " + .model)
3159
3632
  '
3160
3633
  fi
3161
- printf "\n%sThis router does not report which of them your installation has enabled:%s\n" "$C_DIM" "$C_RESET"
3162
- printf "%sselection is an organization-wide setting here. See it, and change it, at%s\n" "$C_DIM" "$C_RESET"
3163
- printf "%s%s%s\n" "$C_DIM" "$MODELS_DASHBOARD_URL" "$C_RESET"
3634
+ printf "\n%sThis list is everything the router supports, not what your organization has turned on.%s\n" "$C_DIM" "$C_RESET"
3164
3635
  }
3165
3636
 
3166
3637
  models_list() {
@@ -3366,13 +3837,10 @@ open_url_in_browser() {
3366
3837
  open "$url" >/dev/null 2>&1
3367
3838
  ;;
3368
3839
  MINGW*|MSYS*|CYGWIN*)
3369
- # explorer.exe is a direct process launch; cmd.exe /c start would parse
3370
- # URL query separators such as '&' as shell syntax. Its exit status is
3371
- # not meaningful: an already-running shell commonly returns 1 after
3372
- # handing the URL off.
3373
- command -v explorer.exe >/dev/null 2>&1 || return 1
3374
- explorer.exe "$url" >/dev/null 2>&1 || true
3375
- return 0
3840
+ # explorer.exe can open a File Explorer window instead of the browser,
3841
+ # and cmd.exe /c start would parse URL query separators such as '&'.
3842
+ command -v rundll32.exe >/dev/null 2>&1 || return 1
3843
+ rundll32.exe url.dll,FileProtocolHandler "$url" >/dev/null 2>&1
3376
3844
  ;;
3377
3845
  *)
3378
3846
  command -v xdg-open >/dev/null 2>&1 || return 1
@@ -3553,56 +4021,298 @@ run_login() {
3553
4021
  extra="$(printf '%s\n' "$models_args" | tail -n +2)"
3554
4022
  [ -n "$provider" ] || { err "Use 'login claude' or 'login codex'."; exit 2; }
3555
4023
  [ -z "$extra" ] || { err "Login accepts exactly one provider."; exit 2; }
3556
- require_cmd jq "Install jq to enroll a subscription account."
4024
+ ensure_jq
4025
+ case "$provider" in
4026
+ claude|codex) models_api GET "/validate" || models_fail "checking Router setup" ;;
4027
+ *) err "Unknown subscription provider: $provider."; exit 2 ;;
4028
+ esac
3557
4029
  require_cmd openssl "Install OpenSSL to enroll a subscription account."
3558
4030
  case "$provider" in
3559
4031
  claude) run_login_claude ;;
3560
4032
  codex) run_login_codex ;;
3561
- *) err "Unknown subscription provider: $provider."; exit 2 ;;
4033
+ esac
4034
+ }
4035
+
4036
+ # capture_bounded prints the stdout of "$@", giving up after $1 seconds so a
4037
+ # stuck client CLI cannot hang the installer. Output goes through a file, not a
4038
+ # pipe, so a descendant that keeps stdout open cannot block the caller.
4039
+ capture_bounded() {
4040
+ local seconds="$1"; shift
4041
+ local out_file status=0
4042
+ out_file="$(mktemp -t weave-capture.XXXXXX)" || return 1
4043
+ "$@" </dev/null >"$out_file" 2>/dev/null &
4044
+ local pid=$!
4045
+ ( sleep "$seconds"; kill "$pid" 2>/dev/null; sleep 1; kill -9 "$pid" 2>/dev/null ) >/dev/null 2>&1 &
4046
+ local watcher=$!
4047
+ wait "$pid" || status=$?
4048
+ kill "$watcher" 2>/dev/null || true
4049
+ cat "$out_file"
4050
+ rm -f "$out_file"
4051
+ return "$status"
4052
+ }
4053
+
4054
+ claude_login_missing() {
4055
+ command -v claude >/dev/null 2>&1 || return 1
4056
+ local auth_status
4057
+ auth_status="$(capture_bounded 10 claude auth status --json || true)"
4058
+ printf '%s' "$auth_status" | jq -e '.loggedIn == false' >/dev/null 2>&1
4059
+ }
4060
+
4061
+ codex_login_missing() {
4062
+ command -v codex >/dev/null 2>&1 || return 1
4063
+ local login_status
4064
+ login_status="$(capture_bounded 10 env CODEX_HOME="$codex_dir" sh -c 'codex login status 2>&1' || true)"
4065
+ grep -q '^Not logged in' <<<"$login_status"
4066
+ }
4067
+
4068
+ # claude_routing_state prints "on <endpoint>", "nokey <endpoint>", "off" or
4069
+ # "absent" for this scope's saved Claude Code settings. In project scope the
4070
+ # gitignored settings.local.json overrides the committed file.
4071
+ claude_routing_state() {
4072
+ local effective_base key_settings_file="$settings_file"
4073
+ effective_base="$(json_get "$settings_file" '.env.ANTHROPIC_BASE_URL')"
4074
+ if [ "$scope" = "project" ] && [ -f "$local_settings_file" ]; then
4075
+ if jq -e '.env | has("ANTHROPIC_BASE_URL")' "$local_settings_file" >/dev/null 2>&1; then
4076
+ effective_base="$(json_get "$local_settings_file" '.env.ANTHROPIC_BASE_URL')"
4077
+ fi
4078
+ if jq -e '.env | has("ANTHROPIC_CUSTOM_HEADERS")' "$local_settings_file" >/dev/null 2>&1; then
4079
+ key_settings_file="$local_settings_file"
4080
+ fi
4081
+ fi
4082
+ if router_shaped_url "$effective_base" && claude_key_present "$key_settings_file"; then
4083
+ printf 'on %s\n' "$effective_base"
4084
+ elif router_shaped_url "$effective_base"; then
4085
+ printf 'nokey %s\n' "$effective_base"
4086
+ elif [ -f "$settings_dir/.weave-parked.json" ] || [ -n "$effective_base" ]; then
4087
+ printf 'off\n'
4088
+ else
4089
+ printf 'absent\n'
4090
+ fi
4091
+ }
4092
+
4093
+ # codex_hooks_trusted fails when Codex has not recorded a trust hash for any
4094
+ # hook in this config yet, which means it will ask for a review on next launch.
4095
+ # Codex keys trust records "<config path>:<event>:<group>:<hook>"; Weave Router
4096
+ # always installs a Stop hook in this config, so only a trusted Stop record for
4097
+ # this file counts. The installer has no TOML parser (jq only); unusual quoting
4098
+ # can only make status suggest an extra review.
4099
+ codex_hooks_trusted() {
4100
+ awk -v state_prefix="[hooks.state.\"$codex_config_file:stop:" '
4101
+ /^[[:space:]]*\[/ { in_state = (index($0, state_prefix) > 0) }
4102
+ in_state && /^[[:space:]]*trusted_hash[[:space:]]*=/ { found = 1 }
4103
+ END { exit(found ? 0 : 1) }
4104
+ ' "$codex_config_file" 2>/dev/null
4105
+ }
4106
+
4107
+ file_mtime() {
4108
+ stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null
4109
+ }
4110
+
4111
+ # newest_file prints the newest regular file in directory $1 whose name ends in
4112
+ # $2. The directory stays quoted so a cache path with spaces still matches.
4113
+ newest_file() {
4114
+ local file newest="" newest_time=0 file_time
4115
+ for file in "$1"/*"$2"; do
4116
+ [ -f "$file" ] || continue
4117
+ file_time="$(file_mtime "$file")" || continue
4118
+ if [ "$file_time" -gt "$newest_time" ]; then
4119
+ newest="$file"; newest_time="$file_time"
4120
+ fi
4121
+ done
4122
+ [ -n "$newest" ] && printf '%s\n' "$newest"
4123
+ }
4124
+
4125
+ time_ago() {
4126
+ local seconds=$(( $(date +%s) - $1 ))
4127
+ if [ "$seconds" -lt 60 ]; then printf 'just now'
4128
+ elif [ "$seconds" -lt 3600 ]; then printf '%sm ago' "$((seconds / 60))"
4129
+ elif [ "$seconds" -lt 86400 ]; then printf '%sh ago' "$((seconds / 3600))"
4130
+ else printf '%sd ago' "$((seconds / 86400))"
4131
+ fi
4132
+ }
4133
+
4134
+ # last_routed_turn summarizes the newest turn a client's status hook recorded.
4135
+ last_routed_turn() {
4136
+ local cache="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router" file detail=""
4137
+ case "$1" in
4138
+ claude)
4139
+ file="$(newest_file "$cache/claude-status" .line)" || return 1
4140
+ detail="$(head -c 512 "$file" | head -n 1)"
4141
+ detail="${detail#WEAVE ROUTER · }"
4142
+ ;;
4143
+ codex)
4144
+ # Codex rewrites the state on command-only replies too, so its mtime is
4145
+ # when the session last updated, not proof of a routed turn.
4146
+ file="$(newest_file "$cache/codex" .state)" || return 1
4147
+ detail="$(sed -n 's/^routed_model=//p' "$file" | head -n 1)"
4148
+ if [ -n "$detail" ]; then
4149
+ printf 'served %s (session updated %s)' "$detail" "$(time_ago "$(file_mtime "$file")")"
4150
+ else
4151
+ printf 'unknown; a session updated %s without recording the served model' "$(time_ago "$(file_mtime "$file")")"
4152
+ fi
4153
+ return 0
4154
+ ;;
4155
+ esac
4156
+ printf '%s%s' "$(time_ago "$(file_mtime "$file")")" "${detail:+ ($detail)}"
4157
+ }
4158
+
4159
+ status_problem() {
4160
+ printf ' %s!%s %s\n' "$C_YELLOW" "$C_RESET" "$1"
4161
+ [ -z "${2:-}" ] || printf ' %sfix:%s %s\n' "$C_DIM" "$C_RESET" "$2"
4162
+ }
4163
+
4164
+ # run_router_status prints one block per client configured in this scope, each
4165
+ # problem followed by the command that fixes it. It describes saved config, not
4166
+ # a running session.
4167
+ # print_copilot_status_row reports Copilot CLI only when a weave provider is
4168
+ # installed, so the status of users without Copilot is unchanged.
4169
+ print_copilot_status_row() {
4170
+ local copilot_dir providers settings model
4171
+ if [ -n "$install_dir" ]; then copilot_dir="$install_dir/.copilot"; else copilot_dir="${COPILOT_HOME:-$settings_base/.copilot}"; fi
4172
+ providers="$copilot_dir/providers.json"
4173
+ settings="$copilot_dir/settings.json"
4174
+ [ -f "$providers" ] && [ ! -L "$providers" ] || return 0
4175
+ [ "$(jq -r '[(.providers // [])[] | select(.name == "weave")] | length > 0' "$providers" 2>/dev/null || true)" = "true" ] || return 0
4176
+ model="$(json_get "$settings" '.model')"
4177
+ case "$model" in
4178
+ weave/*) printf ' %sCopilot CLI%s on, default model %s %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$model" "$C_DIM" "$copilot_dir" "$C_RESET" ;;
4179
+ *)
4180
+ printf ' %sCopilot CLI%s off, weave/auto is in /model but not the default\n' "$C_BOLD" "$C_RESET"
4181
+ printf ' %sturn on:%s %s on --copilot\n' "$C_DIM" "$C_RESET" "npx $npm_package_name"
4182
+ ;;
3562
4183
  esac
3563
4184
  }
3564
4185
 
3565
4186
  run_router_status() {
3566
- local saved_target codex_endpoint redacted_key
3567
- saved_target="$target"
4187
+ local npx="npx $npm_package_name" scope_flags="" redacted_key key_ok="false"
4188
+ local claude_state claude_endpoint codex_state codex_endpoint last_turn
4189
+ if [ -n "$install_dir" ]; then
4190
+ scope_flags=" --dir $(printf '%q' "$install_dir")"
4191
+ elif [ "$scope" = "project" ]; then
4192
+ scope_flags=" --scope project"
4193
+ fi
3568
4194
  settings_dir="$settings_base/.claude"
3569
4195
  settings_file="$settings_dir/settings.json"
3570
- if [ "$scope" = "project" ]; then
3571
- local_settings_file="$settings_dir/settings.local.json"
3572
- else
3573
- local_settings_file=""
3574
- fi
3575
- codex_config_file="$settings_base/.codex/config.toml"
3576
- target="codex"; codex_endpoint="$(resolve_installed_endpoint)"
3577
- target="$saved_target"
4196
+ local_settings_file=""
4197
+ [ "$scope" != "project" ] || local_settings_file="$settings_dir/settings.local.json"
4198
+ codex_dir="$settings_base/.codex"
4199
+ codex_config_file="$codex_dir/config.toml"
3578
4200
  if [ "${#api_key}" -gt 8 ]; then
3579
4201
  redacted_key="${api_key:0:3}…${api_key: -4}"
3580
4202
  else
3581
4203
  redacted_key="redacted"
3582
4204
  fi
3583
- printf 'Router: %s\nIdentity: %s\n' "$base_url" "$redacted_key"
3584
- if models_api GET "/validate"; then
3585
- printf 'Connectivity: connected (API key accepted; inference not verified)\n'
4205
+
4206
+ printf '%sWeave Router status%s %s(%s scope; saved settings, not a running session)%s\n' \
4207
+ "$C_BOLD" "$C_RESET" "$C_DIM" "$scope" "$C_RESET"
4208
+ if [ -z "$base_url" ]; then
4209
+ printf ' Router not set up for Claude Code or Codex\n'
4210
+ elif [ -z "$api_key" ]; then
4211
+ printf ' Router %s\n' "$base_url"
4212
+ printf ' Key none saved\n'
4213
+ status_problem "No router key is saved for this router." "$npx update --$target$scope_flags"
4214
+ elif models_api GET "/validate"; then
4215
+ printf ' Router %s\n' "$base_url"
4216
+ key_ok="true"
4217
+ printf ' Key %s accepted (inference not checked)\n' "$redacted_key"
4218
+ elif [ "$models_http_status" = "401" ] || [ "$models_http_status" = "403" ]; then
4219
+ printf ' Router %s\n' "$base_url"
4220
+ printf ' Key %s rejected\n' "$redacted_key"
4221
+ status_problem "The router rejected this key." "$npx --$target$scope_flags --rotate-key"
4222
+ elif [ -z "$models_http_status" ] || [ "$models_http_status" = "000" ]; then
4223
+ printf ' Router %s\n' "$base_url"
4224
+ printf ' Key %s not checked\n' "$redacted_key"
4225
+ status_problem "Could not reach $base_url." "check your network, or pass --base-url if the router moved"
3586
4226
  else
3587
- printf 'Connectivity: unavailable (HTTP %s)\n' "${models_http_status:-network error}"
3588
- fi
3589
- printf 'Claude Code settings: %s (scope: %s)\n' "$settings_dir" "$scope"
3590
- # Administrative lookup includes parked credentials; routing status must not.
3591
- toggle_claude
3592
- printf 'Status describes this scope only, not a running session; other scopes or runtime overrides may differ. Restart Claude Code after on/off changes.\n'
3593
- printf 'Codex: %s\n' "$(if [ "${codex_endpoint%/}" = "${base_url%/}" ]; then printf 'points at Router'; elif [ -n "$codex_endpoint" ]; then printf 'different endpoint (%s)' "$codex_endpoint"; else printf 'not configured'; fi)"
3594
- if models_api GET "/v1/subscriptions/accounts"; then
3595
- printf 'Subscription accounts:\n'
4227
+ printf ' Router %s\n' "$base_url"
4228
+ printf ' Key %s not checked\n' "$redacted_key"
4229
+ status_problem "The router answered HTTP $models_http_status; try again in a minute."
4230
+ fi
4231
+
4232
+ printf '\n'
4233
+ target="claude"
4234
+ claude_state="$(claude_routing_state)"
4235
+ claude_endpoint="${claude_state#* }"
4236
+ case "$claude_state" in
4237
+ on\ *)
4238
+ printf ' %sClaude Code%s on %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$settings_dir" "$C_RESET"
4239
+ [ "${claude_endpoint%/}" = "${base_url%/}" ] \
4240
+ || status_problem "Uses a different router ($claude_endpoint) than the key check above." "$npx status --claude$scope_flags"
4241
+ if ! command -v claude >/dev/null 2>&1; then
4242
+ status_problem "The claude command isn't on PATH." "install Claude Code: https://docs.claude.com/en/docs/claude-code"
4243
+ elif claude_login_missing; then
4244
+ status_problem "Claude Code isn't signed in." "run claude and type /login"
4245
+ fi
4246
+ if last_turn="$(last_routed_turn claude)"; then
4247
+ printf ' last routed turn %s\n' "$last_turn"
4248
+ else
4249
+ printf ' no routed turn yet\n'
4250
+ fi
4251
+ ;;
4252
+ nokey\ *)
4253
+ printf ' %sClaude Code%s router key missing %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$settings_dir" "$C_RESET"
4254
+ status_problem "The router key header is missing from active settings for $claude_endpoint — Weave-key authentication is not configured; other authentication methods are not checked." "$npx update --claude$scope_flags"
4255
+ ;;
4256
+ off)
4257
+ printf ' %sClaude Code%s off, talks to Anthropic directly %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$settings_dir" "$C_RESET"
4258
+ printf ' %sturn on:%s %s on --claude%s\n' "$C_DIM" "$C_RESET" "$npx" "$scope_flags"
4259
+ ;;
4260
+ *)
4261
+ printf ' %sClaude Code%s not set up %s(add it: %s --claude%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$npx" "$scope_flags" "$C_RESET"
4262
+ ;;
4263
+ esac
4264
+
4265
+ target="codex"
4266
+ codex_state="$(codex_routing_state)"
4267
+ codex_endpoint="$(resolve_installed_endpoint)"
4268
+ case "$codex_state" in
4269
+ on)
4270
+ printf ' %sCodex%s on\n' "$C_BOLD" "$C_RESET"
4271
+ if [ -z "$codex_endpoint" ]; then
4272
+ status_problem "Couldn't read Codex's router endpoint from $codex_config_file." "$npx update --codex$scope_flags"
4273
+ elif [ "${codex_endpoint%/}" != "${base_url%/}" ]; then
4274
+ status_problem "Uses a different router ($codex_endpoint) than the key check above." "$npx status --codex$scope_flags"
4275
+ fi
4276
+ if ! command -v codex >/dev/null 2>&1; then
4277
+ status_problem "The codex command isn't on PATH." "npm install -g @openai/codex"
4278
+ elif codex_login_missing; then
4279
+ status_problem "Codex isn't signed in." "codex login"
4280
+ fi
4281
+ if grep -q 'codex-status' "$codex_config_file" 2>/dev/null && ! codex_hooks_trusted; then
4282
+ status_problem "Codex hasn't trusted Weave Router's hooks yet, so the routed-model title and \$router-on / \$router-off don't run." "start codex and choose Trust all when it asks to review hooks"
4283
+ fi
4284
+ if last_turn="$(last_routed_turn codex)"; then
4285
+ printf ' last routed turn %s\n' "$last_turn"
4286
+ else
4287
+ printf ' no routed turn yet\n'
4288
+ fi
4289
+ ;;
4290
+ off)
4291
+ printf " %sCodex%s off (uses Codex's default provider)\n" "$C_BOLD" "$C_RESET"
4292
+ printf ' %sturn on:%s %s on --codex%s\n' "$C_DIM" "$C_RESET" "$npx" "$scope_flags"
4293
+ ;;
4294
+ *)
4295
+ printf ' %sCodex%s not set up %s(add it: %s --codex%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$npx" "$scope_flags" "$C_RESET"
4296
+ ;;
4297
+ esac
4298
+ print_copilot_status_row
4299
+
4300
+ if [ -z "$api_key" ]; then
4301
+ :
4302
+ elif models_api GET "/v1/subscriptions/accounts"; then
4303
+ printf '\n'
3596
4304
  if [ "$(printf '%s' "$models_http_body" | jq 'length')" -eq 0 ]; then
3597
- printf ' none enrolled\n'
4305
+ printf ' Subscriptions none enrolled %s(%s login claude | login codex)%s\n' "$C_DIM" "$npx" "$C_RESET"
3598
4306
  else
3599
- 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)'
4307
+ printf ' Subscriptions\n'
4308
+ 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)'
3600
4309
  fi
3601
4310
  elif [ "$models_http_status" = "404" ]; then
3602
- printf 'Subscription accounts: server-side pools disabled\n'
3603
- else
3604
- printf 'Subscription accounts: unavailable (HTTP %s)\n' "${models_http_status:-network error}"
4311
+ printf '\n Subscriptions not offered by this router\n'
4312
+ elif [ "$key_ok" = "true" ]; then
4313
+ printf "\n Subscriptions couldn't load them just now (HTTP %s)\n" "${models_http_status:-network error}"
3605
4314
  fi
4315
+ printf '\n%sRestart Claude Code after on/off; Codex picks changes up on its next run.%s\n' "$C_DIM" "$C_RESET"
3606
4316
  }
3607
4317
 
3608
4318
  if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] || [ "$mode" = "status" ]; then
@@ -3643,12 +4353,25 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
3643
4353
  fi
3644
4354
  if [ "$base_url_explicit" != "true" ]; then
3645
4355
  models_base="$(resolve_installed_endpoint)"
3646
- if [ -z "$models_base" ] && { [ "$mode" = "accounts" ] || [ "$mode" = "status" ]; } && [ "$target" = "claude" ]; then
4356
+ if [ -z "$models_base" ] && { [ "$mode" = "accounts" ] || [ "$mode" = "status" ] || [ "$models_auto_target" = "true" ]; } && [ "$target" = "claude" ]; then
3647
4357
  target="codex"
3648
4358
  models_base="$(resolve_installed_endpoint)"
3649
4359
  fi
4360
+ # status reports a missing install as a per-tool row instead of failing.
4361
+ if [ -z "$models_base" ] && [ "$mode" = "status" ]; then
4362
+ base_url=""
4363
+ api_key=""
4364
+ run_router_status
4365
+ exit 0
4366
+ fi
4367
+ if [ -z "$models_base" ] && [ "$models_auto_target" = "true" ]; then
4368
+ err "Weave Router is not installed for Claude Code or Codex in the $scope scope."
4369
+ printf " Run 'npx %s --claude' or 'npx %s --codex' first, then retry. For an existing custom router, pass --base-url <url>.\n" "$npm_package_name" "$npm_package_name" >&2
4370
+ exit 1
4371
+ fi
3650
4372
  if [ -z "$models_base" ]; then
3651
- err "No Weave Router install found for $target in this scope. Run 'npx $npm_package_name --$target' first, or pass --base-url."
4373
+ err "Weave Router is not installed for $target in the $scope scope."
4374
+ printf " Run 'npx %s --%s --scope %s' first, then retry this command. For an existing custom router, pass --base-url <url>.\n" "$npm_package_name" "$target" "$scope" >&2
3652
4375
  exit 1
3653
4376
  fi
3654
4377
  base_url="$models_base"
@@ -3705,6 +4428,26 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
3705
4428
  target="$login_target"
3706
4429
  fi
3707
4430
 
4431
+ # A Claude install that lost its key must not hide a working Codex install
4432
+ # from status: check Codex's own endpoint+key pair instead, and leave the
4433
+ # Claude row to report the missing key.
4434
+ if [ "$mode" = "status" ] && [ -z "$api_key" ] && [ "$target" = "claude" ] && [ "$base_url_explicit" != "true" ]; then
4435
+ target="codex"
4436
+ status_codex_base="$(resolve_installed_endpoint)"
4437
+ status_codex_key="$(read_installed_key)"
4438
+ if [ -n "$status_codex_base" ] && [ -n "$status_codex_key" ]; then
4439
+ base_url="$status_codex_base"
4440
+ api_key="$status_codex_key"
4441
+ models_base_source="$(models_config_file_for_target)"
4442
+ models_key_source="$models_base_source"
4443
+ else
4444
+ target="claude"
4445
+ fi
4446
+ fi
4447
+ if [ -z "$api_key" ] && [ "$mode" = "status" ]; then
4448
+ run_router_status
4449
+ exit 0
4450
+ fi
3708
4451
  if [ -z "$api_key" ]; then
3709
4452
  err "No router key found for $target in this scope. Re-run 'npx $npm_package_name --$target', or export WEAVE_ROUTER_KEY."
3710
4453
  exit 1
@@ -3741,6 +4484,7 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ]; then
3741
4484
  claude) toggle_claude ;;
3742
4485
  codex) toggle_codex ;;
3743
4486
  opencode) toggle_opencode ;;
4487
+ copilot) toggle_copilot ;;
3744
4488
  esac
3745
4489
  exit 0
3746
4490
  fi
@@ -3814,6 +4558,10 @@ elif [ -n "$installed_key" ]; then
3814
4558
  api_key="$installed_key"
3815
4559
  api_key_source="disk"
3816
4560
  [ "$quiet" = "true" ] || info "Reusing the router key already installed (pass --rotate-key to replace it)."
4561
+ elif [ -n "${WEAVE_SETUP_SHARED_KEY:-}" ]; then
4562
+ api_key="$WEAVE_SETUP_SHARED_KEY"
4563
+ api_key_source="setup"
4564
+ [ "$quiet" = "true" ] || info "Using the router key from the Claude Code setup above."
3817
4565
  elif [ "$mode" = "update" ]; then
3818
4566
  err "No router key found for $target. Export WEAVE_ROUTER_KEY, or run the installer once to set one up."
3819
4567
  exit 1
@@ -4149,7 +4897,43 @@ EOF
4149
4897
  # Wrapped in a function so the spinner's exec form sees a single command argv.
4150
4898
  validate_key() {
4151
4899
  printf '%s: %s\n' "$router_key_header" "$api_key" \
4152
- | curl -fsS --max-time 5 --header @- "$base_url/validate"
4900
+ | curl -fsS --max-time 5 --header @- -o /dev/null -w '%{http_code}' \
4901
+ "$base_url/validate" >"$validate_status_file" 2>/dev/null
4902
+ }
4903
+
4904
+ validate_status() {
4905
+ cat "$validate_status_file" 2>/dev/null || true
4906
+ }
4907
+
4908
+ # key_problem explains, in plain words, why the last validate_key call failed.
4909
+ key_problem() {
4910
+ case "$(validate_status)" in
4911
+ 401) printf 'the router did not recognize this key' ;;
4912
+ 403) printf '%s does not serve this key; it likely belongs to a different Weave Router deployment' "$base_url" ;;
4913
+ ""|000) printf 'could not reach %s' "$base_url" ;;
4914
+ *) printf '%s answered HTTP %s' "$base_url" "$(validate_status)" ;;
4915
+ esac
4916
+ }
4917
+
4918
+ # key_fix_hint prints the command that resolves key_problem for the target
4919
+ # flag in $1 (e.g. --codex).
4920
+ key_fix_hint() {
4921
+ case "$(validate_status)" in
4922
+ 401) printf 'copy the full key from the dashboard and run: npx @weave-os/router %s --rotate-key' "$1" ;;
4923
+ 403) printf 're-run with the router URL shown next to your key: npx @weave-os/router %s --base-url <url>' "$1" ;;
4924
+ ""|000) printf 'check your network (or --base-url), then run: npx @weave-os/router update %s' "$1" ;;
4925
+ *) printf 'once the router is healthy, run: npx @weave-os/router update %s' "$1" ;;
4926
+ esac
4927
+ }
4928
+
4929
+ # record_key_verdict sets key_verdict from the last validate_key call. Only an
4930
+ # auth answer (401/403) is evidence that the key is wrong; an unreachable or
4931
+ # failing router leaves the key unverified.
4932
+ record_key_verdict() {
4933
+ case "$(validate_status)" in
4934
+ 401|403) key_verdict="rejected" ;;
4935
+ *) key_verdict="unverified" ;;
4936
+ esac
4153
4937
  }
4154
4938
 
4155
4939
  # rewrite_installed_key rewrites this target's managed config with the key in $1.
@@ -4166,6 +4950,7 @@ rewrite_installed_key() {
4166
4950
  printf '%s\n' "$key" >"$pi_key_file"
4167
4951
  chmod 600 "$pi_key_file"
4168
4952
  ;;
4953
+ copilot) write_copilot_providers "$copilot_providers_file" "$base_url" "$key" "$user_email" "$user_name" ;;
4169
4954
  esac
4170
4955
  }
4171
4956
 
@@ -4185,26 +4970,31 @@ verify_install() {
4185
4970
 
4186
4971
  [ -n "$api_key" ] || return 0
4187
4972
 
4973
+ [ -n "$validate_status_file" ] || validate_status_file="$(mktemp -t weave-validate.XXXXXX)"
4188
4974
  if spin "Validating API key" validate_key; then
4975
+ key_verdict="valid"
4189
4976
  [ "$health_verified" = "true" ] && install_verification_succeeded="true"
4190
4977
  return 0
4191
4978
  fi
4979
+ record_key_verdict
4192
4980
 
4193
4981
  # A key we read back off disk can have been revoked or rotated since it was
4194
4982
  # installed, and reusing it silently would leave a broken install behind
4195
4983
  # exactly where the old behavior (always prompt) would have fixed it. Ask
4196
4984
  # once, then rewrite the config with whatever the user pastes. Anywhere a
4197
4985
  # prompt isn't available — non-interactive, update, --quiet, no tty, or a
4198
- # key that didn't come from disk — keep the historical warn-and-continue.
4199
- if [ "$api_key_source" = "disk" ] && [ "$non_interactive" != "true" ] \
4200
- && [ "$quiet" != "true" ] && [ -r /dev/tty ]; then
4201
- warn "The router key already installed was rejected (revoked or rotated)."
4986
+ # key that didn't come from disk — continue, and announce_done reports the
4987
+ # failure instead of claiming success.
4988
+ if [ "$key_verdict" = "rejected" ] && [ "$api_key_source" = "disk" ] \
4989
+ && [ "$non_interactive" != "true" ] && [ "$quiet" != "true" ] && [ -r /dev/tty ]; then
4990
+ warn "The router key already installed was rejected: $(key_problem)."
4202
4991
  prompt_for_key
4203
4992
  rewrite_installed_key "$api_key"
4204
4993
  if spin "Validating API key" validate_key; then
4994
+ key_verdict="valid"
4205
4995
  [ "$health_verified" = "true" ] && install_verification_succeeded="true"
4206
4996
  else
4207
- warn "Router rejected the API key (check it matches the dashboard at $base_url)."
4997
+ record_key_verdict
4208
4998
  fi
4209
4999
  return 0
4210
5000
  fi
@@ -4215,14 +5005,13 @@ verify_install() {
4215
5005
  # of the nonzero exit — a scheduled run that reports success here would
4216
5006
  # hide a revoked key indefinitely.
4217
5007
  if [ "$quiet" = "true" ]; then
4218
- warn "Router rejected the installed API key. Re-run the installer to set a new one."
5008
+ warn "Router could not verify the installed API key: $(key_problem). Re-run the installer to set a new one."
4219
5009
  else
4220
- err "Router rejected the installed API key. Re-run the installer to set a new one."
5010
+ err "Router could not verify the installed API key: $(key_problem). Re-run the installer to set a new one."
4221
5011
  fi
4222
5012
  exit 1
4223
5013
  fi
4224
5014
 
4225
- warn "Router rejected the API key (check it matches the dashboard at $base_url)."
4226
5015
  }
4227
5016
 
4228
5017
  # announce_done prints the closing line for the client named in $1. `update`
@@ -4230,17 +5019,92 @@ verify_install() {
4230
5019
  # skips the uninstall hint — that run was never the user's first contact with
4231
5020
  # the installer.
4232
5021
  announce_done() {
5022
+ write_setup_handoff
4233
5023
  printf "\n"
4234
5024
  if [ "$mode" = "update" ]; then
4235
5025
  printf "%s✓%s %s%sWeave Router config refreshed for %s.%s\n" \
4236
5026
  "$C_GREEN" "$C_RESET" "$C_BOLD" "$C_BRAND" "$1" "$C_RESET"
4237
5027
  return 0
4238
5028
  fi
4239
- printf "%s✓%s %s%sWeave Router installed for %s.%s\n" \
4240
- "$C_GREEN" "$C_RESET" "$C_BOLD" "$C_BRAND" "$1" "$C_RESET"
5029
+ case "$key_verdict" in
5030
+ rejected|unverified)
5031
+ printf "%s✗%s %sWeave Router is configured for %s, but not working yet:%s %s.\n" \
5032
+ "$C_RED" "$C_RESET" "$C_BOLD" "$1" "$C_RESET" "$(key_problem)"
5033
+ printf " Fix: %s\n" "$(key_fix_hint "--$target")"
5034
+ ;;
5035
+ *)
5036
+ printf "%s✓%s %s%sWeave Router installed for %s.%s\n" \
5037
+ "$C_GREEN" "$C_RESET" "$C_BOLD" "$C_BRAND" "$1" "$C_RESET"
5038
+ ;;
5039
+ esac
4241
5040
  open_return_url_if_verified
4242
5041
  }
4243
5042
 
5043
+ # write_setup_handoff passes this run's key and identity choice to the next
5044
+ # client a multi-client `setup` installs, so each is asked for only once. A key
5045
+ # the router did not accept is not passed on.
5046
+ write_setup_handoff() {
5047
+ [ -n "${WEAVE_SETUP_HANDOFF_FILE:-}" ] && [ -f "$WEAVE_SETUP_HANDOFF_FILE" ] || return 0
5048
+ local shared_key=""
5049
+ [ "$key_verdict" = "valid" ] && shared_key="$api_key"
5050
+ printf '%s\n%s\n' "$shared_key" "$user_email" >"$WEAVE_SETUP_HANDOFF_FILE"
5051
+ }
5052
+
5053
+
5054
+
5055
+
5056
+ # print_next_steps tells a first-time user what stands between this install and
5057
+ # their first routed prompt: the client's own login and, for Codex, the hook
5058
+ # review it shows on first launch.
5059
+ print_next_steps() {
5060
+ printf "\n"
5061
+ case "$target" in
5062
+ claude)
5063
+ if claude_login_missing; then
5064
+ printf "%sNext:%s Claude Code isn't signed in yet. Run %sclaude%s and type %s/login%s (or set ANTHROPIC_API_KEY); Weave Router routes your requests once you're signed in.\n" \
5065
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET"
5066
+ else
5067
+ printf "%sNext:%s run %sclaude%s; your next prompt goes through Weave Router.\n" \
5068
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET"
5069
+ fi
5070
+ ;;
5071
+ codex)
5072
+ local codex_cmd="codex"
5073
+ [ "$scope" = "project" ] && codex_cmd="CODEX_HOME=$codex_dir codex"
5074
+ if codex_login_missing; then
5075
+ printf "%sNext:%s Codex isn't signed in yet. Run %s%s login%s first; Weave Router routes your requests once you're signed in.\n" \
5076
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$codex_cmd" "$C_RESET"
5077
+ else
5078
+ printf "%sNext:%s run %s%s%s; your next prompt goes through Weave Router.\n" \
5079
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$codex_cmd" "$C_RESET"
5080
+ fi
5081
+ printf " On first launch Codex asks you to review Weave Router's hooks. Choose %sTrust all%s, or the routed-model title and \$router-on / \$router-off won't work.\n" \
5082
+ "$C_BOLD" "$C_RESET"
5083
+ ;;
5084
+ esac
5085
+ }
5086
+
5087
+ # finish_install closes a Claude Code or Codex run. Only a working first install
5088
+ # gets onboarding; a failed check or an update must not invite the user in.
5089
+ finish_install() {
5090
+ local label="$1"; shift
5091
+ if [ "$mode" = "install" ] && [ "$quiet" != "true" ] && [ -z "$install_dir" ] && [ "$key_verdict" = "valid" ]; then
5092
+ local pkg="npx $npm_package_name" flags="--$target" feedback="type /rf <what happened> in Claude Code"
5093
+ [ "$scope" = "project" ] && flags="$flags --scope project"
5094
+ [ "$target" = "codex" ] && feedback="type \$rf <what happened> in Codex"
5095
+ print_next_steps
5096
+ printf "\n"
5097
+ printf " %-14s %s\n" "Check routing" "$pkg status $flags"
5098
+ printf " %-14s %s\n" "Turn off" "$pkg off $flags"
5099
+ printf " %-14s %s\n" "Turn back on" "$pkg on $flags"
5100
+ printf " %-14s %s\n" "Give feedback" "$feedback"
5101
+ printf " %-14s %s\n" "Uninstall" "$(uninstall_cmd)"
5102
+ offer_launch "$label" "$@"
5103
+ elif [ "$mode" != "update" ]; then
5104
+ print_uninstall_hint
5105
+ fi
5106
+ }
5107
+
4244
5108
  # ---------- codex install path (dispatch + exit before the Claude-only writes) ----------
4245
5109
 
4246
5110
  # Install the Codex lifecycle helper that reflects the active router and the
@@ -4316,6 +5180,7 @@ install_codex_status_script() {
4316
5180
  # blocks on the network, and every failure path leaves the title model-only.
4317
5181
 
4318
5182
  set -euo pipefail
5183
+ export PATH="$PATH:$HOME/.weave/bin"
4319
5184
 
4320
5185
  # ---------- background self-refresh ----------
4321
5186
  #
@@ -4390,6 +5255,9 @@ weave_self_refresh() {
4390
5255
  return 0
4391
5256
  }
4392
5257
 
5258
+ async_title_enabled=0
5259
+ [ ! -t 2 ] || async_title_enabled=1
5260
+
4393
5261
  state_root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/codex"
4394
5262
  helper_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
4395
5263
  disabled_marker="$helper_dir/.weave-router-disabled"
@@ -4399,7 +5267,7 @@ emit_title() {
4399
5267
  local title="$1"
4400
5268
  if [ -n "${WEAVE_CODEX_STATUS_TITLE_FILE:-}" ]; then
4401
5269
  printf '%s\n' "$title" >"$WEAVE_CODEX_STATUS_TITLE_FILE"
4402
- elif [ -t 2 ] && [ -w /dev/tty ]; then
5270
+ elif { [ -t 2 ] || [ "${async_title_enabled:-0}" = "1" ]; } && [ -w /dev/tty ]; then
4403
5271
  printf '\033]0;%s\007' "$title" >/dev/tty
4404
5272
  fi
4405
5273
  return 0
@@ -4415,13 +5283,14 @@ safe_session_id() {
4415
5283
  }
4416
5284
 
4417
5285
  safe_display_value() {
4418
- printf '%s' "$1" | sed 's/[^A-Za-z0-9._:\/-]//g' | cut -c1-128
5286
+ printf '%s' "$1" | sed 's/[^A-Za-z0-9._:\/-]//g' | cut -c1-64
4419
5287
  }
4420
5288
 
4421
5289
  state_file_for() {
4422
- local id
5290
+ local id scope
4423
5291
  id="$(safe_session_id "$1")" || return 1
4424
- printf '%s/%s.state' "$state_root" "$id"
5292
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5293
+ printf '%s/%s-%s.state' "$state_root" "$scope" "$id"
4425
5294
  }
4426
5295
 
4427
5296
  read_state() {
@@ -4430,6 +5299,8 @@ read_state() {
4430
5299
  while IFS='=' read -r key value; do
4431
5300
  case "$key" in
4432
5301
  routed_model) routed_model="$value" ;;
5302
+ last_pin_model) last_pin_model="$value" ;;
5303
+ command_ids) command_ids="$value" ;;
4433
5304
  esac
4434
5305
  done <"$file"
4435
5306
  }
@@ -4439,7 +5310,7 @@ write_state() {
4439
5310
  mkdir -p "$state_root"
4440
5311
  chmod 700 "$state_root"
4441
5312
  tmp="$(mktemp "$state_root/.state.XXXXXX")"
4442
- printf 'requested_model=%s\nrouted_model=%s\n' "$requested_model" "$routed_model" >"$tmp"
5313
+ printf 'requested_model=%s\nrouted_model=%s\nlast_pin_model=%s\ncommand_ids=%s\n' "$requested_model" "$routed_model" "$last_pin_model" "$command_ids" >"$tmp"
4443
5314
  chmod 600 "$tmp"
4444
5315
  mv "$tmp" "$file"
4445
5316
  }
@@ -4450,6 +5321,99 @@ cost_file_for() {
4450
5321
  printf '%s/%s.cost' "$state_root" "$id"
4451
5322
  }
4452
5323
 
5324
+ context_file_for() {
5325
+ local id scope
5326
+ id="$(safe_session_id "$1")" || return 1
5327
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5328
+ printf '%s/%s-%s.context' "$state_root" "$scope" "$id"
5329
+ }
5330
+
5331
+ generation_file_for() {
5332
+ local id scope
5333
+ id="$(safe_session_id "$1")" || return 1
5334
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5335
+ printf '%s/active-%s-%s' "$state_root" "$scope" "$id"
5336
+ }
5337
+
5338
+ state_lock_for() {
5339
+ local id scope
5340
+ id="$(safe_session_id "$1")" || return 1
5341
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5342
+ printf '%s/state-%s-%s.lock' "$state_root" "$scope" "$id"
5343
+ }
5344
+
5345
+ acquire_state_lock() {
5346
+ local lock="$1" attempt=0 lock_mtime now dead
5347
+ while ! mkdir "$lock" 2>/dev/null; do
5348
+ lock_mtime="$(stat -c %Y "$lock" 2>/dev/null || stat -f %m "$lock" 2>/dev/null)" || lock_mtime=0
5349
+ now="$(date +%s 2>/dev/null)" || now=0
5350
+ if [ "$lock_mtime" -gt 0 ] && [ $((now - lock_mtime)) -gt 30 ]; then
5351
+ dead="${lock}.dead.$$"
5352
+ mv "$lock" "$dead" 2>/dev/null || continue
5353
+ rmdir "$dead" 2>/dev/null || true
5354
+ continue
5355
+ fi
5356
+ attempt=$((attempt + 1))
5357
+ [ "$attempt" -lt 1000 ] || return 1
5358
+ sleep 0.01
5359
+ done
5360
+ return 0
5361
+ }
5362
+
5363
+ release_state_lock() {
5364
+ rmdir "$1" 2>/dev/null || true
5365
+ }
5366
+
5367
+ context_snapshot() {
5368
+ local file="$1" id="$2" now
5369
+ [ -f "$file" ] || return 0
5370
+ [ "$(wc -c <"$file")" -le 4096 ] || return 0
5371
+ now="$(date +%s)"
5372
+ jq -ce --arg session "$id" --argjson now "$now" '
5373
+
5374
+ def tokens: type == "number" and floor == . and . > 0 and . <= 2147483647;
5375
+ def epoch: sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601;
5376
+ .context_snapshot as $s |
5377
+ select(.session_id == $session and $s.version == 1 and $s.estimate_kind == "approximate") |
5378
+ select(($s.estimate_tokens | tokens) and ($s.context_window | tokens) and ($s.output_reserve_tokens | tokens)) |
5379
+ select(($s.served_model | type) == "string" and ($s.served_model | test("^[A-Za-z0-9._:/-]{1,128}$"))) |
5380
+ select(($s.request_id | type) == "string" and ($s.request_id | length) > 0 and ($s.request_id | length) <= 128) |
5381
+ ($s.recorded_at | epoch) as $recorded | ($s.requested_at | epoch) as $requested |
5382
+ select($requested > 0 and $requested <= $recorded and $recorded <= $now and $now - $recorded <= 300) |
5383
+ $s
5384
+ ' "$file" 2>/dev/null || true
5385
+ }
5386
+
5387
+ # The Stop payload preserves this exact router wire record in raw Markdown.
5388
+ # A general Markdown parser would add a runtime dependency to standalone installs.
5389
+ command_outcome() {
5390
+ printf '%s' "$1" | jq -Rsec '
5391
+ def safe_identifier: type == "string" and test("^[A-Za-z0-9._:/-]{1,128}$");
5392
+ capture("(?:^|\n)\\[weave-router-command-v1\\]: <weave-router:(?<encoded>[A-Za-z0-9_-]{1,8192})>(?:\n|$)").encoded |
5393
+ gsub("-"; "+") | gsub("_"; "/") | @base64d | fromjson |
5394
+ select(.version == 1 and (.id | 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}$"))) |
5395
+ select(.command == "force_model" or .command == "router_session" or .command == "router_models" or .command == "router_feedback" or .command == "loop_stop") |
5396
+ select(.disposition == "accepted" or .disposition == "rejected") |
5397
+ select(.pin.transition == "unchanged" or
5398
+ (.command == "force_model" and .disposition == "accepted" and
5399
+ (.pin.transition == "cleared" or (.pin.transition == "applied" and
5400
+ (.pin.model | safe_identifier) and (.pin.provider | safe_identifier) and
5401
+ (.pin.effort == null or (.pin.effort | safe_identifier))))))
5402
+ ' 2>/dev/null || true
5403
+ }
5404
+
5405
+ pin_clause() {
5406
+ [ -z "$last_pin_model" ] || printf ' · last pin: %s' "$(safe_display_value "$last_pin_model")"
5407
+ }
5408
+
5409
+ context_clause() {
5410
+ local snapshot="$1"
5411
+ [ -n "$snapshot" ] || return 0
5412
+ awk -v estimate="$(jq -r '.estimate_tokens' <<<"$snapshot")" -v window="$(jq -r '.context_window' <<<"$snapshot")" 'BEGIN {
5413
+ printf " · last Router ctx est. ~%s/%s", (estimate < 1000 ? estimate : sprintf("%.0fk", estimate/1000)), (window < 1000 ? window : sprintf("%.0fk", window/1000))
5414
+ }'
5415
+ }
5416
+
4453
5417
  # Reads the router base URL and key out of the Codex config this install owns.
4454
5418
  # Resolved from the helper's own location first so a project-scope install never
4455
5419
  # reads (or leaks) the user-scope key: the project helper lives in the same
@@ -4527,11 +5491,11 @@ read_codex_endpoint() {
4527
5491
  # Fire-and-forget on purpose — a slow or unreachable router must never stall a
4528
5492
  # Codex turn, and every failure simply leaves the previous cache in place.
4529
5493
  refresh_session_cost() {
4530
- local id="$1" file="$2"
4531
- [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && return 0
5494
+ local id="$1" file="$2" context_file="$3" generation="$4"
5495
+ [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" = "0" ] && return 0
4532
5496
  command -v curl >/dev/null 2>&1 || return 0
4533
5497
 
4534
- local endpoint base_url key
5498
+ local endpoint base_url key active_file state_lock
4535
5499
  endpoint="$(read_codex_endpoint)" || return 0
4536
5500
  base_url="$(printf '%s' "$endpoint" | sed -n 1p)"
4537
5501
  key="$(printf '%s' "$endpoint" | sed -n 2p)"
@@ -4539,6 +5503,8 @@ refresh_session_cost() {
4539
5503
 
4540
5504
  mkdir -p "$state_root" 2>/dev/null || return 0
4541
5505
  chmod 700 "$state_root" 2>/dev/null || true
5506
+ active_file="$(generation_file_for "$id")" || return 0
5507
+ state_lock="$(state_lock_for "$id")" || return 0
4542
5508
 
4543
5509
  (
4544
5510
  exec </dev/null
@@ -4563,29 +5529,112 @@ refresh_session_cost() {
4563
5529
  file://*) ;;
4564
5530
  *) url="${url%/v1}/v1/sessions/$id/cost" ;;
4565
5531
  esac
4566
- body="$(curl -fsS --max-time 5 -H "X-Weave-Router-Key: $key" "$url" 2>/dev/null)" || exit 0
4567
- # savings_usd is the router's own (requested - actual). A body without it
4568
- # (404, error envelope, older router) writes nothing and leaves the cache.
4569
- savings="$(printf '%s' "$body" | jq -r '.savings_usd // empty' 2>/dev/null)" || exit 0
4570
- case "$savings" in
4571
- ''|*[!0-9.eE+-]*) exit 0 ;;
4572
- esac
4573
- tmp="$file.tmp.$$"
4574
- mkdir -p "$(dirname "$file")" 2>/dev/null
4575
- if printf '%s' "$savings" >"$tmp" 2>/dev/null; then
4576
- chmod 600 "$tmp" 2>/dev/null
4577
- mv "$tmp" "$file" 2>/dev/null
5532
+ header_file="$(mktemp "$state_root/.headers.XXXXXX")" || exit 0
5533
+ chmod 600 "$header_file"
5534
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
5535
+ if ! body="$(curl -fsS --max-time 5 --max-filesize 8192 -K "$header_file" "$url" 2>/dev/null)"; then
5536
+ rm -f "$header_file"
5537
+ exit 0
4578
5538
  fi
4579
- rm -f "$tmp" 2>/dev/null
5539
+ rm -f "$header_file"
5540
+ [ "$(printf '%s' "$body" | wc -c)" -le 8192 ] || exit 0
5541
+ response_session="$(jq -r '.session_id // empty' <<<"$body" 2>/dev/null)" || exit 0
5542
+ [ -z "$response_session" ] || [ "$response_session" = "$id" ] || exit 0
5543
+ context_tmp=""
5544
+ fresh_snapshot=""
5545
+ fresh_title=""
5546
+ savings_tmp=""
5547
+ savings=""
5548
+ fresh_model=""
5549
+ fresh_requested=""
5550
+ if [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" != "0" ]; then
5551
+ context_tmp="$(mktemp "$state_root/.context.XXXXXX")" || exit 0
5552
+ chmod 600 "$context_tmp"
5553
+ printf '%s' "$body" >"$context_tmp" || { rm -f "$context_tmp"; exit 0; }
5554
+ fresh_snapshot="$(context_snapshot "$context_tmp" "$id")"
5555
+ if [ -n "$fresh_snapshot" ]; then
5556
+ fresh_model="$(safe_display_value "$(jq -r '.served_model' <<<"$fresh_snapshot")")"
5557
+ fresh_requested="$(jq -r '.requested_model // empty' <<<"$fresh_snapshot")"
5558
+ if { [ -z "$requested_model" ] || [ "$fresh_requested" = "$requested_model" ]; } \
5559
+ && { [ -z "$force_model" ] || [ "$fresh_model" = "$(safe_display_value "$force_model")" ]; } \
5560
+ && { [ -z "$marker_model" ] || [ "$fresh_model" = "$routed_model" ]; }; then
5561
+ shown_requested="$requested_model"
5562
+ [ -n "$shown_requested" ] || shown_requested="$(safe_display_value "$fresh_requested")"
5563
+ if [ -n "$shown_requested" ] && [ "$fresh_model" != "$shown_requested" ]; then
5564
+ fresh_title="Weave Router · $shown_requested → $fresh_model"
5565
+ else
5566
+ fresh_title="Weave Router · $fresh_model"
5567
+ fi
5568
+ fi
5569
+ fi
5570
+ fi
5571
+ if [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" != "0" ]; then
5572
+ # savings_usd is the router's own (requested - actual). A body without it
5573
+ # (404, error envelope, older router) leaves the cache untouched.
5574
+ savings="$(printf '%s' "$body" | jq -r '.savings_usd // empty' 2>/dev/null)" || savings=""
5575
+ case "$savings" in ''|*[!0-9.eE+-]*) savings="" ;; esac
5576
+ if [ -n "$savings" ]; then
5577
+ savings_tmp="$(mktemp "$state_root/.cost.XXXXXX")" || savings=""
5578
+ if [ -n "$savings" ]; then
5579
+ if ! chmod 600 "$savings_tmp" 2>/dev/null || ! printf '%s' "$savings" >"$savings_tmp" 2>/dev/null; then
5580
+ rm -f "$savings_tmp"
5581
+ savings_tmp=""
5582
+ fi
5583
+ fi
5584
+ fi
5585
+ fi
5586
+ if ! acquire_state_lock "$state_lock"; then
5587
+ rm -f "$context_tmp" "$savings_tmp"
5588
+ exit 0
5589
+ fi
5590
+ trap 'release_state_lock "$state_lock"; rmdir "$lock" 2>/dev/null || true' EXIT
5591
+ if [ "$(cat "$active_file" 2>/dev/null)" = "$generation" ]; then
5592
+ if [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" != "0" ]; then
5593
+ if [ -n "$fresh_snapshot" ]; then
5594
+ existing_snapshot="$(context_snapshot "$context_file" "$id")"
5595
+ if [ -n "$existing_snapshot" ] && ! jq -en --argjson incoming "$fresh_snapshot" --argjson existing "$existing_snapshot" '
5596
+ def instant:
5597
+ capture("^(?<whole>[0-9-]+T[0-9:]+)(?:\\.(?<fraction>[0-9]{1,9}))?Z$") |
5598
+ [.whole, ((.fraction // "") + "000000000" | .[:9])];
5599
+ [($incoming.requested_at | instant), ($incoming.recorded_at | instant)] as $incoming_time |
5600
+ [($existing.requested_at | instant), ($existing.recorded_at | instant)] as $existing_time |
5601
+ $incoming_time > $existing_time or
5602
+ ($incoming_time == $existing_time and $incoming.request_id == $existing.request_id)
5603
+ ' >/dev/null 2>&1; then
5604
+ rm -f "$context_tmp" "$savings_tmp"
5605
+ exit 0
5606
+ elif mv "$context_tmp" "$context_file" 2>/dev/null; then
5607
+ context_tmp=""
5608
+ else
5609
+ fresh_title=""
5610
+ fi
5611
+ else
5612
+ rm -f "$context_file"
5613
+ fi
5614
+ fi
5615
+ if [ -n "$savings_tmp" ]; then
5616
+ if mv "$savings_tmp" "$file" 2>/dev/null; then
5617
+ savings_tmp=""
5618
+ else
5619
+ rm -f "$savings_tmp"
5620
+ savings_tmp=""
5621
+ fi
5622
+ fi
5623
+ if [ -n "$fresh_title" ] && [ ! -f "$disabled_marker" ]; then
5624
+ emit_title "$fresh_title$(savings_clause "$file")$(context_clause "$fresh_snapshot")$(pin_clause)"
5625
+ fi
5626
+ fi
5627
+ release_state_lock "$state_lock"
5628
+ rm -f "$context_tmp" "$savings_tmp"
4580
5629
  ) >/dev/null 2>&1 &
4581
5630
  disown 2>/dev/null || true
4582
5631
  }
4583
5632
 
4584
5633
  # Renders the cached savings as a display clause, or nothing. Values below a
4585
5634
  # cent read as "<$0.01" rather than "$0.00", which would be indistinguishable
4586
- # from "the router ran and did not beat your selection". Negative totals are
4587
- # omitted entirely: the router picked a pricier model for quality on this
4588
- # session and "saved -$0.02" is a worse answer than staying quiet.
5635
+ # from "the router ran and did not beat your selection". A negative total means
5636
+ # the router upgraded hard turns past the requested model; it reads as "cost
5637
+ # $X more" rather than a negative saving.
4589
5638
  savings_clause() {
4590
5639
  local file="$1" raw
4591
5640
  [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && return 0
@@ -4596,6 +5645,8 @@ savings_clause() {
4596
5645
  esac
4597
5646
  awk -v v="$raw" 'BEGIN{
4598
5647
  v = v + 0
5648
+ if (v <= -0.01) { printf " · cost $%.2f more", -v; exit }
5649
+ if (v <= -0.005) { printf " · cost <$0.01 more"; exit }
4599
5650
  if (v < 0.005) { exit }
4600
5651
  if (v < 0.01) { printf " · saved <$0.01"; exit }
4601
5652
  printf " · saved $%.2f", v
@@ -4645,6 +5696,38 @@ if [ "${WEAVE_CAPTURE_LLM_CLASSIFIER:-}" = "1" ] && [ -n "${WEAVE_CAPTURE_HOOK_T
4645
5696
  esac
4646
5697
  fi
4647
5698
  fi
5699
+ session_id="$(safe_session_id "$(jq -r '.session_id // empty' <<<"$payload")")" || exit 0
5700
+ active_file="$(generation_file_for "$session_id")"
5701
+ state_lock="$(state_lock_for "$session_id")"
5702
+ mkdir -p "$state_root"
5703
+ chmod 700 "$state_root"
5704
+ acquire_state_lock "$state_lock" || exit 0
5705
+ trap 'release_state_lock "$state_lock"' EXIT
5706
+ turn_file="${active_file}.turn"
5707
+ turn_id="$(safe_session_id "$(jq -r '.turn_id // empty' <<<"$payload")")" || turn_id=""
5708
+ if [ "$hook_event_name" = "SessionStart" ]; then
5709
+ rm -f "$turn_file"
5710
+ elif [ "$hook_event_name" = "UserPromptSubmit" ]; then
5711
+ if [ -n "$turn_id" ]; then
5712
+ printf '%s' "$turn_id" >"$turn_file"
5713
+ chmod 600 "$turn_file"
5714
+ else
5715
+ rm -f "$turn_file"
5716
+ fi
5717
+ elif [ "$hook_event_name" = "Stop" ] && [ -n "$turn_id" ] && [ -f "$turn_file" ] && [ "$(cat "$turn_file")" != "$turn_id" ]; then
5718
+ exit 0
5719
+ fi
5720
+ generation="$(mktemp "$state_root/.generation.XXXXXX")"
5721
+ printf '%s' "$generation" >"$generation"
5722
+ chmod 600 "$generation"
5723
+ mv "$generation" "$active_file"
5724
+ if [ "$hook_event_name" = "SessionStart" ] || [ "$hook_event_name" = "PreCompact" ]; then
5725
+ reset_context="$(context_file_for "$session_id")" || reset_context=""
5726
+ [ -z "$reset_context" ] || rm -f "$reset_context"
5727
+ fi
5728
+ if [ "$hook_event_name" = "UserPromptSubmit" ]; then
5729
+ exit 0
5730
+ fi
4648
5731
  if [ "$hook_event_name" = "SessionStart" ]; then
4649
5732
  if [ -f "$disabled_marker" ]; then
4650
5733
  emit_title "Codex · direct"
@@ -4654,7 +5737,11 @@ if [ "$hook_event_name" = "SessionStart" ]; then
4654
5737
  exit 0
4655
5738
  fi
4656
5739
 
4657
- if [ "$hook_event_name" = "PreToolUse" ] || [ "$hook_event_name" = "PreCompact" ]; then
5740
+ if [ "$hook_event_name" = "PreCompact" ]; then
5741
+ [ -f "$disabled_marker" ] || emit_title "Weave Router · active"
5742
+ exit 0
5743
+ fi
5744
+ if [ "$hook_event_name" = "PreToolUse" ]; then
4658
5745
  exit 0
4659
5746
  fi
4660
5747
 
@@ -4664,6 +5751,8 @@ fi
4664
5751
 
4665
5752
  requested_model="$(safe_display_value "$(jq -r '.model // ""' <<<"$payload")")"
4666
5753
  routed_model=""
5754
+ last_pin_model=""
5755
+ command_ids=""
4667
5756
  session_id="$(jq -r '.session_id // ""' <<<"$payload")"
4668
5757
  last_assistant_message="$(jq -r '.last_assistant_message // ""' <<<"$payload")"
4669
5758
 
@@ -4672,31 +5761,52 @@ if file="$(state_file_for "$session_id" 2>/dev/null)"; then
4672
5761
  read_state "$file"
4673
5762
  fi
4674
5763
 
4675
- # The marker is intentionally matched only at the beginning of the assistant
4676
- # message. Do not treat ordinary prose that mentions the heading as metadata.
4677
5764
  first_line="${last_assistant_message%%$'\n'*}"
4678
5765
  marker_model=""
4679
5766
  force_model=""
4680
- case "$first_line" in
4681
- "${router_badge_sentinel}✦ **Weave Router** → "*)
4682
- marker_model="${first_line#"${router_badge_sentinel}✦ **Weave Router** → "}"
4683
- marker_model="${marker_model%% ·*}"
4684
- ;;
4685
- "✦ **Weave Router** → "*)
4686
- marker_model="${first_line#"✦ **Weave Router** → "}"
4687
- marker_model="${marker_model%% ·*}"
4688
- ;;
4689
- esac
4690
- case "$first_line" in
4691
- "Weave Router: force-model applied: "*" ("*)
4692
- force_model="${first_line#"Weave Router: force-model applied: "}"
4693
- force_model="${force_model%% (*}"
4694
- ;;
5767
+ structured_command=0
5768
+ case "$last_assistant_message" in
5769
+ *'[weave-router-command-v'*) structured_command=1 ;;
4695
5770
  esac
5771
+ if [ "$structured_command" = 1 ]; then
5772
+ outcome="$(command_outcome "$last_assistant_message")"
5773
+ if [ -n "$outcome" ]; then
5774
+ outcome_id="$(jq -r '.id' <<<"$outcome")"
5775
+ case " $command_ids " in
5776
+ *" $outcome_id "*) ;;
5777
+ *)
5778
+ command_ids="${command_ids:+$command_ids }$outcome_id"
5779
+ case "$(jq -r '.pin.transition' <<<"$outcome")" in
5780
+ applied)
5781
+ last_pin_model="$(jq -r '.pin.model + (if (.pin.effort // "") == "" then "" else ":" + .pin.effort end)' <<<"$outcome")"
5782
+ force_model="$(jq -r '.pin.model' <<<"$outcome")"
5783
+ ;;
5784
+ cleared) last_pin_model="" ;;
5785
+ esac
5786
+ ;;
5787
+ esac
5788
+ fi
5789
+ else
5790
+ # Legacy acknowledgments remain readable; only explicit force and clear mutate history.
5791
+ case "$first_line" in
5792
+ "Weave Router: force-model applied: "*" ("*|"✦ **Weave Router** → force-model applied: "*" ("*|"Weave Router: force-parent applied: "*" ("*|"✦ **Weave Router** → force-parent applied: "*" ("*)
5793
+ force_model="${first_line#*applied: }"
5794
+ force_model="${force_model%% (*}"
5795
+ last_pin_model="$(safe_display_value "$force_model")"
5796
+ ;;
5797
+ "Weave Router: force-model cleared"*|"✦ **Weave Router** → force-model cleared"*) last_pin_model="" ;;
5798
+ *)
5799
+ case "$first_line" in
5800
+ "${router_badge_sentinel}✦ **Weave Router** → "*) marker_model="${first_line#"${router_badge_sentinel}✦ **Weave Router** → "}" ;;
5801
+ "✦ **Weave Router** → "*) marker_model="${first_line#"✦ **Weave Router** → "}" ;;
5802
+ esac
5803
+ marker_model="${marker_model%% ·*}"
5804
+ case "$marker_model" in ''|*[!A-Za-z0-9._:/-]*) marker_model="" ;; esac
5805
+ ;;
5806
+ esac
5807
+ fi
4696
5808
  if [ -n "$marker_model" ]; then
4697
5809
  routed_model="$(safe_display_value "$marker_model")"
4698
- elif [ -n "$force_model" ]; then
4699
- routed_model="$(safe_display_value "$force_model")"
4700
5810
  else
4701
5811
  routed_model="$(safe_display_value "$routed_model")"
4702
5812
  fi
@@ -4710,22 +5820,41 @@ fi
4710
5820
  # turn would not be included even in a blocking read — reading first and
4711
5821
  # refreshing after costs a turn of freshness and buys never blocking Codex.
4712
5822
  savings=""
5823
+ context=""
5824
+ context_file="$(context_file_for "$session_id" 2>/dev/null)" || context_file=""
5825
+ if [ -n "$context_file" ] && [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" != "0" ]; then
5826
+ snapshot="$(context_snapshot "$context_file" "$session_id")"
5827
+ if [ -n "$snapshot" ]; then
5828
+ snapshot_model="$(safe_display_value "$(jq -r '.served_model' <<<"$snapshot")")"
5829
+ snapshot_requested="$(jq -r '.requested_model // empty' <<<"$snapshot")"
5830
+ if { [ -z "$marker_model" ] || [ "$snapshot_model" = "$routed_model" ]; } && { [ -z "$requested_model" ] || [ "$snapshot_requested" = "$requested_model" ]; } && { [ -z "$force_model" ] || [ "$snapshot_model" = "$(safe_display_value "$force_model")" ]; }; then
5831
+ routed_model="$snapshot_model"
5832
+ [ -n "$requested_model" ] || requested_model="$(safe_display_value "$snapshot_requested")"
5833
+ context="$(context_clause "$snapshot")"
5834
+ fi
5835
+ fi
5836
+ fi
4713
5837
  cost_file=""
4714
5838
  if cost_file="$(cost_file_for "$session_id" 2>/dev/null)"; then
4715
5839
  savings="$(savings_clause "$cost_file")"
4716
- refresh_session_cost "$(safe_session_id "$session_id")" "$cost_file"
5840
+
4717
5841
  fi
4718
5842
 
4719
5843
  if [ -n "$routed_model" ] && [ -n "$requested_model" ] && [ "$routed_model" != "$requested_model" ]; then
4720
- title="Weave Router · $routed_model ← $requested_model$savings"
5844
+ title="Weave Router · $requested_model → $routed_model$savings"
4721
5845
  elif [ -n "$routed_model" ]; then
4722
5846
  title="Weave Router · $routed_model$savings"
4723
5847
  elif [ -n "$requested_model" ]; then
4724
- title="Weave Router · active ← $requested_model$savings"
5848
+ title="Weave Router · $requested_model → active$savings"
4725
5849
  else
4726
5850
  title="Weave Router · active$savings"
4727
5851
  fi
4728
- emit_title "$title"
5852
+ emit_title "$title$context$(pin_clause)"
5853
+ release_state_lock "$state_lock"
5854
+ trap - EXIT
5855
+ if [ -n "$cost_file" ] && [ -n "$context_file" ]; then
5856
+ refresh_session_cost "$(safe_session_id "$session_id")" "$cost_file" "$context_file" "$generation"
5857
+ fi
4729
5858
  CODEX_STATUS_EOF
4730
5859
  fi
4731
5860
  chmod 700 "$codex_status_file"
@@ -4799,6 +5928,7 @@ install_codex_directive_script() {
4799
5928
  # fire.
4800
5929
 
4801
5930
  set -uo pipefail
5931
+ export PATH="$PATH:$HOME/.weave/bin"
4802
5932
 
4803
5933
  # How long the toggle may take before the hook gives up and passes the prompt
4804
5934
  # through. npx resolves from cache after first use; the budget covers a cold
@@ -4942,7 +6072,7 @@ trap "rm -f '$out_file'" EXIT
4942
6072
  # word-split at runtime -- the braces are a template token, not an expansion.
4943
6073
  # shellcheck disable=SC1083
4944
6074
  run_bounded "$WEAVE_TOGGLE_TIMEOUT" "$out_file" \
4945
- npx --package @weave-os/router -y -- weave-router "$toggle" --codex{{SCOPE}}
6075
+ env NPM_CONFIG_UPDATE_NOTIFIER=false npx --package @weave-os/router -y -- weave-router "$toggle" --codex{{SCOPE}}
4946
6076
  status=$?
4947
6077
 
4948
6078
  output="$(cat "$out_file" 2>/dev/null || true)"
@@ -5058,6 +6188,39 @@ if [ "$target" = "codex" ]; then
5058
6188
  # point CODEX_HOME at the directory we wrote so Codex finds our config.
5059
6189
  info "Run Codex with CODEX_HOME=$codex_dir codex so it picks up this config."
5060
6190
  fi
6191
+ if [ "$scope" = "project" ]; then
6192
+ finish_install "Codex" env CODEX_HOME="$codex_dir" codex
6193
+ else
6194
+ finish_install "Codex" codex
6195
+ fi
6196
+ exit 0
6197
+ fi
6198
+
6199
+ # ---------- copilot install path (dispatch + exit before the Claude-only writes) ----------
6200
+
6201
+ if [ "$target" = "copilot" ]; then
6202
+ # A re-install or update keeps the wire format already installed unless
6203
+ # --wire picks a new one.
6204
+ if [ "$copilot_wire_explicit" != "true" ] && [ -f "$copilot_providers_file" ] \
6205
+ && [ "$(jq -r '[(.providers // [])[] | select(.name == "weave") | .type][0] // empty' "$copilot_providers_file" 2>/dev/null || true)" = "openai" ]; then
6206
+ copilot_wire="openai"
6207
+ fi
6208
+ write_copilot_providers "$copilot_providers_file" "$base_url" "$api_key" "$user_email" "$user_name"
6209
+ ok "Copilot CLI provider weave/auto written to $copilot_providers_file ($copilot_wire wire)"
6210
+ set_copilot_default_model
6211
+ ok "Copilot CLI default model set to weave/auto in $copilot_settings_file"
6212
+ install_copilot_skills
6213
+
6214
+ verify_install
6215
+
6216
+ announce_done "GitHub Copilot CLI"
6217
+ if [ "$mode" = "install" ] && [ "$quiet" != "true" ]; then
6218
+ info "GitHub models stay available: switch any time with /model in Copilot CLI."
6219
+ info "Router directives are Copilot skills: /force-model <id>, /unforce-model, /rf <feedback>, /router-off, /router-on."
6220
+ fi
6221
+ if [ -n "$install_dir" ]; then
6222
+ info "Run Copilot CLI with COPILOT_HOME=$copilot_dir copilot so it picks up this config."
6223
+ fi
5061
6224
  [ "$mode" = "update" ] || print_uninstall_hint
5062
6225
  exit 0
5063
6226
  fi
@@ -5184,26 +6347,65 @@ cat > "$statusline_file" << 'STATUSLINE_EOF'
5184
6347
  #!/usr/bin/env bash
5185
6348
  #
5186
6349
  # Claude Code statusline for the Weave Router. CC pipes a JSON blob on stdin
5187
- # whose `transcript_path` points at the JSONL log of the current session and
5188
- # whose `model.display_name` is the user's CC-side model selection. The
5189
- # router rewrites each request's `model` field before forwarding, so
5190
- # Anthropic/OpenAI/Google return `message.model = <routed>` in the SSE
5191
- # stream and CC stores that in the transcript verbatim. Per-turn savings
5192
- # come from comparing each turn's routed cost against what the user's
5193
- # selection would have cost on the same tokens. Works identically for
5194
- # local docker and the managed cloud router — no sidecar, no DB, no auth.
6350
+ # whose `transcript_path` points at the current session's JSONL log. Model
6351
+ # names and price comparisons come from that local transcript; neither
6352
+ # establishes the request's destination, including when the transcript
6353
+ # contains an old router pin acknowledgement.
5195
6354
  #
5196
6355
  # Wire up by adding to ~/.claude/settings.json:
5197
6356
  # { "statusLine": { "type": "command", "command": "/abs/path/to/cc-statusline.sh" } }
5198
6357
  #
5199
6358
  # Renders:
5200
- # WEAVE ROUTER — claude-sonnet-4-5 ← claude-opus-4-7 · saved $1.23 · 12.4k in / 3.1k out / 45.2k cached
6359
+ # WEAVE ROUTER · you picked opus-4-7 → served sonnet-4-5 · saved ~$1.23 this session
5201
6360
  #
5202
6361
  # Pricing source of truth: internal/router/catalog. Input/output prices and
5203
6362
  # cache-read multipliers are generated by cmd/genprices. Cache creation remains
5204
6363
  # at 1.25× input pending TTL-aware pricing.
5205
6364
 
5206
6365
  set -euo pipefail
6366
+ export PATH="$PATH:$HOME/.weave/bin"
6367
+
6368
+ # ---------- /router-status prompt hook ----------
6369
+ #
6370
+ # Registered as a UserPromptSubmit hook with --prompt-hook. Every other prompt
6371
+ # passes through untouched; /router-status is answered from local state and
6372
+ # stopped before it reaches a model, so checking the router never spends a
6373
+ # turn. The settings env (router URL and key header) is inherited by hooks, and
6374
+ # the session's last statusline render is cached by the statusline below.
6375
+ weave_router_status_hook() {
6376
+ command -v jq >/dev/null 2>&1 || return 0
6377
+ local payload prompt session line="" root report scope_suffix=""
6378
+ [ "$#" -eq 0 ] || scope_suffix="$(printf ' %q' "$@")"
6379
+ payload="$(cat)"
6380
+ prompt="$(jq -r '.prompt // empty' <<<"$payload" 2>/dev/null)" || return 0
6381
+ [[ "$prompt" =~ ^[[:space:]]*/router-status[[:space:]]*$ ]] || return 0
6382
+ if [[ "${ANTHROPIC_BASE_URL:-}" == https://api.anthropic.com* ]]; then
6383
+ report="Weave Router is off: Claude Code talks to Anthropic directly. Turn it back on with /router-on."
6384
+ elif [[ -n "${ANTHROPIC_BASE_URL:-}" && "${ANTHROPIC_CUSTOM_HEADERS:-}" == *"X-Weave-Router-Key:"* ]]; then
6385
+ report="Weave Router is on: Claude Code sends requests to ${ANTHROPIC_BASE_URL}."
6386
+ elif [[ -n "${ANTHROPIC_BASE_URL:-}" ]]; then
6387
+ report="Claude Code sends requests to ${ANTHROPIC_BASE_URL}, but no Weave Router key is set. Repair it with: npx @weave-os/router update --claude${scope_suffix}"
6388
+ else
6389
+ report="Weave Router is off: Claude Code talks to Anthropic directly. Turn it back on with /router-on."
6390
+ fi
6391
+ session="$(jq -r '.session_id // empty' <<<"$payload" 2>/dev/null)" || session=""
6392
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-status"
6393
+ if [[ "$session" =~ ^[A-Za-z0-9._-]{1,128}$ && -f "$root/$session.line" ]]; then
6394
+ line="$(head -c 512 "$root/$session.line" | head -n 1)"
6395
+ fi
6396
+ if [[ -n "$line" ]]; then
6397
+ report="$report"$'\n'"This session: $line"
6398
+ else
6399
+ report="$report"$'\n'"No routed turn yet in this session."
6400
+ fi
6401
+ report="$report"$'\n'"Full check (key, login, endpoint): npx @weave-os/router status --claude${scope_suffix}"
6402
+ jq -n --arg reason "$report" '{continue: false, stopReason: $reason, suppressOutput: true}'
6403
+ }
6404
+ if [ "${1:-}" = "--prompt-hook" ]; then
6405
+ shift
6406
+ weave_router_status_hook "$@" || true
6407
+ exit 0
6408
+ fi
5207
6409
 
5208
6410
  # ---------- background self-refresh ----------
5209
6411
  #
@@ -5605,7 +6807,14 @@ weave_hidden_gate() {
5605
6807
  file://*) ;;
5606
6808
  *) url="$url/v1/display-settings" ;;
5607
6809
  esac
5608
- body="$(curl -fsS --max-time 5 -H "X-Weave-Router-Key: $key" "$url" 2>/dev/null)" || exit 0
6810
+ header_file="$(mktemp "$cache_dir/.headers.XXXXXX")" || exit 0
6811
+ chmod 600 "$header_file"
6812
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
6813
+ if ! body="$(curl -fsS --max-time 5 -K "$header_file" "$url" 2>/dev/null)"; then
6814
+ rm -f "$header_file"
6815
+ exit 0
6816
+ fi
6817
+ rm -f "$header_file"
5609
6818
  hidden="$(printf '%s' "$body" | jq -r '.hide_terminal_surfaces // false' 2>/dev/null)"
5610
6819
  tmp="$cache.tmp.$$"
5611
6820
  if [ "$hidden" = "true" ]; then
@@ -5624,21 +6833,32 @@ if weave_hidden_gate </dev/null; then
5624
6833
  fi
5625
6834
 
5626
6835
  input="$(cat)"
6836
+ jq -e 'type == "object"' >/dev/null 2>&1 <<<"$input" || exit 0
5627
6837
  transcript_path="$(printf '%s' "$input" | jq -r '.transcript_path // empty')"
5628
- # Prefer model.id over display_name: pricing keys + the routed model id in
6838
+ # Prefer model.id over display_name: pricing keys + the response model id in
5629
6839
  # the transcript are canonical ids (e.g. claude-opus-4-7), while display_name
5630
6840
  # is a human label ("Opus 4.7 (1M context)") that won't hit the pricing table,
5631
- # zeroing out savings. id passes through normalize_model cleanly.
6841
+ # preventing a price comparison. id passes through normalize_model cleanly.
5632
6842
  selected_display="$(printf '%s' "$input" | jq -r '.model.id // .model.display_name // "?"')"
5633
6843
 
6844
+ # Claude owns this percentage and its window; session totals never establish it.
6845
+ context_clause="$(jq -r '
6846
+ .context_window as $c |
6847
+ if ($c.context_window_size | type) == "number" and $c.context_window_size > 0 and $c.context_window_size <= 2147483647
6848
+ and ($c.context_window_size | floor) == $c.context_window_size
6849
+ and ($c.used_percentage | type) == "number" and $c.used_percentage >= 0 and $c.used_percentage <= 100
6850
+ then " · Context " + ($c.used_percentage | floor | tostring) + "%" +
6851
+ (if $c.used_percentage >= 90 then " !" else "" end)
6852
+ else "" end
6853
+ ' <<<"$input" 2>/dev/null)" || context_clause=""
6854
+
6855
+ [ "${WEAVE_STATUSLINE_CONTEXT:-1}" != "0" ] || context_clause=""
6856
+
5634
6857
  # Normalize a model id to a pricing-table key. CC + the decisions log carry
5635
6858
  # two flavors of annotation we don't want in the lookup:
5636
6859
  # * date suffix: claude-opus-4-7-20260101 → claude-opus-4-7
5637
6860
  # * variant tag: claude-opus-4-7[1m] → claude-opus-4-7
5638
- # The 1M-context variant prices ~2× base for prompts >200k tokens, but for
5639
- # the "saved $X vs your selection" UX the base rate is the right comparison
5640
- # — we're measuring the model swap, not the context tier. Used below on the
5641
- # routed and requested model ids from the decisions log / transcript.
6861
+ # This estimate compares base model prices, not context-tier surcharges.
5642
6862
  normalize_model() {
5643
6863
  printf '%s' "$1" | sed -E 's/\[[^]]*\]$//; s/-[0-9]{8}$//'
5644
6864
  }
@@ -5652,6 +6872,7 @@ prices='{
5652
6872
  "claude-fable-5": 0.01,
5653
6873
  "claude-fable-5-1": 0.01,
5654
6874
  "claude-haiku-4-5": 0.001,
6875
+ "claude-haiku-5-5": 0.0001,
5655
6876
  "claude-opus-4-0": 0.015,
5656
6877
  "claude-opus-4-1": 0.015,
5657
6878
  "claude-opus-4-5": 0.005,
@@ -5662,12 +6883,12 @@ prices='{
5662
6883
  "claude-opus-5-5": 0.004,
5663
6884
  "claude-sonnet-4-5": 0.003,
5664
6885
  "claude-sonnet-4-6": 0.003,
5665
- "claude-sonnet-5": 0.003,
6886
+ "claude-sonnet-5": 0.002,
5666
6887
  "claude-sonnet-5-5": 0.002,
5667
- "deepseek/deepseek-v4-flash": 0.0001134,
6888
+ "deepseek/deepseek-v4-flash": 0.00014,
5668
6889
  "deepseek/deepseek-v4-pro": 0.00174,
5669
6890
  "deepseek/deepseek-v4-pro-0813": 0.00174,
5670
- "deepseek/deepseek-v4.1-flash": 0.00022,
6891
+ "deepseek/deepseek-v4.1-flash": 0.0002,
5671
6892
  "gemini-2.0-flash": 0.0001,
5672
6893
  "gemini-2.0-flash-lite": 0.000075,
5673
6894
  "gemini-2.5-flash": 0.0003,
@@ -5682,6 +6903,7 @@ prices='{
5682
6903
  "gemini-3.6-flash": 0.0015,
5683
6904
  "gemini-3.7-flash": 0.0015,
5684
6905
  "gemini-3.8-flash": 0.0015,
6906
+ "gemini-4-argon": 0.002,
5685
6907
  "google/gemma-4-26b-a4b-it": 0.00015,
5686
6908
  "gpt-4.1": 0.002,
5687
6909
  "gpt-4.1-mini": 0.0004,
@@ -5708,17 +6930,21 @@ prices='{
5708
6930
  "gpt-6-astra": 0.01,
5709
6931
  "gpt-6-luna": 0.0001,
5710
6932
  "gpt-6-sol": 0.002,
6933
+ "gpt-6.1-sol": 0.002,
6934
+ "gpt-6.1-terra": 0.001,
5711
6935
  "grok-4.5": 0.002,
5712
6936
  "grok-4.6": 0.002,
5713
6937
  "grok-4.7": 0.002,
5714
6938
  "inclusionai/ling-3.0-flash": 0.00006,
5715
6939
  "minimax/minimax-m2.7": 0.0003,
5716
6940
  "minimax/minimax-m3": 0.0003,
6941
+ "minimax/minimax-m3.1-flash": 0.00015,
5717
6942
  "mistralai/mistral-small-2603": 0.0002,
5718
6943
  "moonshotai/kimi-k2.5": 0.0006,
5719
6944
  "moonshotai/kimi-k2.6": 0.00095,
5720
6945
  "moonshotai/kimi-k2.7": 0.00095,
5721
6946
  "moonshotai/kimi-k3": 0.003,
6947
+ "moonshotai/kimi-k3.1": 0.002,
5722
6948
  "muse-spark-1.3": 0.00125,
5723
6949
  "qwen/qwen3-235b-a22b-2507": 0.0002266,
5724
6950
  "qwen/qwen3-30b-a3b-instruct-2507": 0.00015,
@@ -5730,7 +6956,7 @@ prices='{
5730
6956
  "qwen/qwen3.7-plus": 0.0004,
5731
6957
  "qwen/qwen3.8-max": 0.002,
5732
6958
  "xiaomi/mimo-v2.5-pro": 0.001,
5733
- "xiaomi/mimo-v2.6-flash": 0.00014,
6959
+ "xiaomi/mimo-v2.6-flash": 0.00013,
5734
6960
  "xiaomi/mimo-v2.6-pro": 0.000435,
5735
6961
  "z-ai/glm-5": 0.001,
5736
6962
  "z-ai/glm-5.1": 0.0014,
@@ -5742,6 +6968,7 @@ prices='{
5742
6968
  "claude-fable-5": 0.05,
5743
6969
  "claude-fable-5-1": 0.05,
5744
6970
  "claude-haiku-4-5": 0.005,
6971
+ "claude-haiku-5-5": 0.0005,
5745
6972
  "claude-opus-4-0": 0.075,
5746
6973
  "claude-opus-4-1": 0.075,
5747
6974
  "claude-opus-4-5": 0.025,
@@ -5752,12 +6979,12 @@ prices='{
5752
6979
  "claude-opus-5-5": 0.02,
5753
6980
  "claude-sonnet-4-5": 0.015,
5754
6981
  "claude-sonnet-4-6": 0.015,
5755
- "claude-sonnet-5": 0.015,
6982
+ "claude-sonnet-5": 0.01,
5756
6983
  "claude-sonnet-5-5": 0.01,
5757
- "deepseek/deepseek-v4-flash": 0.0002791,
6984
+ "deepseek/deepseek-v4-flash": 0.00028,
5758
6985
  "deepseek/deepseek-v4-pro": 0.00348,
5759
6986
  "deepseek/deepseek-v4-pro-0813": 0.00348,
5760
- "deepseek/deepseek-v4.1-flash": 0.00066,
6987
+ "deepseek/deepseek-v4.1-flash": 0.00099,
5761
6988
  "gemini-2.0-flash": 0.0004,
5762
6989
  "gemini-2.0-flash-lite": 0.0003,
5763
6990
  "gemini-2.5-flash": 0.0012,
@@ -5772,6 +6999,7 @@ prices='{
5772
6999
  "gemini-3.6-flash": 0.0075,
5773
7000
  "gemini-3.7-flash": 0.0075,
5774
7001
  "gemini-3.8-flash": 0.0075,
7002
+ "gemini-4-argon": 0.01,
5775
7003
  "google/gemma-4-26b-a4b-it": 0.0006,
5776
7004
  "gpt-4.1": 0.008,
5777
7005
  "gpt-4.1-mini": 0.0016,
@@ -5798,17 +7026,21 @@ prices='{
5798
7026
  "gpt-6-astra": 0.05,
5799
7027
  "gpt-6-luna": 0.0005,
5800
7028
  "gpt-6-sol": 0.01,
7029
+ "gpt-6.1-sol": 0.01,
7030
+ "gpt-6.1-terra": 0.005,
5801
7031
  "grok-4.5": 0.006,
5802
7032
  "grok-4.6": 0.006,
5803
7033
  "grok-4.7": 0.006,
5804
7034
  "inclusionai/ling-3.0-flash": 0.00018,
5805
7035
  "minimax/minimax-m2.7": 0.0012,
5806
7036
  "minimax/minimax-m3": 0.0012,
7037
+ "minimax/minimax-m3.1-flash": 0.0006,
5807
7038
  "mistralai/mistral-small-2603": 0.0006,
5808
7039
  "moonshotai/kimi-k2.5": 0.003,
5809
7040
  "moonshotai/kimi-k2.6": 0.004,
5810
7041
  "moonshotai/kimi-k2.7": 0.004,
5811
7042
  "moonshotai/kimi-k3": 0.015,
7043
+ "moonshotai/kimi-k3.1": 0.01,
5812
7044
  "muse-spark-1.3": 0.00425,
5813
7045
  "qwen/qwen3-235b-a22b-2507": 0.0009064,
5814
7046
  "qwen/qwen3-30b-a3b-instruct-2507": 0.0006,
@@ -5832,6 +7064,7 @@ prices='{
5832
7064
  "claude-fable-5": 0.1,
5833
7065
  "claude-fable-5-1": 0.025,
5834
7066
  "claude-haiku-4-5": 0.1,
7067
+ "claude-haiku-5-5": 0.1,
5835
7068
  "claude-opus-4-0": 0.1,
5836
7069
  "claude-opus-4-1": 0.1,
5837
7070
  "claude-opus-4-5": 0.1,
@@ -5844,10 +7077,10 @@ prices='{
5844
7077
  "claude-sonnet-4-6": 0.1,
5845
7078
  "claude-sonnet-5": 0.1,
5846
7079
  "claude-sonnet-5-5": 0.1,
5847
- "deepseek/deepseek-v4-flash": 0.2,
7080
+ "deepseek/deepseek-v4-flash": 0.1,
5848
7081
  "deepseek/deepseek-v4-pro": 0.0862,
5849
7082
  "deepseek/deepseek-v4-pro-0813": 0.0862,
5850
- "deepseek/deepseek-v4.1-flash": 0.031818181818181815,
7083
+ "deepseek/deepseek-v4.1-flash": 0.03,
5851
7084
  "gemini-2.0-flash": 0.25,
5852
7085
  "gemini-2.0-flash-lite": 0.25,
5853
7086
  "gemini-2.5-flash": 0.1,
@@ -5862,6 +7095,7 @@ prices='{
5862
7095
  "gemini-3.6-flash": 0.1,
5863
7096
  "gemini-3.7-flash": 0.1,
5864
7097
  "gemini-3.8-flash": 0.1,
7098
+ "gemini-4-argon": 0.1,
5865
7099
  "google/gemma-4-26b-a4b-it": 0.1,
5866
7100
  "gpt-4.1": 0.25,
5867
7101
  "gpt-4.1-mini": 0.25,
@@ -5888,17 +7122,21 @@ prices='{
5888
7122
  "gpt-6-astra": 0.1,
5889
7123
  "gpt-6-luna": 0.1,
5890
7124
  "gpt-6-sol": 0.1,
7125
+ "gpt-6.1-sol": 0.05,
7126
+ "gpt-6.1-terra": 0.05,
5891
7127
  "grok-4.5": 0.25,
5892
7128
  "grok-4.6": 0.25,
5893
7129
  "grok-4.7": 0.25,
5894
7130
  "inclusionai/ling-3.0-flash": 0.2,
5895
7131
  "minimax/minimax-m2.7": 0.2,
5896
7132
  "minimax/minimax-m3": 0.2,
7133
+ "minimax/minimax-m3.1-flash": 0.1,
5897
7134
  "mistralai/mistral-small-2603": 0.1,
5898
7135
  "moonshotai/kimi-k2.5": 0.5,
5899
7136
  "moonshotai/kimi-k2.6": 0.1684,
5900
7137
  "moonshotai/kimi-k2.7": 0.2,
5901
7138
  "moonshotai/kimi-k3": 0.1,
7139
+ "moonshotai/kimi-k3.1": 0.1,
5902
7140
  "muse-spark-1.3": 0.12,
5903
7141
  "qwen/qwen3-235b-a22b-2507": 0.5,
5904
7142
  "qwen/qwen3-30b-a3b-instruct-2507": 0.1684,
@@ -5910,7 +7148,7 @@ prices='{
5910
7148
  "qwen/qwen3.7-plus": 0.2,
5911
7149
  "qwen/qwen3.8-max": 0.125,
5912
7150
  "xiaomi/mimo-v2.5-pro": 0.1,
5913
- "xiaomi/mimo-v2.6-flash": 0.02,
7151
+ "xiaomi/mimo-v2.6-flash": 0.015384615384615385,
5914
7152
  "xiaomi/mimo-v2.6-pro": 0.00827586,
5915
7153
  "z-ai/glm-5": 0.2,
5916
7154
  "z-ai/glm-5.1": 0.18571428571428572,
@@ -5921,24 +7159,14 @@ prices='{
5921
7159
  }'
5922
7160
  # END_GENERATED_PRICES
5923
7161
 
5924
- routed=""
5925
- forced="false"
5926
- forced_model=""
5927
- session_savings=""
5928
- tot_in=0
5929
- tot_out=0
5930
- tot_cache_read=0
5931
- tot_cache_write=0
5932
-
5933
- # Per-turn savings compare each turn's routed cost (priced from
5934
- # message.model in the transcript) against what the CC-side model selection
5935
- # (selected_display) would have cost on the same tokens. The selection
5936
- # isn't strictly the per-turn "requested" model — CC tags some background
5937
- # side-calls (compaction probes, title-gen) with a different model id —
5938
- # but for those the planner short-circuits to a hard pin and the savings
5939
- # math zeroes out anyway. Turns where routed == selection or where either
5940
- # model isn't in the pricing table emit 0 savings; the tokens clause
5941
- # always renders.
7162
+ transcript_model=""
7163
+ has_pin_record="false"
7164
+ last_pin_model=""
7165
+ session_cost_difference=""
7166
+
7167
+ # This is a hypothetical comparison against the CURRENT selection, not
7168
+ # realized router savings: the transcript does not record each turn's
7169
+ # requested model or prove that any turn went through the router.
5942
7170
 
5943
7171
  # Normalize the CC-side selection once for use in the jq math below.
5944
7172
  requested_norm="$(normalize_model "$selected_display")"
@@ -5952,62 +7180,52 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
5952
7180
  # locally (errored requests, cancellations, tool-only stubs) instead of a
5953
7181
  # real model id. Show that as "failure" rather than leaking the internal
5954
7182
  # sentinel into the statusline.
5955
- routed="$("${reverse[@]}" "$transcript_path" 2>/dev/null \
7183
+ transcript_model="$("${reverse[@]}" "$transcript_path" 2>/dev/null \
5956
7184
  | jq -r 'select(.type=="assistant") | .message.model // empty' \
5957
7185
  | head -n 1 || true)"
5958
- if [[ "$routed" == "<synthetic>" ]]; then
5959
- routed="failure"
7186
+ if [[ "$transcript_model" == "<synthetic>" ]]; then
7187
+ transcript_model="failure"
5960
7188
  else
5961
- routed="$(normalize_model "$routed")"
5962
- fi
5963
-
5964
- # Detect an active /force-model pin from the router's synthetic ack turns —
5965
- # the only turns stamped message.model == "weave-router". The router emits
5966
- # one whenever a pin changes state:
5967
- # * /force-model → "force-model applied: <model> (<provider>) …"
5968
- # * /unforce-model → "force-model cleared …"
5969
- # * loop / no-progress break → "… clearing the session pin …" (expires the
5970
- # pin, including a user-forced one)
5971
- # * unrecognized model → "… isn't a recognized model · keeping
5972
- # automatic routing" — a NO-OP: the prior
5973
- # pin, if any, is left untouched
5974
- # * listing (historical) → "… pick a model by id …" / "no models are
5975
- # available to pin …" — also NO-OPs. The
5976
- # router no longer emits these, but a
5977
- # transcript written while it did still
5978
- # carries them, and they must not read as
5979
- # a clear or a live pin loses its [forced]
5980
- # These persist on disk (the ingress stripper only scrubs them from upstream
5981
- # requests). Classify each weave-router turn newest-first, skip the no-op
5982
- # "rejected" acks, and let the latest real state change decide: an "applied"
5983
- # marker means the session is pinned (and names the model); anything else
5984
- # (cleared / loop-break / no-progress) means automatic routing has resumed.
5985
- # Restricting to weave-router turns keeps a normal reply that merely quotes
5986
- # these phrases from flipping the tag. (A silent server-side TTL expiry emits
5987
- # no turn and so can't be reflected here — the pin TTL outlives a session.)
5988
- force_state="$("${reverse[@]}" "$transcript_path" 2>/dev/null \
5989
- | jq -r 'select(.type=="assistant" and .message.model=="weave-router")
5990
- | ([.message.content[]? | select(.type? == "text") | .text] | join(" ") | gsub("[\n\r]"; " ")) as $t
5991
- | if ($t | test("force-model applied:")) then "APPLIED " + ($t | capture("force-model applied: (?<m>[^ ]+)").m)
5992
- elif ($t | test("isn.t a recognized model")) then "REJECTED"
5993
- elif ($t | test("pick a model by id|no models are available to pin")) then "REJECTED"
5994
- else "CLEARED" end' 2>/dev/null \
5995
- | grep -m1 -v '^REJECTED$' || true)"
7189
+ transcript_model="$(normalize_model "$transcript_model")"
7190
+ fi
7191
+
7192
+ # Fold acknowledged transitions in transcript order. Content-block copies and
7193
+ # replayed outcome IDs are the same event, not a newer state change.
7194
+ force_state="$(jq -nRr '
7195
+ def model: type == "string" and test("^[A-Za-z0-9._:/-]{1,128}$");
7196
+ def valid_command_outcome:
7197
+ try (.version == 1 and (.id | 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}$"))
7198
+ and (.command | IN("force_model", "router_session", "router_models", "router_feedback", "loop_stop"))
7199
+ and (.disposition | IN("accepted", "rejected"))
7200
+ and (.pin.transition | IN("unchanged", "applied", "cleared"))
7201
+ and (if .pin.transition == "unchanged" then true else
7202
+ .command == "force_model" and .disposition == "accepted" end)
7203
+ and (if .pin.transition == "applied" then (.pin.model | model)
7204
+ and (.pin.provider | model)
7205
+ and ((.pin.effort // "") | type == "string" and test("^[A-Za-z0-9_-]{0,32}$")) else true end)) catch false;
7206
+ reduce (inputs | fromjson? | objects) as $entry ({seen:{}, pin:null};
7207
+ if $entry.type != "assistant" or $entry.message.model != "weave-router" then .
7208
+ elif ($entry.message | has("router_command")) then
7209
+ $entry.message.router_command as $o |
7210
+ if ($o | valid_command_outcome) and (.seen[$o.id] != true) then
7211
+ .seen[$o.id] = true |
7212
+ if $o.pin.transition == "applied" then
7213
+ .pin = ($o.pin.model + (if ($o.pin.effort // "") == "" then "" else ":" + $o.pin.effort end))
7214
+ elif $o.pin.transition == "cleared" then .pin = null else . end
7215
+ else . end
7216
+ else
7217
+ ([$entry.message.content[]? | select(.type? == "text") | .text] | join(" ") | sub("^(?:✦ \\*\\*Weave Router\\*\\* →|Weave Router:)[[:space:]]*"; "")) as $t |
7218
+ if ($t | test("^force-(model|parent) applied: [A-Za-z0-9._:/-]+")) then
7219
+ .pin = ($t | capture("force-(?:model|parent) applied: (?<m>[A-Za-z0-9._:/-]+)").m)
7220
+ elif ($t | test("^force-model cleared\\b")) then .pin = null else . end
7221
+ end) | if .pin then "APPLIED " + .pin else "CLEARED" end
7222
+ ' "$transcript_path" 2>/dev/null || true)"
5996
7223
  if [[ "$force_state" == APPLIED\ * ]]; then
5997
- forced="true"
5998
- forced_model="${force_state#APPLIED }"
7224
+ has_pin_record="true"
7225
+ last_pin_model="${force_state#APPLIED }"
5999
7226
  fi
6000
7227
 
6001
- # Compute a session running total: savings across every assistant turn
6002
- # whose marker reports a requested ≠ routed swap, plus cumulative token
6003
- # counts across every assistant turn (rerouted or not — total work the
6004
- # session has done). cache_creation is priced at 1.25× input; cache_read
6005
- # uses each model's generated catalog multiplier. Both are no-ops when the
6006
- # provider does not return those fields.
6007
- #
6008
- # The marker regex tolerates the optional "(<provider>)" segment and a
6009
- # `[1m]` / `-YYYYMMDD` suffix on either model name so transcripts written
6010
- # against context-tiered or dated model ids still parse cleanly.
7228
+ # Missing prices leave the comparison unknown without hiding the model.
6011
7229
  #
6012
7230
  # Dedup note: CC writes one JSONL entry per *content block* in an
6013
7231
  # assistant turn (text, text, tool_use → 3 entries), and every entry
@@ -6021,9 +7239,9 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
6021
7239
  # grows), so the composite key keeps turns distinct. Two turns with
6022
7240
  # byte-identical id AND usage would still collapse, but that's a
6023
7241
  # genuine retry/duplicate we want to drop.
6024
- read -r session_savings tot_in tot_out tot_cache_read tot_cache_write < <(
7242
+ session_cost_difference="$(
6025
7243
  jq -rs --argjson p "$prices" --arg requested "$requested_norm" '
6026
- [.[] | select(.type=="assistant")] |
7244
+ [.[] | select(.type=="assistant" and .message.model!="<synthetic>" and .message.model!="weave-router")] |
6027
7245
  unique_by([.message.id, .message.usage]) |
6028
7246
  .[] |
6029
7247
  .message as $m |
@@ -6034,13 +7252,13 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
6034
7252
  cwrt: ($m.usage.cache_creation_input_tokens // 0),
6035
7253
  crd: ($m.usage.cache_read_input_tokens // 0)
6036
7254
  } as $t |
6037
- (if $requested == "" or $requested == $rm then 0
7255
+ (if ($t.in + $t.out + $t.cwrt + $t.crd) == 0 then 0
6038
7256
  else
6039
7257
  ($p.input[$rm] // null) as $rin | ($p.output[$rm] // null) as $rout |
6040
7258
  ($p.cache_read[$rm] // null) as $rcr |
6041
7259
  ($p.input[$requested] // null) as $sin | ($p.output[$requested] // null) as $sout |
6042
7260
  ($p.cache_read[$requested] // null) as $scr |
6043
- if ($rin == null or $rout == null or $rcr == null or $sin == null or $sout == null or $scr == null) then 0
7261
+ if ($rin == null or $rout == null or $rcr == null or $sin == null or $sout == null or $scr == null) then null
6044
7262
  else
6045
7263
  (($t.in + 1.25 * $t.cwrt + $rcr * $t.crd) / 1000) as $routed_input_units |
6046
7264
  (($t.in + 1.25 * $t.cwrt + $scr * $t.crd) / 1000) as $requested_input_units |
@@ -6050,21 +7268,20 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
6050
7268
  ($requested_cost - $routed_cost)
6051
7269
  end
6052
7270
  end) as $savings |
6053
- "\($savings) \($t.in) \($t.out) \($t.crd) \($t.cwrt)"
7271
+ if $savings == null then "unknown" else $savings end
6054
7272
  ' "$transcript_path" 2>/dev/null \
6055
- | awk 'BEGIN{s=0; i=0; o=0; r=0; w=0}
6056
- {s+=$1; i+=$2; o+=$3; r+=$4; w+=$5}
6057
- END{printf "%.4f %d %d %d %d\n", s, i, o, r, w}'
6058
- ) || true
7273
+ | awk 'BEGIN{s=0}
7274
+ {if ($1 == "unknown") comparison_unknown=1; else s+=$1}
7275
+ END{
7276
+ if (NR == 0 || comparison_unknown) printf "unknown"; else printf "%.4f", s;
7277
+ }'
7278
+ )" || true
6059
7279
  fi
6060
7280
 
6061
7281
  # ---------- refresh when a model isn't in the pricing table ----------
6062
7282
  #
6063
- # A model that shipped after this copy of the script has no price entry, so the
6064
- # jq guard above zeroes savings on every turn and the line reads "saved $0.00"
6065
- # — indistinguishable from "the router ran and didn't beat your selection". The
6066
- # periodic check heals that eventually, but a week late, and a model launch is
6067
- # exactly when the number gets looked at. Refresh off-schedule instead.
7283
+ # A model missing from this copy's price table cannot be compared. Refresh
7284
+ # off-schedule instead of waiting up to a week for the periodic check.
6068
7285
  #
6069
7286
  # Keyed on its own stamp per unpriced id: a model we never price (self-hosted,
6070
7287
  # unrecognized) then costs one download per interval, not one per turn, and
@@ -6092,85 +7309,176 @@ weave_refresh_on_price_miss() {
6092
7309
  model_slug="$(printf '%s' "$missing" | tr -c 'A-Za-z0-9._-' '_')"
6093
7310
  weave_self_refresh ".miss.${model_slug}" 1
6094
7311
  }
6095
- weave_refresh_on_price_miss "$requested_norm" "$routed" 2>/dev/null || true
7312
+ weave_refresh_on_price_miss "$requested_norm" "$transcript_model" 2>/dev/null || true
7313
+
7314
+ router_context_fallback() {
7315
+ [ -z "$context_clause" ] || return 0
7316
+ [ "${WEAVE_STATUSLINE_CONTEXT:-1}" != "0" ] || return 0
7317
+ local session helper_dir scope cache root now snapshot
7318
+ session="$(jq -r '.session_id // empty' <<<"$input")"
7319
+ case "$session" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
7320
+ [ "${#session}" -le 128 ] || return 0
7321
+ helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
7322
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
7323
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-context"
7324
+ cache="$root/$scope-$session.json"
7325
+ mkdir -p "$root" 2>/dev/null || return 0
7326
+ chmod 700 "$root"
7327
+ local generation active_file
7328
+ active_file="$cache.active"
7329
+ now="$(date +%s)"
7330
+ if [ -f "$cache" ] && [ "$(wc -c <"$cache")" -le 8192 ]; then
7331
+ snapshot="$(jq -ce --arg session "$session" --argjson now "$now" '
7332
+
7333
+ def tokens: type == "number" and floor == . and . > 0 and . <= 2147483647;
7334
+ def epoch: sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601;
7335
+ .context_snapshot as $s |
7336
+ select(.session_id == $session and $s.version == 1 and $s.estimate_kind == "approximate") |
7337
+ select(($s.estimate_tokens | tokens) and ($s.context_window | tokens) and ($s.output_reserve_tokens | tokens)) |
7338
+ select(($s.served_model | type) == "string" and ($s.served_model | test("^[A-Za-z0-9._:/-]{1,128}$"))) |
7339
+ select(($s.request_id | type) == "string" and ($s.request_id | length) > 0 and ($s.request_id | length) <= 128) |
7340
+ ($s.recorded_at | epoch) as $recorded | ($s.requested_at | epoch) as $requested |
7341
+ select($requested > 0 and $requested <= $recorded and $recorded <= $now and $now - $recorded <= 300) |
7342
+ $s
7343
+ ' "$cache" 2>/dev/null)" || snapshot=""
7344
+ if [ -n "$snapshot" ]; then
7345
+ local served requested
7346
+ served="$(normalize_model "$(jq -r '.served_model' <<<"$snapshot")")"
7347
+ requested="$(normalize_model "$(jq -r '.requested_model // empty' <<<"$snapshot")")"
7348
+ if [ "$served" = "$transcript_model" ] && [ "$requested" = "$requested_norm" ]; then
7349
+ context_clause="$(awk -v e="$(jq -r '.estimate_tokens' <<<"$snapshot")" -v w="$(jq -r '.context_window' <<<"$snapshot")" 'BEGIN {
7350
+ printf " · last Router ctx est. ~%s/%s", (e < 1000 ? e : sprintf("%.0fk", e/1000)), (w < 1000 ? w : sprintf("%.0fk", w/1000))
7351
+ }')"
7352
+ fi
7353
+ fi
7354
+ fi
7355
+ command -v curl >/dev/null 2>&1 || return 0
7356
+ mkdir -p "$root" 2>/dev/null || return 0
7357
+ chmod 700 "$root"
7358
+ (
7359
+ exec </dev/null
7360
+ # Serialize refreshes; a timeout cannot delay the status-line process.
7361
+ if ! mkdir "$cache.lock" 2>/dev/null; then
7362
+ lock_mtime="$(stat -c %Y "$cache.lock" 2>/dev/null || stat -f %m "$cache.lock" 2>/dev/null)" || lock_mtime=0
7363
+ [ $(( $(date +%s) - lock_mtime )) -gt 30 ] || exit 0
7364
+ dead="$cache.lock.dead.$$"
7365
+ mv "$cache.lock" "$dead" 2>/dev/null || exit 0
7366
+ rm -rf "$dead"
7367
+ mkdir "$cache.lock" 2>/dev/null || exit 0
7368
+ fi
7369
+ trap 'rmdir "$cache.lock" 2>/dev/null' EXIT
7370
+ generation="$(mktemp "$root/.generation.XXXXXX")" || exit 0
7371
+ printf '%s' "$generation" >"$generation"
7372
+ chmod 600 "$generation"
7373
+ mv "$generation" "$active_file"
7374
+ settings_base="$HOME"
7375
+ case "$helper_dir" in */.claude) settings_base="${helper_dir%/.claude}" ;; esac
7376
+ settings="$settings_base/.claude/settings.json"
7377
+ local_settings="$settings_base/.claude/settings.local.json"
7378
+ base=""
7379
+ key=""
7380
+ for settings_file in "$settings" "$local_settings"; do
7381
+ [ -f "$settings_file" ] || continue
7382
+ if jq -e '.env | has("ANTHROPIC_BASE_URL")' "$settings_file" >/dev/null 2>&1; then
7383
+ base="$(jq -r '.env.ANTHROPIC_BASE_URL // empty' "$settings_file" 2>/dev/null)"
7384
+ fi
7385
+ if jq -e '.env | has("ANTHROPIC_CUSTOM_HEADERS")' "$settings_file" >/dev/null 2>&1; then
7386
+ key="$(jq -r '.env.ANTHROPIC_CUSTOM_HEADERS // "" | split("\n")[] | select(startswith("X-Weave-Router-Key:")) | sub("^X-Weave-Router-Key:[[:space:]]*"; "")' "$settings_file" 2>/dev/null | head -n1)"
7387
+ fi
7388
+ done
7389
+ base="${WEAVE_ROUTER_BASE_URL:-${ANTHROPIC_BASE_URL:-$base}}"
7390
+ key="${WEAVE_ROUTER_KEY:-$key}"
7391
+ [ -n "$base" ] && [ -n "$key" ] || exit 0
7392
+ url="${base%/}"
7393
+ case "$url" in file://*) ;; *) url="${url%/v1}/v1/sessions/$session/cost" ;; esac
7394
+ tmp="$(mktemp "$root/.snapshot.XXXXXX")" || exit 0
7395
+ header_file="$(mktemp "$root/.headers.XXXXXX")" || { rm -f "$tmp"; exit 0; }
7396
+ chmod 600 "$tmp"
7397
+ chmod 600 "$header_file"
7398
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
7399
+ if curl -fsS --max-time 5 --max-filesize 8192 -K "$header_file" "$url" -o "$tmp" 2>/dev/null \
7400
+ && [ "$(wc -c <"$tmp")" -le 8192 ] \
7401
+ && [ "$(jq -r '.session_id // empty' "$tmp" 2>/dev/null)" = "$session" ]; then
7402
+ # Request observation order is independent of fetch completion order.
7403
+ # Fraction padding preserves RFC3339Nano order within the same second.
7404
+ previous="$cache"
7405
+ [ -f "$previous" ] || previous=/dev/null
7406
+ if [ "$(cat "$active_file" 2>/dev/null)" = "$generation" ] && jq -e -s '
7407
+ def timestamp_parts: split(".") as $p |
7408
+ [($p[0] | sub("Z$"; "")), ((($p[1] // "") | sub("Z$"; "")) + "000000000")[0:9]];
7409
+ def observation: [.context_snapshot.requested_at | timestamp_parts] + [.context_snapshot.recorded_at | timestamp_parts];
7410
+ (.[0] | observation) as $fresh |
7411
+ if length == 1 or .[1].context_snapshot == null then true else $fresh > (.[1] | observation) or ($fresh == (.[1] | observation) and .[0].context_snapshot.request_id == .[1].context_snapshot.request_id) end
7412
+ ' "$tmp" "$previous" 2>/dev/null; then
7413
+ mv "$tmp" "$cache"
7414
+ fi
7415
+ fi
7416
+ rm -f "$tmp" "$header_file"
7417
+ ) >/dev/null 2>&1 &
7418
+ disown 2>/dev/null || true
7419
+ }
7420
+ router_context_fallback 2>/dev/null || true
6096
7421
 
6097
7422
  # Brand color (#FF6C47) on terminals that grok 24-bit truecolor — that's
6098
7423
  # every modern one (iTerm2, Apple Terminal, vscode, ghostty, alacritty,
6099
7424
  # wezterm, kitty). Falls back gracefully on any escape-stripping terminal.
6100
7425
  brand=$'\033[38;2;255;108;71mWEAVE ROUTER\033[0m'
6101
7426
 
6102
- # Format helpers.
6103
- fmt_money() {
6104
- awk -v v="$1" 'BEGIN{
6105
- if (v == "" || v+0 == 0) { printf "$0.00"; exit }
6106
- if (v+0 < 0.005 && v+0 > -0.005){ printf "<$0.01"; exit }
6107
- if (v+0 < 0) { printf "-$%.2f", -v+0; exit }
6108
- printf "$%.2f", v
6109
- }'
6110
- }
6111
7427
 
6112
- fmt_tok() {
6113
- awk -v v="$1" 'BEGIN{
6114
- v = v+0
6115
- if (v >= 1000000) { printf "%.1fM", v/1000000; exit }
6116
- if (v >= 1000) { printf "%.1fk", v/1000; exit }
6117
- printf "%d", v
6118
- }'
6119
- }
6120
-
6121
- # cache_read tokens are the cached portion of every prompt that the
6122
- # provider serves at 0.1× input price; cache_write tokens are the bytes
6123
- # that get newly cached on this turn at 1.25× input price. They behave
6124
- # completely differently both in cost and in what they tell the user
6125
- # about session-level efficiency, so we surface them separately rather
6126
- # than summing into a single "cached" number that conflates the two.
6127
- # Each clause is shown only when nonzero, so quiet sessions stay quiet.
6128
- tokens_clause=""
6129
- if [[ "$tot_in" -gt 0 || "$tot_out" -gt 0 || "$tot_cache_read" -gt 0 || "$tot_cache_write" -gt 0 ]]; then
6130
- tokens_clause=" · $(fmt_tok "$tot_in") in / $(fmt_tok "$tot_out") out"
6131
- if [[ "$tot_cache_read" -gt 0 ]]; then
6132
- tokens_clause+=" / $(fmt_tok "$tot_cache_read") cache read"
6133
- fi
6134
- if [[ "$tot_cache_write" -gt 0 ]]; then
6135
- tokens_clause+=" / $(fmt_tok "$tot_cache_write") cache write"
6136
- fi
7428
+ # "you picked" is Claude Code's selection; "served" is the latest response
7429
+ # model in the transcript. The cost clause is the whole session priced at the
7430
+ # served models versus the pick, so an upgrade reads as "more", not a negative
7431
+ # saving.
7432
+ short_model() { printf '%s' "${1#claude-}"; }
7433
+ picked=""
7434
+ if [[ -n "$selected_display" && "$selected_display" != "?" ]]; then
7435
+ picked="$(short_model "$requested_norm")"
6137
7436
  fi
6138
-
6139
- if [[ "$forced" == "true" ]]; then
6140
- # Session is pinned via /force-model. The "← selection · saved $X" clause
6141
- # describes automatic routing and would be misleading on a manual pin, so
6142
- # show the pinned model with a [forced] tag instead. forced_model comes from
6143
- # the marker; fall back to the routed/selected id if parsing came up empty.
6144
- forced_display="${forced_model:-${routed:-$selected_display}}"
6145
- printf '%s — %s [forced]%s' "$brand" "$forced_display" "$tokens_clause"
6146
- elif [[ "$routed" == "failure" ]]; then
6147
- # Latest turn was a CC-synthesized error stub — don't claim a routing
6148
- # swap or compute savings against a non-model.
6149
- printf '%s — %s%s' "$brand" "$routed" "$tokens_clause"
6150
- elif [[ -n "$routed" ]]; then
6151
- # Always show the savings clause, flooring a non-positive total at $0.00.
6152
- # session_savings is "0.0000" on fresh sessions or sessions where every
6153
- # turn routed back to the selected model, and can go negative when routing
6154
- # upgrades a turn to a pricier model (e.g. a sticky/hard-pinned side-call,
6155
- # or a hard turn escalated to opus). "saved -$X" would mislead, so clamp
6156
- # the display to $0.00 rather than dropping the clause — a $0.00 readout
6157
- # tells the user the router ran and simply didn't beat their selection.
6158
- # When the CC selection is unknown ("?" or empty) there's nothing to
6159
- # compare against, so drop the "← selection" arrow and just show routed.
6160
- display_savings="$session_savings"
6161
- if [[ -z "$display_savings" ]] \
6162
- || awk -v v="$display_savings" 'BEGIN{exit !(v+0 < 0)}'; then
6163
- display_savings="0"
6164
- fi
6165
- if [[ -n "$selected_display" && "$selected_display" != "?" ]]; then
6166
- printf '%s — %s ← %s · saved %s%s' \
6167
- "$brand" "$routed" "$selected_display" "$(fmt_money "$display_savings")" "$tokens_clause"
7437
+ status_text=""
7438
+ if [[ "$transcript_model" == "failure" ]]; then
7439
+ status_text=" · last response failed"
7440
+ elif [[ "$transcript_model" == "weave-router" ]]; then
7441
+ status_text=" · control acknowledgement"
7442
+ elif [[ -n "$transcript_model" ]]; then
7443
+ if [[ -n "$picked" && "$transcript_model" != "$requested_norm" ]]; then
7444
+ status_text=" · you picked $picked → served $(short_model "$transcript_model")"
6168
7445
  else
6169
- printf '%s — %s%s' "$brand" "$routed" "$tokens_clause"
7446
+ status_text=" · served $(short_model "$transcript_model")"
6170
7447
  fi
6171
- else
6172
- printf '%s — %s%s' "$brand" "$selected_display" "$tokens_clause"
7448
+ elif [[ -n "$picked" ]]; then
7449
+ status_text=" · you picked $picked"
7450
+ fi
7451
+ if [[ -n "$session_cost_difference" && "$session_cost_difference" != "unknown" && "$transcript_model" != "failure" && "$transcript_model" != "weave-router" ]]; then
7452
+ status_text="$status_text$(awk -v v="$session_cost_difference" -v pick="$picked" 'BEGIN{
7453
+ v = v + 0
7454
+ if (v >= 0.005) printf " · saved ~$%.2f this session", v
7455
+ else if (v > 0) printf " · saved <$0.01 this session"
7456
+ else if (v == 0) printf " · no savings yet this session"
7457
+ else if (v > -0.005) printf " · cost <$0.01 more than %s this session", pick
7458
+ else printf " · cost ~$%.2f more than %s this session (upgraded hard turns)", -v, pick
7459
+ }')"
6173
7460
  fi
7461
+ if [[ "$has_pin_record" == "true" ]]; then
7462
+ status_text="$status_text · last pin: $last_pin_model"
7463
+ fi
7464
+
7465
+ # /router-status reads this back through the prompt hook, so it can answer
7466
+ # without a model turn.
7467
+ weave_cache_status_line() {
7468
+ local session root
7469
+ session="$(jq -r '.session_id // empty' <<<"$input")"
7470
+ case "$session" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
7471
+ [ "${#session}" -le 128 ] || return 0
7472
+ [ -n "$transcript_model" ] || return 0
7473
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-status"
7474
+ mkdir -p "$root" && chmod 700 "$root" || return 0
7475
+ printf '%s\n' "${status_text# · }" >"$root/$session.line.$$" \
7476
+ && mv -f "$root/$session.line.$$" "$root/$session.line"
7477
+ }
7478
+ weave_cache_status_line 2>/dev/null || true
7479
+
7480
+ printf '%s%s' "$brand" "$status_text"
7481
+ printf '%s' "$context_clause"
6174
7482
  STATUSLINE_EOF
6175
7483
  chmod +x "$statusline_file"
6176
7484
  printf '%s\n' "$CLAUDE_STATUSLINE_MARKER" >"$statusline_ownership_file"
@@ -6215,22 +7523,28 @@ write_claude_settings() {
6215
7523
  # Setting ANTHROPIC_BASE_URL makes Claude Code treat us as non-first-party.
6216
7524
  # Force tool-search deferral to match first-party Claude Code; "auto" can inline
6217
7525
  # every tool schema when the custom endpoint advertises a 200K context window.
7526
+ local prompt_hook_scope=""
7527
+ if [ -n "$install_dir" ]; then
7528
+ prompt_hook_scope=" --dir $(printf '%q' "$install_dir")"
7529
+ elif [ "$scope" = "project" ]; then
7530
+ prompt_hook_scope=" --scope project"
7531
+ fi
6218
7532
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
6219
- jq -n --arg url "$base_url" --arg sl "$statusline_path_for_settings" --arg statusline_install "$statusline_install" '{
6220
- env: { ANTHROPIC_BASE_URL: $url, ENABLE_TOOL_SEARCH: "true" },
6221
- attribution: {
7533
+ jq -n --arg attribution "$attribution" --arg url "$base_url" --arg sl "$statusline_path_for_settings" --arg prompt_hook_scope "$prompt_hook_scope" --arg statusline_install "$statusline_install" '{
7534
+ env: { ANTHROPIC_BASE_URL: $url, ENABLE_TOOL_SEARCH: "true" }
7535
+ } + (if $attribution == "true" then {attribution: {
6222
7536
  commit: "Co-Authored-By: Weave Router <router@weaveos.com>",
6223
7537
  pr: "🤖 Generated with [Weave Router](https://router.workweave.ai)"
6224
- }
6225
- } + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl }} else {} end)' >"$tmp_patch"
7538
+ }} else {} end) + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl },
7539
+ hooks: {UserPromptSubmit: [{hooks: [{type: "command", command: ("[ ! -x \"" + $sl + "\" ] || \"" + $sl + "\" --prompt-hook" + $prompt_hook_scope)}]}]}} else {} end)' >"$tmp_patch"
6226
7540
  else
6227
- jq -n --arg url "$base_url" --arg header "$custom_headers" --arg sl "$statusline_path_for_settings" --arg statusline_install "$statusline_install" '{
6228
- env: { ANTHROPIC_BASE_URL: $url, ANTHROPIC_CUSTOM_HEADERS: $header, ENABLE_TOOL_SEARCH: "true" },
6229
- attribution: {
7541
+ jq -n --arg attribution "$attribution" --arg url "$base_url" --arg header "$custom_headers" --arg sl "$statusline_path_for_settings" --arg prompt_hook_scope "$prompt_hook_scope" --arg statusline_install "$statusline_install" '{
7542
+ env: { ANTHROPIC_BASE_URL: $url, ANTHROPIC_CUSTOM_HEADERS: $header, ENABLE_TOOL_SEARCH: "true" }
7543
+ } + (if $attribution == "true" then {attribution: {
6230
7544
  commit: "Co-Authored-By: Weave Router <router@weaveos.com>",
6231
7545
  pr: "🤖 Generated with [Weave Router](https://router.workweave.ai)"
6232
- }
6233
- } + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl }} else {} end)' >"$tmp_patch"
7546
+ }} else {} end) + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl },
7547
+ hooks: {UserPromptSubmit: [{hooks: [{type: "command", command: ("[ ! -x \"" + $sl + "\" ] || \"" + $sl + "\" --prompt-hook" + $prompt_hook_scope)}]}]}} else {} end)' >"$tmp_patch"
6234
7548
  fi
6235
7549
 
6236
7550
  # Merge with existing settings. Deep-merge env and replace statusLine only
@@ -6248,13 +7562,29 @@ write_claude_settings() {
6248
7562
  | (if (.env | length) == 0 then del(.env) else . end)
6249
7563
  | del(.apiKeyHelper)
6250
7564
  | (if $b.statusLine then .statusLine = $b.statusLine else . end)
6251
- | (if $b.attribution then .attribution = $b.attribution else . end)
7565
+ | (if $b.hooks then .hooks = ((.hooks // {})
7566
+ | .UserPromptSubmit = (((.UserPromptSubmit // [])
7567
+ | map(if (.hooks | type) == "array" then .hooks |= map(select((.command // "" | tostring | test("cc-statusline\\.sh\"? --prompt-hook( |$)")) | not)) else . end) | map(select((.hooks | type) != "array" or (.hooks | length) > 0)))
7568
+ + $b.hooks.UserPromptSubmit))
7569
+ else . end)
7570
+ | (($a.attribution.commit // "") | startswith("Co-Authored-By: Weave Router")) as $ours
7571
+ | (($a.env // {} | has("ANTHROPIC_BASE_URL")) and $a.attribution == null) as $opted_out
7572
+ | (if $b.attribution and ($ours or ($a.attribution == null and ($opted_out | not)))
7573
+ then .attribution = $b.attribution
7574
+ elif ($b.attribution | not) and $ours then
7575
+ .attribution |= (del(.commit)
7576
+ | if .pr == "🤖 Generated with [Weave Router](https://router.workweave.ai)" then del(.pr) else . end)
7577
+ | (if (.attribution | length) == 0 then del(.attribution) else . end)
7578
+ else . end)
6252
7579
  ' "$settings_file" "$tmp_patch")"
6253
7580
  printf '%s\n' "$merged" >"$settings_file"
6254
7581
  else
6255
7582
  cp "$tmp_patch" "$settings_file"
6256
7583
  fi
6257
7584
  ok "Settings written to $settings_file"
7585
+ if [ "$quiet" != "true" ] && jq -e '(.attribution.commit // "") | startswith("Co-Authored-By: Weave Router")' "$settings_file" >/dev/null 2>&1; then
7586
+ info "Claude Code will credit Weave Router in commits (Co-Authored-By) and PR descriptions. To turn this off, re-run with --no-attribution."
7587
+ fi
6258
7588
 
6259
7589
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
6260
7590
  jq -n --arg header "$custom_headers" --arg router_url "$base_url" '{
@@ -6333,4 +7663,4 @@ verify_install
6333
7663
  # ---------- done ----------
6334
7664
 
6335
7665
  announce_done "Claude Code"
6336
- [ "$mode" = "update" ] || print_uninstall_hint
7666
+ finish_install "Claude Code" claude