@weave-os/router 0.2.29 → 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
@@ -126,6 +130,7 @@ email_explicit="false"
126
130
  return_url=""
127
131
  non_interactive="false"
128
132
  quiet="false"
133
+ attribution="true"
129
134
  router_key_header="X-Weave-Router-Key"
130
135
  # Target tool whose config we patch. "claude" (default) writes Claude Code
131
136
  # settings.json; "codex" writes ~/.codex/config.toml; "opencode" merges a
@@ -137,6 +142,10 @@ router_key_header="X-Weave-Router-Key"
137
142
  # prompt for the choice.
138
143
  target="claude"
139
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"
140
149
 
141
150
  # Operation mode. "install" (default) writes/refreshes config. "update" is a
142
151
  # never-prompting install that reuses the key already on disk. "off"/"on"/
@@ -155,6 +164,7 @@ setup_codex="false"
155
164
  # `set -u` would not. --json switches the output to the raw API payload.
156
165
  models_args=""
157
166
  models_json="false"
167
+ models_auto_target="false"
158
168
 
159
169
  # --lsp <langs>: comma-separated languages whose language servers to install
160
170
  # for the pi extension's `lsp` tool (pi target only). Empty = don't install any.
@@ -168,6 +178,11 @@ rotate_key="false"
168
178
  api_key_source=""
169
179
  # Set by verify_install; a return URL is opened only after both probes pass.
170
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=""
171
186
 
172
187
  # ---------- helpers ----------
173
188
 
@@ -215,6 +230,7 @@ uninstall_cmd() {
215
230
  codex) cmd="$cmd --codex" ;;
216
231
  opencode) cmd="$cmd --opencode" ;;
217
232
  pi) cmd="$cmd --pi" ;;
233
+ copilot) cmd="$cmd --copilot" ;;
218
234
  esac
219
235
  [ "$scope" = "project" ] && cmd="$cmd --scope project"
220
236
  [ -n "$install_dir" ] && cmd="$cmd --dir $(printf '%q' "$install_dir")"
@@ -229,6 +245,25 @@ print_uninstall_hint() {
229
245
  "$C_BOLD" "$C_RESET" "$C_CYAN" "$(uninstall_cmd)" "$C_RESET"
230
246
  }
231
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
+
232
267
  # ---------- banner ----------
233
268
  #
234
269
  # Print the WEAVE wordmark in brand orange. Skipped under --quiet or when
@@ -241,6 +276,7 @@ print_banner() {
241
276
  codex) target_label="Codex installer" ;;
242
277
  opencode) target_label="opencode installer" ;;
243
278
  pi) target_label="pi installer" ;;
279
+ copilot) target_label="GitHub Copilot CLI installer" ;;
244
280
  *) target_label="Claude Code installer" ;;
245
281
  esac
246
282
  printf '\n'
@@ -285,6 +321,9 @@ _spin_cleanup() {
285
321
  if [ -n "$spin_log" ]; then
286
322
  rm -f "$spin_log" 2>/dev/null || true
287
323
  fi
324
+ if [ -n "${validate_status_file:-}" ]; then
325
+ rm -f "$validate_status_file" 2>/dev/null || true
326
+ fi
288
327
  # Also restore stty echo in case we died mid-keypaste prompt. macOS
289
328
  # `[ -r /dev/tty ]` returns true even when the underlying device errors
290
329
  # on open (ENXIO "Device not configured") under `curl | sh` and CI, so
@@ -348,13 +387,38 @@ spin() {
348
387
  fi
349
388
  }
350
389
 
390
+ # usage is the short, task-grouped help. The comment block at the top of this
391
+ # file is the full reference.
351
392
  usage() {
352
- # Print the leading comment block (lines 2..just-before `set -euo`), stripping
353
- # the leading `# `. awk avoids GNU `head -n -<N>`, which BSD head on macOS
354
- # rejects with "illegal line count -- -N". Banner sits above so `--help`
355
- # gets the same wordmark as a fresh install run.
356
393
  print_banner
357
- 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
358
422
  exit "${1:-0}"
359
423
  }
360
424
 
@@ -454,6 +518,17 @@ claude_statusline_configured() {
454
518
  jq -e 'has("statusLine") and (.statusLine != null)' "$settings_path" >/dev/null 2>&1
455
519
  }
456
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
+
457
532
  # claude_statusline_router_owned reports whether a settings entry points at the
458
533
  # router's statusline. Existing scripts prove ownership with the marker; when a
459
534
  # script is missing, the adjacent ownership marker proves that the router wrote
@@ -462,7 +537,7 @@ claude_statusline_router_owned() {
462
537
  local settings_path="$1" expected_command="$2" script_path="$3" ownership_marker_path="$4" configured_command
463
538
  [ -f "$settings_path" ] || return 1
464
539
  configured_command="$(jq -r '.statusLine.command // empty' "$settings_path" 2>/dev/null || true)"
465
- [ "$configured_command" = "$expected_command" ] || return 1
540
+ statusline_commands_match "$configured_command" "$expected_command" || return 1
466
541
  if [ -f "$script_path" ]; then
467
542
  if grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$script_path" 2>/dev/null; then
468
543
  return 0
@@ -555,6 +630,10 @@ resolve_user_email() {
555
630
  printf '%s' "$candidate"
556
631
  return
557
632
  fi
633
+ if [ "${WEAVE_SETUP_IDENTITY_RESOLVED:-}" = "1" ]; then
634
+ normalize_email "${WEAVE_SETUP_SHARED_EMAIL:-}"
635
+ return
636
+ fi
558
637
  if [ -n "${WEAVE_USER_EMAIL:-}" ]; then
559
638
  candidate="$(normalize_email "$WEAVE_USER_EMAIL")"
560
639
  if [ -z "$candidate" ]; then
@@ -914,10 +993,20 @@ TOML
914
993
  type = "command"
915
994
  command = "${esc_status}"
916
995
 
996
+ [[hooks.UserPromptSubmit]]
997
+ [[hooks.UserPromptSubmit.hooks]]
998
+ type = "command"
999
+ command = "${esc_status}"
1000
+
917
1001
  [[hooks.Stop]]
918
1002
  [[hooks.Stop.hooks]]
919
1003
  type = "command"
920
1004
  command = "${esc_status}"
1005
+
1006
+ [[hooks.PreCompact]]
1007
+ [[hooks.PreCompact.hooks]]
1008
+ type = "command"
1009
+ command = "${esc_status}"
921
1010
  TOML
922
1011
  )${directive_hook_block}"
923
1012
  if [ "${WEAVE_CAPTURE_LLM_CLASSIFIER:-}" = "1" ]; then
@@ -929,10 +1018,6 @@ matcher = "spawn_agent"
929
1018
  type = "command"
930
1019
  command = "${esc_status}"
931
1020
 
932
- [[hooks.PreCompact]]
933
- [[hooks.PreCompact.hooks]]
934
- type = "command"
935
- command = "${esc_status}"
936
1021
  TOML
937
1022
  )"
938
1023
  fi
@@ -1279,10 +1364,12 @@ write_pi_models_config() {
1279
1364
  { id: "claude-sonnet-5-5", name: "Claude Sonnet 5.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 128000 },
1280
1365
  { id: "claude-opus-4-7", name: "Claude Opus 4.7 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 64000 },
1281
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 },
1282
1368
  { id: "claude-haiku-4-5", name: "Claude Haiku 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 200000, maxTokens: 32000 },
1283
1369
  { id: "gpt-6-astra", name: "GPT-6 Astra (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1284
1370
  { id: "gpt-6-sol", name: "GPT-6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1285
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 },
1286
1373
  { id: "gpt-6-luna", name: "GPT-6 Luna (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1287
1374
  { id: "gpt-5.6-sol", name: "GPT-5.6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1288
1375
  { id: "grok-4.5", name: "Grok 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 },
@@ -1425,6 +1512,146 @@ resolve_user_name() {
1425
1512
  printf '%s' "$candidate"
1426
1513
  }
1427
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
+
1428
1655
  # ---------- uninstall delegation ----------
1429
1656
  #
1430
1657
  # `--uninstall` flips this script into a thin shim for uninstall.sh: the
@@ -1519,6 +1746,9 @@ while [ $# -gt 0 ]; do
1519
1746
  --quiet)
1520
1747
  quiet="true"; shift
1521
1748
  ;;
1749
+ --no-attribution)
1750
+ attribution="false"; shift
1751
+ ;;
1522
1752
  --rotate-key)
1523
1753
  rotate_key="true"; shift
1524
1754
  ;;
@@ -1536,6 +1766,14 @@ while [ $# -gt 0 ]; do
1536
1766
  --pi)
1537
1767
  target="pi"; target_explicit="true"; shift
1538
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
+ ;;
1539
1777
  --lsp)
1540
1778
  lsp_langs="${2:-}"; shift 2
1541
1779
  [ -n "$lsp_langs" ] || { err "--lsp requires a comma-separated language list (go,typescript,python,rust)."; exit 2; }
@@ -1627,9 +1865,36 @@ if [ "$mode" = "setup" ]; then
1627
1865
  [ -n "$return_url" ] && setup_args+=(--return-url "$return_url")
1628
1866
  [ -n "$install_dir" ] && setup_args+=(--dir "$install_dir")
1629
1867
  [ "$quiet" = "true" ] && setup_args+=(--quiet)
1868
+ [ "$attribution" = "false" ] && setup_args+=(--no-attribution)
1630
1869
  [ "$rotate_key" = "true" ] && setup_args+=(--rotate-key)
1631
- [ "$setup_claude" = "true" ] && bash "$0" "${setup_args[@]}" --claude
1632
- [ "$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
1633
1898
  exit 0
1634
1899
  fi
1635
1900
 
@@ -1637,6 +1902,15 @@ if [ -n "$return_url" ] && [ "$mode" != "install" ]; then
1637
1902
  err "--return-url is supported only for install (or setup with one explicit target)."
1638
1903
  exit 2
1639
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
1640
1914
 
1641
1915
  # --lsp is a pi-extension feature, so it implies the pi target; combining it
1642
1916
  # with another explicit target is a contradiction, not a preference.
@@ -1667,6 +1941,11 @@ if [ "$mode" = "login" ]; then
1667
1941
  esac
1668
1942
  elif [ "$mode" = "accounts" ] || [ "$mode" = "status" ]; then
1669
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"
1670
1949
  fi
1671
1950
 
1672
1951
  # Toggle verbs only flip config install.sh already wrote: no key, no identity,
@@ -1680,7 +1959,7 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ]; then
1680
1959
  if [ "$mode" = "models" ]; then
1681
1960
  err "'models' requires an explicit client: --claude or --codex."
1682
1961
  else
1683
- err "'$mode' requires an explicit client: --claude, --codex, or --opencode."
1962
+ err "'$mode' requires an explicit client: --claude, --codex, --opencode, or --copilot."
1684
1963
  fi
1685
1964
  exit 2
1686
1965
  fi
@@ -1727,6 +2006,17 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ] && [ "$target" = "pi" ];
1727
2006
  exit 2
1728
2007
  fi
1729
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
+
1730
2020
  if [ -z "$base_url" ]; then
1731
2021
  base_url="$DEFAULT_BASE_URL"
1732
2022
  fi
@@ -1747,13 +2037,15 @@ if [ "$target_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ -r
1747
2037
  printf " %s2)%s Codex %s— patches ~/.codex/config.toml (or <repo>/.codex/)%s\n" "$C_BRAND" "$C_RESET" "$C_DIM" "$C_RESET"
1748
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"
1749
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"
1750
- 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"
1751
2042
  read -r target_choice </dev/tty || target_choice=""
1752
2043
  case "${target_choice:-1}" in
1753
2044
  1|""|claude|c|C) target="claude" ;;
1754
2045
  2|codex|x|X) target="codex" ;;
1755
2046
  3|opencode|o|O) target="opencode" ;;
1756
2047
  4|pi|p|P) target="pi" ;;
2048
+ 5|copilot|g|G) target="copilot" ;;
1757
2049
  *) err "Invalid choice: $target_choice."; exit 2 ;;
1758
2050
  esac
1759
2051
  fi
@@ -1763,6 +2055,11 @@ fi
1763
2055
  # not a bare "Install scope:" line. Target prompt above already finalized
1764
2056
  # $target, so the banner's per-target label reflects the user's choice.
1765
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
+
1766
2063
  [ "$mode" = "install" ] && print_banner
1767
2064
 
1768
2065
  # ---------- interactive scope prompt ----------
@@ -1772,7 +2069,7 @@ fi
1772
2069
  # they keep the user-scope default unless the caller explicitly selects a
1773
2070
  # project scope. Non-interactive installs (CI, `curl | sh --non-interactive`)
1774
2071
  # silently use the "user" default.
1775
- 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
1776
2073
  # Per-target paths so the prompt text matches what actually gets written.
1777
2074
  case "$target" in
1778
2075
  codex)
@@ -1863,7 +2160,7 @@ fi
1863
2160
  # payloads with jq regardless of which client's config supplied the endpoint,
1864
2161
  # so require it there too rather than dying mid-render on `jq: command not
1865
2162
  # found`. Installing Codex itself still needs no jq.
1866
- if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] \
2163
+ if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] || [ "$target" = "copilot" ] \
1867
2164
  || { [ "$mode" = "models" ] && [ "$target" = "codex" ]; }; then
1868
2165
  ensure_jq
1869
2166
  fi
@@ -1906,6 +2203,12 @@ case "$target" in
1906
2203
  warn "Continuing — models.json/settings.json will be written and take effect once pi is installed."
1907
2204
  fi
1908
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
+ ;;
1909
2212
  esac
1910
2213
  fi
1911
2214
 
@@ -1924,6 +2227,7 @@ WEAVE_REGISTRY_DATA=$(cat <<'WEAVE_REGISTRY_EOF'
1924
2227
  # canonical|aliases|capability|claude|codex|opencode|pi|cursor|adapter
1925
2228
  # aliases are comma-separated; client columns are yes/no. adapter is the native asset kind.
1926
2229
  force-model|fm|prompt|yes|yes|yes|yes|manual|command,skill
2230
+ force-parent||prompt|yes|yes|yes|yes|manual|command,skill
1927
2231
  unforce-model|ufm|prompt|yes|yes|yes|yes|manual|command,skill
1928
2232
  router-feedback|rf|prompt|yes|yes|yes|no|manual|command,skill
1929
2233
  router-off||local-toggle|yes|yes|no|no|manual|command,skill
@@ -2183,6 +2487,23 @@ elif [ "$target" = "pi" ]; then
2183
2487
  fi
2184
2488
 
2185
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"
2186
2507
  else
2187
2508
  # opencode discovers config in this order: $XDG_CONFIG_HOME/opencode/opencode.json
2188
2509
  # (or ~/.config/opencode/opencode.json) for user scope, and opencode.json /
@@ -2357,6 +2678,14 @@ read_pi_key() {
2357
2678
  printf '%s' "$key"
2358
2679
  }
2359
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
+
2360
2689
  # read_installed_key prints the router key this install already has on disk, or
2361
2690
  # nothing, for whichever client is being installed. Reading it back is what makes
2362
2691
  # a re-run painless — see the token-handling section below. Defined up here
@@ -2375,6 +2704,7 @@ models_config_file_for_target() {
2375
2704
  codex) printf '%s' "$codex_config_file" ;;
2376
2705
  opencode) printf '%s' "$opencode_config_file" ;;
2377
2706
  pi) printf '%s' "$pi_models_file" ;;
2707
+ copilot) printf '%s' "$copilot_providers_file" ;;
2378
2708
  esac
2379
2709
  }
2380
2710
 
@@ -2410,6 +2740,7 @@ read_installed_key() {
2410
2740
  codex) read_codex_key "$codex_config_file" ;;
2411
2741
  opencode) read_opencode_key "$opencode_config_file" ;;
2412
2742
  pi) read_pi_key ;;
2743
+ copilot) read_copilot_key ;;
2413
2744
  esac
2414
2745
  }
2415
2746
 
@@ -2525,6 +2856,13 @@ resolve_installed_endpoint() {
2525
2856
  found="$(json_get "$pi_models_file" '.providers.weave.baseUrl')"
2526
2857
  fi
2527
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
+ ;;
2528
2866
  esac
2529
2867
  printf '%s' "${found%/}"
2530
2868
  }
@@ -2666,7 +3004,7 @@ prepare_claude_context_window() {
2666
3004
  model="${model:-sonnet}"
2667
3005
  case "$model" in
2668
3006
  *'[1m]') context_window=""; return 0 ;;
2669
- 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) ;;
2670
3008
  *) err "Cannot assert 1M support for '$model'. Select a supported Sonnet/Opus/Fable model first; leaving it unchanged."; return 1 ;;
2671
3009
  esac
2672
3010
  context_managed_model="${model}[1m]"
@@ -2861,21 +3199,28 @@ toggle_claude() {
2861
3199
  esac
2862
3200
  }
2863
3201
 
2864
- toggle_codex() {
2865
- local f="$codex_config_file" state="absent" tmp
2866
- if [ -f "$f" ]; then
2867
- state="$(awk '
2868
- /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*\]/ { has_weave = 1 }
2869
- /^[[:space:]]*\[/ { in_section = 1 }
2870
- !in_section && /^[[:space:]]*model_provider[[:space:]]*=[[:space:]]*"weave"[[:space:]]*$/ { active_weave = 1 }
2871
- !in_section && /^[[:space:]]*model_provider[[:space:]]*=/ { has_active_provider = 1 }
2872
- END {
2873
- if (!has_weave) print "absent"
2874
- else if (active_weave) print "on"
2875
- else print (has_active_provider ? "absent" : "off")
2876
- }
2877
- ' "$f")"
3202
+ codex_routing_state() {
3203
+ local f="$codex_config_file"
3204
+ if [ ! -f "$f" ]; then
3205
+ printf 'absent\n'
3206
+ return 0
2878
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)"
2879
3224
 
2880
3225
  case "$mode" in
2881
3226
  status)
@@ -3037,6 +3382,64 @@ toggle_opencode() {
3037
3382
  esac
3038
3383
  }
3039
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
+
3040
3443
  # ---------- model selection ----------
3041
3444
  #
3042
3445
  # `models` reads and edits the installation's model/provider selection through
@@ -3054,7 +3457,7 @@ toggle_opencode() {
3054
3457
  # Public, unauthed catalog of everything the router can route to. Mounted in
3055
3458
  # both deployment modes, so it is the one listing that always works.
3056
3459
  MODELS_CATALOG_PATH="/v1/router/models"
3057
- MODELS_DASHBOARD_URL="https://router.workweave.ai/dashboard/settings"
3460
+ MODELS_DASHBOARD_URL="https://router.workweave.ai/models"
3058
3461
 
3059
3462
  # Set by models_api on every call.
3060
3463
  models_http_status=""
@@ -3100,19 +3503,36 @@ models_api_error() {
3100
3503
  # models_fail turns the status left by models_api into a message that says what
3101
3504
  # to do next, then exits. $1 names the attempted operation.
3102
3505
  models_fail() {
3103
- local what="$1" detail
3506
+ local what="$1" detail repair_command
3104
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
3105
3519
  case "$models_http_status" in
3106
3520
  ""|000)
3107
3521
  err "Could not reach the router at $base_url. Is it running?"
3108
3522
  ;;
3109
3523
  401|403)
3110
- # 403 with a message is the ROUTER_EXCLUDED_MODELS/PROVIDERS env pin,
3111
- # which is actionable on its own; a bare 401/403 is a key problem.
3112
- if [ -n "$detail" ]; then
3524
+ # Preserve policy errors; invalid_key needs local setup instructions.
3525
+ if [ -n "$detail" ] && [ "$detail" != "invalid_key" ]; then
3113
3526
  err "$detail"
3114
3527
  else
3115
- 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
3116
3536
  fi
3117
3537
  ;;
3118
3538
  404)
@@ -3123,11 +3543,15 @@ models_fail() {
3123
3543
  "$C_DIM" "$C_RESET" >&2
3124
3544
  ;;
3125
3545
  *)
3126
- if [ -n "$detail" ]; then
3127
- err "$what failed (HTTP $models_http_status): $detail"
3128
- else
3129
- err "$what failed (HTTP $models_http_status)."
3130
- 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
3131
3555
  ;;
3132
3556
  esac
3133
3557
  exit 1
@@ -3196,6 +3620,7 @@ models_list_catalog() {
3196
3620
  return 0
3197
3621
  fi
3198
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"
3199
3624
  printf "%severything this router can route to%s\n\n" "$C_DIM" "$C_RESET"
3200
3625
  if [ "$what" = "providers" ]; then
3201
3626
  printf '%s' "$models_http_body" | jq -r '[.models[].provider] | unique[] | " " + .'
@@ -3206,9 +3631,7 @@ models_list_catalog() {
3206
3631
  (.[] | " " + .model)
3207
3632
  '
3208
3633
  fi
3209
- printf "\n%sThis router does not report which of them your installation has enabled:%s\n" "$C_DIM" "$C_RESET"
3210
- printf "%sselection is an organization-wide setting here. See it, and change it, at%s\n" "$C_DIM" "$C_RESET"
3211
- 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"
3212
3635
  }
3213
3636
 
3214
3637
  models_list() {
@@ -3414,13 +3837,10 @@ open_url_in_browser() {
3414
3837
  open "$url" >/dev/null 2>&1
3415
3838
  ;;
3416
3839
  MINGW*|MSYS*|CYGWIN*)
3417
- # explorer.exe is a direct process launch; cmd.exe /c start would parse
3418
- # URL query separators such as '&' as shell syntax. Its exit status is
3419
- # not meaningful: an already-running shell commonly returns 1 after
3420
- # handing the URL off.
3421
- command -v explorer.exe >/dev/null 2>&1 || return 1
3422
- explorer.exe "$url" >/dev/null 2>&1 || true
3423
- 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
3424
3844
  ;;
3425
3845
  *)
3426
3846
  command -v xdg-open >/dev/null 2>&1 || return 1
@@ -3602,55 +4022,297 @@ run_login() {
3602
4022
  [ -n "$provider" ] || { err "Use 'login claude' or 'login codex'."; exit 2; }
3603
4023
  [ -z "$extra" ] || { err "Login accepts exactly one provider."; exit 2; }
3604
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
3605
4029
  require_cmd openssl "Install OpenSSL to enroll a subscription account."
3606
4030
  case "$provider" in
3607
4031
  claude) run_login_claude ;;
3608
4032
  codex) run_login_codex ;;
3609
- *) 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
+ ;;
3610
4183
  esac
3611
4184
  }
3612
4185
 
3613
4186
  run_router_status() {
3614
- local saved_target codex_endpoint redacted_key
3615
- 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
3616
4194
  settings_dir="$settings_base/.claude"
3617
4195
  settings_file="$settings_dir/settings.json"
3618
- if [ "$scope" = "project" ]; then
3619
- local_settings_file="$settings_dir/settings.local.json"
3620
- else
3621
- local_settings_file=""
3622
- fi
3623
- codex_config_file="$settings_base/.codex/config.toml"
3624
- target="codex"; codex_endpoint="$(resolve_installed_endpoint)"
3625
- 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"
3626
4200
  if [ "${#api_key}" -gt 8 ]; then
3627
4201
  redacted_key="${api_key:0:3}…${api_key: -4}"
3628
4202
  else
3629
4203
  redacted_key="redacted"
3630
4204
  fi
3631
- printf 'Router: %s\nIdentity: %s\n' "$base_url" "$redacted_key"
3632
- if models_api GET "/validate"; then
3633
- 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"
3634
4226
  else
3635
- printf 'Connectivity: unavailable (HTTP %s)\n' "${models_http_status:-network error}"
3636
- fi
3637
- printf 'Claude Code settings: %s (scope: %s)\n' "$settings_dir" "$scope"
3638
- # Administrative lookup includes parked credentials; routing status must not.
3639
- toggle_claude
3640
- 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'
3641
- 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)"
3642
- if models_api GET "/v1/subscriptions/accounts"; then
3643
- 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'
3644
4304
  if [ "$(printf '%s' "$models_http_body" | jq 'length')" -eq 0 ]; then
3645
- printf ' none enrolled\n'
4305
+ printf ' Subscriptions none enrolled %s(%s login claude | login codex)%s\n' "$C_DIM" "$npx" "$C_RESET"
3646
4306
  else
3647
- 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)'
3648
4309
  fi
3649
4310
  elif [ "$models_http_status" = "404" ]; then
3650
- printf 'Subscription accounts: server-side pools disabled\n'
3651
- else
3652
- 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}"
3653
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"
3654
4316
  }
3655
4317
 
3656
4318
  if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] || [ "$mode" = "status" ]; then
@@ -3691,12 +4353,25 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
3691
4353
  fi
3692
4354
  if [ "$base_url_explicit" != "true" ]; then
3693
4355
  models_base="$(resolve_installed_endpoint)"
3694
- 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
3695
4357
  target="codex"
3696
4358
  models_base="$(resolve_installed_endpoint)"
3697
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
3698
4372
  if [ -z "$models_base" ]; then
3699
- 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
3700
4375
  exit 1
3701
4376
  fi
3702
4377
  base_url="$models_base"
@@ -3753,6 +4428,26 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
3753
4428
  target="$login_target"
3754
4429
  fi
3755
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
3756
4451
  if [ -z "$api_key" ]; then
3757
4452
  err "No router key found for $target in this scope. Re-run 'npx $npm_package_name --$target', or export WEAVE_ROUTER_KEY."
3758
4453
  exit 1
@@ -3789,6 +4484,7 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ]; then
3789
4484
  claude) toggle_claude ;;
3790
4485
  codex) toggle_codex ;;
3791
4486
  opencode) toggle_opencode ;;
4487
+ copilot) toggle_copilot ;;
3792
4488
  esac
3793
4489
  exit 0
3794
4490
  fi
@@ -3862,6 +4558,10 @@ elif [ -n "$installed_key" ]; then
3862
4558
  api_key="$installed_key"
3863
4559
  api_key_source="disk"
3864
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."
3865
4565
  elif [ "$mode" = "update" ]; then
3866
4566
  err "No router key found for $target. Export WEAVE_ROUTER_KEY, or run the installer once to set one up."
3867
4567
  exit 1
@@ -4197,7 +4897,43 @@ EOF
4197
4897
  # Wrapped in a function so the spinner's exec form sees a single command argv.
4198
4898
  validate_key() {
4199
4899
  printf '%s: %s\n' "$router_key_header" "$api_key" \
4200
- | 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
4201
4937
  }
4202
4938
 
4203
4939
  # rewrite_installed_key rewrites this target's managed config with the key in $1.
@@ -4214,6 +4950,7 @@ rewrite_installed_key() {
4214
4950
  printf '%s\n' "$key" >"$pi_key_file"
4215
4951
  chmod 600 "$pi_key_file"
4216
4952
  ;;
4953
+ copilot) write_copilot_providers "$copilot_providers_file" "$base_url" "$key" "$user_email" "$user_name" ;;
4217
4954
  esac
4218
4955
  }
4219
4956
 
@@ -4233,26 +4970,31 @@ verify_install() {
4233
4970
 
4234
4971
  [ -n "$api_key" ] || return 0
4235
4972
 
4973
+ [ -n "$validate_status_file" ] || validate_status_file="$(mktemp -t weave-validate.XXXXXX)"
4236
4974
  if spin "Validating API key" validate_key; then
4975
+ key_verdict="valid"
4237
4976
  [ "$health_verified" = "true" ] && install_verification_succeeded="true"
4238
4977
  return 0
4239
4978
  fi
4979
+ record_key_verdict
4240
4980
 
4241
4981
  # A key we read back off disk can have been revoked or rotated since it was
4242
4982
  # installed, and reusing it silently would leave a broken install behind
4243
4983
  # exactly where the old behavior (always prompt) would have fixed it. Ask
4244
4984
  # once, then rewrite the config with whatever the user pastes. Anywhere a
4245
4985
  # prompt isn't available — non-interactive, update, --quiet, no tty, or a
4246
- # key that didn't come from disk — keep the historical warn-and-continue.
4247
- if [ "$api_key_source" = "disk" ] && [ "$non_interactive" != "true" ] \
4248
- && [ "$quiet" != "true" ] && [ -r /dev/tty ]; then
4249
- 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)."
4250
4991
  prompt_for_key
4251
4992
  rewrite_installed_key "$api_key"
4252
4993
  if spin "Validating API key" validate_key; then
4994
+ key_verdict="valid"
4253
4995
  [ "$health_verified" = "true" ] && install_verification_succeeded="true"
4254
4996
  else
4255
- warn "Router rejected the API key (check it matches the dashboard at $base_url)."
4997
+ record_key_verdict
4256
4998
  fi
4257
4999
  return 0
4258
5000
  fi
@@ -4263,14 +5005,13 @@ verify_install() {
4263
5005
  # of the nonzero exit — a scheduled run that reports success here would
4264
5006
  # hide a revoked key indefinitely.
4265
5007
  if [ "$quiet" = "true" ]; then
4266
- 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."
4267
5009
  else
4268
- 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."
4269
5011
  fi
4270
5012
  exit 1
4271
5013
  fi
4272
5014
 
4273
- warn "Router rejected the API key (check it matches the dashboard at $base_url)."
4274
5015
  }
4275
5016
 
4276
5017
  # announce_done prints the closing line for the client named in $1. `update`
@@ -4278,17 +5019,92 @@ verify_install() {
4278
5019
  # skips the uninstall hint — that run was never the user's first contact with
4279
5020
  # the installer.
4280
5021
  announce_done() {
5022
+ write_setup_handoff
4281
5023
  printf "\n"
4282
5024
  if [ "$mode" = "update" ]; then
4283
5025
  printf "%s✓%s %s%sWeave Router config refreshed for %s.%s\n" \
4284
5026
  "$C_GREEN" "$C_RESET" "$C_BOLD" "$C_BRAND" "$1" "$C_RESET"
4285
5027
  return 0
4286
5028
  fi
4287
- printf "%s✓%s %s%sWeave Router installed for %s.%s\n" \
4288
- "$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
4289
5040
  open_return_url_if_verified
4290
5041
  }
4291
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
+
4292
5108
  # ---------- codex install path (dispatch + exit before the Claude-only writes) ----------
4293
5109
 
4294
5110
  # Install the Codex lifecycle helper that reflects the active router and the
@@ -4439,6 +5255,9 @@ weave_self_refresh() {
4439
5255
  return 0
4440
5256
  }
4441
5257
 
5258
+ async_title_enabled=0
5259
+ [ ! -t 2 ] || async_title_enabled=1
5260
+
4442
5261
  state_root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/codex"
4443
5262
  helper_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
4444
5263
  disabled_marker="$helper_dir/.weave-router-disabled"
@@ -4448,7 +5267,7 @@ emit_title() {
4448
5267
  local title="$1"
4449
5268
  if [ -n "${WEAVE_CODEX_STATUS_TITLE_FILE:-}" ]; then
4450
5269
  printf '%s\n' "$title" >"$WEAVE_CODEX_STATUS_TITLE_FILE"
4451
- elif [ -t 2 ] && [ -w /dev/tty ]; then
5270
+ elif { [ -t 2 ] || [ "${async_title_enabled:-0}" = "1" ]; } && [ -w /dev/tty ]; then
4452
5271
  printf '\033]0;%s\007' "$title" >/dev/tty
4453
5272
  fi
4454
5273
  return 0
@@ -4464,13 +5283,14 @@ safe_session_id() {
4464
5283
  }
4465
5284
 
4466
5285
  safe_display_value() {
4467
- 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
4468
5287
  }
4469
5288
 
4470
5289
  state_file_for() {
4471
- local id
5290
+ local id scope
4472
5291
  id="$(safe_session_id "$1")" || return 1
4473
- 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"
4474
5294
  }
4475
5295
 
4476
5296
  read_state() {
@@ -4479,6 +5299,8 @@ read_state() {
4479
5299
  while IFS='=' read -r key value; do
4480
5300
  case "$key" in
4481
5301
  routed_model) routed_model="$value" ;;
5302
+ last_pin_model) last_pin_model="$value" ;;
5303
+ command_ids) command_ids="$value" ;;
4482
5304
  esac
4483
5305
  done <"$file"
4484
5306
  }
@@ -4488,7 +5310,7 @@ write_state() {
4488
5310
  mkdir -p "$state_root"
4489
5311
  chmod 700 "$state_root"
4490
5312
  tmp="$(mktemp "$state_root/.state.XXXXXX")"
4491
- 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"
4492
5314
  chmod 600 "$tmp"
4493
5315
  mv "$tmp" "$file"
4494
5316
  }
@@ -4499,6 +5321,99 @@ cost_file_for() {
4499
5321
  printf '%s/%s.cost' "$state_root" "$id"
4500
5322
  }
4501
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
+
4502
5417
  # Reads the router base URL and key out of the Codex config this install owns.
4503
5418
  # Resolved from the helper's own location first so a project-scope install never
4504
5419
  # reads (or leaks) the user-scope key: the project helper lives in the same
@@ -4576,11 +5491,11 @@ read_codex_endpoint() {
4576
5491
  # Fire-and-forget on purpose — a slow or unreachable router must never stall a
4577
5492
  # Codex turn, and every failure simply leaves the previous cache in place.
4578
5493
  refresh_session_cost() {
4579
- local id="$1" file="$2"
4580
- [ "${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
4581
5496
  command -v curl >/dev/null 2>&1 || return 0
4582
5497
 
4583
- local endpoint base_url key
5498
+ local endpoint base_url key active_file state_lock
4584
5499
  endpoint="$(read_codex_endpoint)" || return 0
4585
5500
  base_url="$(printf '%s' "$endpoint" | sed -n 1p)"
4586
5501
  key="$(printf '%s' "$endpoint" | sed -n 2p)"
@@ -4588,6 +5503,8 @@ refresh_session_cost() {
4588
5503
 
4589
5504
  mkdir -p "$state_root" 2>/dev/null || return 0
4590
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
4591
5508
 
4592
5509
  (
4593
5510
  exec </dev/null
@@ -4612,29 +5529,112 @@ refresh_session_cost() {
4612
5529
  file://*) ;;
4613
5530
  *) url="${url%/v1}/v1/sessions/$id/cost" ;;
4614
5531
  esac
4615
- body="$(curl -fsS --max-time 5 -H "X-Weave-Router-Key: $key" "$url" 2>/dev/null)" || exit 0
4616
- # savings_usd is the router's own (requested - actual). A body without it
4617
- # (404, error envelope, older router) writes nothing and leaves the cache.
4618
- savings="$(printf '%s' "$body" | jq -r '.savings_usd // empty' 2>/dev/null)" || exit 0
4619
- case "$savings" in
4620
- ''|*[!0-9.eE+-]*) exit 0 ;;
4621
- esac
4622
- tmp="$file.tmp.$$"
4623
- mkdir -p "$(dirname "$file")" 2>/dev/null
4624
- if printf '%s' "$savings" >"$tmp" 2>/dev/null; then
4625
- chmod 600 "$tmp" 2>/dev/null
4626
- 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
4627
5538
  fi
4628
- 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"
4629
5629
  ) >/dev/null 2>&1 &
4630
5630
  disown 2>/dev/null || true
4631
5631
  }
4632
5632
 
4633
5633
  # Renders the cached savings as a display clause, or nothing. Values below a
4634
5634
  # cent read as "<$0.01" rather than "$0.00", which would be indistinguishable
4635
- # from "the router ran and did not beat your selection". Negative totals are
4636
- # omitted entirely: the router picked a pricier model for quality on this
4637
- # 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.
4638
5638
  savings_clause() {
4639
5639
  local file="$1" raw
4640
5640
  [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && return 0
@@ -4645,6 +5645,8 @@ savings_clause() {
4645
5645
  esac
4646
5646
  awk -v v="$raw" 'BEGIN{
4647
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 }
4648
5650
  if (v < 0.005) { exit }
4649
5651
  if (v < 0.01) { printf " · saved <$0.01"; exit }
4650
5652
  printf " · saved $%.2f", v
@@ -4694,6 +5696,38 @@ if [ "${WEAVE_CAPTURE_LLM_CLASSIFIER:-}" = "1" ] && [ -n "${WEAVE_CAPTURE_HOOK_T
4694
5696
  esac
4695
5697
  fi
4696
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
4697
5731
  if [ "$hook_event_name" = "SessionStart" ]; then
4698
5732
  if [ -f "$disabled_marker" ]; then
4699
5733
  emit_title "Codex · direct"
@@ -4703,7 +5737,11 @@ if [ "$hook_event_name" = "SessionStart" ]; then
4703
5737
  exit 0
4704
5738
  fi
4705
5739
 
4706
- 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
4707
5745
  exit 0
4708
5746
  fi
4709
5747
 
@@ -4713,6 +5751,8 @@ fi
4713
5751
 
4714
5752
  requested_model="$(safe_display_value "$(jq -r '.model // ""' <<<"$payload")")"
4715
5753
  routed_model=""
5754
+ last_pin_model=""
5755
+ command_ids=""
4716
5756
  session_id="$(jq -r '.session_id // ""' <<<"$payload")"
4717
5757
  last_assistant_message="$(jq -r '.last_assistant_message // ""' <<<"$payload")"
4718
5758
 
@@ -4721,31 +5761,52 @@ if file="$(state_file_for "$session_id" 2>/dev/null)"; then
4721
5761
  read_state "$file"
4722
5762
  fi
4723
5763
 
4724
- # The marker is intentionally matched only at the beginning of the assistant
4725
- # message. Do not treat ordinary prose that mentions the heading as metadata.
4726
5764
  first_line="${last_assistant_message%%$'\n'*}"
4727
5765
  marker_model=""
4728
5766
  force_model=""
4729
- case "$first_line" in
4730
- "${router_badge_sentinel}✦ **Weave Router** → "*)
4731
- marker_model="${first_line#"${router_badge_sentinel}✦ **Weave Router** → "}"
4732
- marker_model="${marker_model%% ·*}"
4733
- ;;
4734
- "✦ **Weave Router** → "*)
4735
- marker_model="${first_line#"✦ **Weave Router** → "}"
4736
- marker_model="${marker_model%% ·*}"
4737
- ;;
4738
- esac
4739
- case "$first_line" in
4740
- "Weave Router: force-model applied: "*" ("*)
4741
- force_model="${first_line#"Weave Router: force-model applied: "}"
4742
- force_model="${force_model%% (*}"
4743
- ;;
5767
+ structured_command=0
5768
+ case "$last_assistant_message" in
5769
+ *'[weave-router-command-v'*) structured_command=1 ;;
4744
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
4745
5808
  if [ -n "$marker_model" ]; then
4746
5809
  routed_model="$(safe_display_value "$marker_model")"
4747
- elif [ -n "$force_model" ]; then
4748
- routed_model="$(safe_display_value "$force_model")"
4749
5810
  else
4750
5811
  routed_model="$(safe_display_value "$routed_model")"
4751
5812
  fi
@@ -4759,22 +5820,41 @@ fi
4759
5820
  # turn would not be included even in a blocking read — reading first and
4760
5821
  # refreshing after costs a turn of freshness and buys never blocking Codex.
4761
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
4762
5837
  cost_file=""
4763
5838
  if cost_file="$(cost_file_for "$session_id" 2>/dev/null)"; then
4764
5839
  savings="$(savings_clause "$cost_file")"
4765
- refresh_session_cost "$(safe_session_id "$session_id")" "$cost_file"
5840
+
4766
5841
  fi
4767
5842
 
4768
5843
  if [ -n "$routed_model" ] && [ -n "$requested_model" ] && [ "$routed_model" != "$requested_model" ]; then
4769
- title="Weave Router · $routed_model ← $requested_model$savings"
5844
+ title="Weave Router · $requested_model → $routed_model$savings"
4770
5845
  elif [ -n "$routed_model" ]; then
4771
5846
  title="Weave Router · $routed_model$savings"
4772
5847
  elif [ -n "$requested_model" ]; then
4773
- title="Weave Router · active ← $requested_model$savings"
5848
+ title="Weave Router · $requested_model → active$savings"
4774
5849
  else
4775
5850
  title="Weave Router · active$savings"
4776
5851
  fi
4777
- 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
4778
5858
  CODEX_STATUS_EOF
4779
5859
  fi
4780
5860
  chmod 700 "$codex_status_file"
@@ -4992,7 +6072,7 @@ trap "rm -f '$out_file'" EXIT
4992
6072
  # word-split at runtime -- the braces are a template token, not an expansion.
4993
6073
  # shellcheck disable=SC1083
4994
6074
  run_bounded "$WEAVE_TOGGLE_TIMEOUT" "$out_file" \
4995
- 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}}
4996
6076
  status=$?
4997
6077
 
4998
6078
  output="$(cat "$out_file" 2>/dev/null || true)"
@@ -5108,6 +6188,39 @@ if [ "$target" = "codex" ]; then
5108
6188
  # point CODEX_HOME at the directory we wrote so Codex finds our config.
5109
6189
  info "Run Codex with CODEX_HOME=$codex_dir codex so it picks up this config."
5110
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
5111
6224
  [ "$mode" = "update" ] || print_uninstall_hint
5112
6225
  exit 0
5113
6226
  fi
@@ -5243,7 +6356,7 @@ cat > "$statusline_file" << 'STATUSLINE_EOF'
5243
6356
  # { "statusLine": { "type": "command", "command": "/abs/path/to/cc-statusline.sh" } }
5244
6357
  #
5245
6358
  # Renders:
5246
- # WEAVE ROUTER · response model: claude-sonnet-4-5 · selected: claude-opus-4-7 · est. cost difference $1.23
6359
+ # WEAVE ROUTER · you picked opus-4-7 → served sonnet-4-5 · saved ~$1.23 this session
5247
6360
  #
5248
6361
  # Pricing source of truth: internal/router/catalog. Input/output prices and
5249
6362
  # cache-read multipliers are generated by cmd/genprices. Cache creation remains
@@ -5252,6 +6365,48 @@ cat > "$statusline_file" << 'STATUSLINE_EOF'
5252
6365
  set -euo pipefail
5253
6366
  export PATH="$PATH:$HOME/.weave/bin"
5254
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
6409
+
5255
6410
  # ---------- background self-refresh ----------
5256
6411
  #
5257
6412
  # Once every WEAVE_STATUSLINE_UPDATE_INTERVAL_DAYS (default 7), check
@@ -5652,7 +6807,14 @@ weave_hidden_gate() {
5652
6807
  file://*) ;;
5653
6808
  *) url="$url/v1/display-settings" ;;
5654
6809
  esac
5655
- 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"
5656
6818
  hidden="$(printf '%s' "$body" | jq -r '.hide_terminal_surfaces // false' 2>/dev/null)"
5657
6819
  tmp="$cache.tmp.$$"
5658
6820
  if [ "$hidden" = "true" ]; then
@@ -5671,6 +6833,7 @@ if weave_hidden_gate </dev/null; then
5671
6833
  fi
5672
6834
 
5673
6835
  input="$(cat)"
6836
+ jq -e 'type == "object"' >/dev/null 2>&1 <<<"$input" || exit 0
5674
6837
  transcript_path="$(printf '%s' "$input" | jq -r '.transcript_path // empty')"
5675
6838
  # Prefer model.id over display_name: pricing keys + the response model id in
5676
6839
  # the transcript are canonical ids (e.g. claude-opus-4-7), while display_name
@@ -5678,6 +6841,19 @@ transcript_path="$(printf '%s' "$input" | jq -r '.transcript_path // empty')"
5678
6841
  # preventing a price comparison. id passes through normalize_model cleanly.
5679
6842
  selected_display="$(printf '%s' "$input" | jq -r '.model.id // .model.display_name // "?"')"
5680
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
+
5681
6857
  # Normalize a model id to a pricing-table key. CC + the decisions log carry
5682
6858
  # two flavors of annotation we don't want in the lookup:
5683
6859
  # * date suffix: claude-opus-4-7-20260101 → claude-opus-4-7
@@ -5696,6 +6872,7 @@ prices='{
5696
6872
  "claude-fable-5": 0.01,
5697
6873
  "claude-fable-5-1": 0.01,
5698
6874
  "claude-haiku-4-5": 0.001,
6875
+ "claude-haiku-5-5": 0.0001,
5699
6876
  "claude-opus-4-0": 0.015,
5700
6877
  "claude-opus-4-1": 0.015,
5701
6878
  "claude-opus-4-5": 0.005,
@@ -5706,7 +6883,7 @@ prices='{
5706
6883
  "claude-opus-5-5": 0.004,
5707
6884
  "claude-sonnet-4-5": 0.003,
5708
6885
  "claude-sonnet-4-6": 0.003,
5709
- "claude-sonnet-5": 0.003,
6886
+ "claude-sonnet-5": 0.002,
5710
6887
  "claude-sonnet-5-5": 0.002,
5711
6888
  "deepseek/deepseek-v4-flash": 0.00014,
5712
6889
  "deepseek/deepseek-v4-pro": 0.00174,
@@ -5726,6 +6903,7 @@ prices='{
5726
6903
  "gemini-3.6-flash": 0.0015,
5727
6904
  "gemini-3.7-flash": 0.0015,
5728
6905
  "gemini-3.8-flash": 0.0015,
6906
+ "gemini-4-argon": 0.002,
5729
6907
  "google/gemma-4-26b-a4b-it": 0.00015,
5730
6908
  "gpt-4.1": 0.002,
5731
6909
  "gpt-4.1-mini": 0.0004,
@@ -5753,17 +6931,20 @@ prices='{
5753
6931
  "gpt-6-luna": 0.0001,
5754
6932
  "gpt-6-sol": 0.002,
5755
6933
  "gpt-6.1-sol": 0.002,
6934
+ "gpt-6.1-terra": 0.001,
5756
6935
  "grok-4.5": 0.002,
5757
6936
  "grok-4.6": 0.002,
5758
6937
  "grok-4.7": 0.002,
5759
6938
  "inclusionai/ling-3.0-flash": 0.00006,
5760
6939
  "minimax/minimax-m2.7": 0.0003,
5761
6940
  "minimax/minimax-m3": 0.0003,
6941
+ "minimax/minimax-m3.1-flash": 0.00015,
5762
6942
  "mistralai/mistral-small-2603": 0.0002,
5763
6943
  "moonshotai/kimi-k2.5": 0.0006,
5764
6944
  "moonshotai/kimi-k2.6": 0.00095,
5765
6945
  "moonshotai/kimi-k2.7": 0.00095,
5766
6946
  "moonshotai/kimi-k3": 0.003,
6947
+ "moonshotai/kimi-k3.1": 0.002,
5767
6948
  "muse-spark-1.3": 0.00125,
5768
6949
  "qwen/qwen3-235b-a22b-2507": 0.0002266,
5769
6950
  "qwen/qwen3-30b-a3b-instruct-2507": 0.00015,
@@ -5775,7 +6956,7 @@ prices='{
5775
6956
  "qwen/qwen3.7-plus": 0.0004,
5776
6957
  "qwen/qwen3.8-max": 0.002,
5777
6958
  "xiaomi/mimo-v2.5-pro": 0.001,
5778
- "xiaomi/mimo-v2.6-flash": 0.00014,
6959
+ "xiaomi/mimo-v2.6-flash": 0.00013,
5779
6960
  "xiaomi/mimo-v2.6-pro": 0.000435,
5780
6961
  "z-ai/glm-5": 0.001,
5781
6962
  "z-ai/glm-5.1": 0.0014,
@@ -5787,6 +6968,7 @@ prices='{
5787
6968
  "claude-fable-5": 0.05,
5788
6969
  "claude-fable-5-1": 0.05,
5789
6970
  "claude-haiku-4-5": 0.005,
6971
+ "claude-haiku-5-5": 0.0005,
5790
6972
  "claude-opus-4-0": 0.075,
5791
6973
  "claude-opus-4-1": 0.075,
5792
6974
  "claude-opus-4-5": 0.025,
@@ -5797,7 +6979,7 @@ prices='{
5797
6979
  "claude-opus-5-5": 0.02,
5798
6980
  "claude-sonnet-4-5": 0.015,
5799
6981
  "claude-sonnet-4-6": 0.015,
5800
- "claude-sonnet-5": 0.015,
6982
+ "claude-sonnet-5": 0.01,
5801
6983
  "claude-sonnet-5-5": 0.01,
5802
6984
  "deepseek/deepseek-v4-flash": 0.00028,
5803
6985
  "deepseek/deepseek-v4-pro": 0.00348,
@@ -5817,6 +6999,7 @@ prices='{
5817
6999
  "gemini-3.6-flash": 0.0075,
5818
7000
  "gemini-3.7-flash": 0.0075,
5819
7001
  "gemini-3.8-flash": 0.0075,
7002
+ "gemini-4-argon": 0.01,
5820
7003
  "google/gemma-4-26b-a4b-it": 0.0006,
5821
7004
  "gpt-4.1": 0.008,
5822
7005
  "gpt-4.1-mini": 0.0016,
@@ -5844,17 +7027,20 @@ prices='{
5844
7027
  "gpt-6-luna": 0.0005,
5845
7028
  "gpt-6-sol": 0.01,
5846
7029
  "gpt-6.1-sol": 0.01,
7030
+ "gpt-6.1-terra": 0.005,
5847
7031
  "grok-4.5": 0.006,
5848
7032
  "grok-4.6": 0.006,
5849
7033
  "grok-4.7": 0.006,
5850
7034
  "inclusionai/ling-3.0-flash": 0.00018,
5851
7035
  "minimax/minimax-m2.7": 0.0012,
5852
7036
  "minimax/minimax-m3": 0.0012,
7037
+ "minimax/minimax-m3.1-flash": 0.0006,
5853
7038
  "mistralai/mistral-small-2603": 0.0006,
5854
7039
  "moonshotai/kimi-k2.5": 0.003,
5855
7040
  "moonshotai/kimi-k2.6": 0.004,
5856
7041
  "moonshotai/kimi-k2.7": 0.004,
5857
7042
  "moonshotai/kimi-k3": 0.015,
7043
+ "moonshotai/kimi-k3.1": 0.01,
5858
7044
  "muse-spark-1.3": 0.00425,
5859
7045
  "qwen/qwen3-235b-a22b-2507": 0.0009064,
5860
7046
  "qwen/qwen3-30b-a3b-instruct-2507": 0.0006,
@@ -5878,6 +7064,7 @@ prices='{
5878
7064
  "claude-fable-5": 0.1,
5879
7065
  "claude-fable-5-1": 0.025,
5880
7066
  "claude-haiku-4-5": 0.1,
7067
+ "claude-haiku-5-5": 0.1,
5881
7068
  "claude-opus-4-0": 0.1,
5882
7069
  "claude-opus-4-1": 0.1,
5883
7070
  "claude-opus-4-5": 0.1,
@@ -5908,6 +7095,7 @@ prices='{
5908
7095
  "gemini-3.6-flash": 0.1,
5909
7096
  "gemini-3.7-flash": 0.1,
5910
7097
  "gemini-3.8-flash": 0.1,
7098
+ "gemini-4-argon": 0.1,
5911
7099
  "google/gemma-4-26b-a4b-it": 0.1,
5912
7100
  "gpt-4.1": 0.25,
5913
7101
  "gpt-4.1-mini": 0.25,
@@ -5935,17 +7123,20 @@ prices='{
5935
7123
  "gpt-6-luna": 0.1,
5936
7124
  "gpt-6-sol": 0.1,
5937
7125
  "gpt-6.1-sol": 0.05,
7126
+ "gpt-6.1-terra": 0.05,
5938
7127
  "grok-4.5": 0.25,
5939
7128
  "grok-4.6": 0.25,
5940
7129
  "grok-4.7": 0.25,
5941
7130
  "inclusionai/ling-3.0-flash": 0.2,
5942
7131
  "minimax/minimax-m2.7": 0.2,
5943
7132
  "minimax/minimax-m3": 0.2,
7133
+ "minimax/minimax-m3.1-flash": 0.1,
5944
7134
  "mistralai/mistral-small-2603": 0.1,
5945
7135
  "moonshotai/kimi-k2.5": 0.5,
5946
7136
  "moonshotai/kimi-k2.6": 0.1684,
5947
7137
  "moonshotai/kimi-k2.7": 0.2,
5948
7138
  "moonshotai/kimi-k3": 0.1,
7139
+ "moonshotai/kimi-k3.1": 0.1,
5949
7140
  "muse-spark-1.3": 0.12,
5950
7141
  "qwen/qwen3-235b-a22b-2507": 0.5,
5951
7142
  "qwen/qwen3-30b-a3b-instruct-2507": 0.1684,
@@ -5957,7 +7148,7 @@ prices='{
5957
7148
  "qwen/qwen3.7-plus": 0.2,
5958
7149
  "qwen/qwen3.8-max": 0.125,
5959
7150
  "xiaomi/mimo-v2.5-pro": 0.1,
5960
- "xiaomi/mimo-v2.6-flash": 0.02,
7151
+ "xiaomi/mimo-v2.6-flash": 0.015384615384615385,
5961
7152
  "xiaomi/mimo-v2.6-pro": 0.00827586,
5962
7153
  "z-ai/glm-5": 0.2,
5963
7154
  "z-ai/glm-5.1": 0.18571428571428572,
@@ -5998,38 +7189,37 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
5998
7189
  transcript_model="$(normalize_model "$transcript_model")"
5999
7190
  fi
6000
7191
 
6001
- # Read the last /force-model acknowledgement in the transcript —
6002
- # the only turns stamped message.model == "weave-router". The router emits
6003
- # one whenever a pin changes state:
6004
- # * /force-model → "force-model applied: <model> (<provider>) …"
6005
- # * /unforce-model → "force-model cleared …"
6006
- # * loop / no-progress break → "… clearing the session pin …" (expires the
6007
- # pin, including a user-forced one)
6008
- # * unrecognized model → "… isn't a recognized model · keeping
6009
- # automatic routing" — a NO-OP: the prior
6010
- # pin, if any, is left untouched
6011
- # * listing (historical) → "… pick a model by id …" / "no models are
6012
- # available to pin …" — also NO-OPs. The
6013
- # router no longer emits these, but a
6014
- # transcript written while it did still
6015
- # carries them, and they must not read as
6016
- # a clear or a live pin loses its [forced]
6017
- # These persist on disk (the ingress stripper only scrubs them from upstream
6018
- # requests). Classify each weave-router turn newest-first, skip the no-op
6019
- # "rejected" acks, and let the latest real state change decide: an "applied"
6020
- # marker records a pin (and names the model); a later clear removes it.
6021
- # This history cannot establish the running client's route or current pin.
6022
- # Restricting to weave-router turns keeps a normal reply that merely quotes
6023
- # these phrases from flipping the tag. (A silent server-side TTL expiry emits
6024
- # no turn and so can't be reflected here — the pin TTL outlives a session.)
6025
- force_state="$("${reverse[@]}" "$transcript_path" 2>/dev/null \
6026
- | jq -r 'select(.type=="assistant" and .message.model=="weave-router")
6027
- | ([.message.content[]? | select(.type? == "text") | .text] | join(" ") | gsub("[\n\r]"; " ")) as $t
6028
- | if ($t | test("force-model applied:")) then "APPLIED " + ($t | capture("force-model applied: (?<m>[^ ]+)").m)
6029
- elif ($t | test("isn.t a recognized model")) then "REJECTED"
6030
- elif ($t | test("pick a model by id|no models are available to pin")) then "REJECTED"
6031
- else "CLEARED" end' 2>/dev/null \
6032
- | grep -m1 -v '^REJECTED$' || true)"
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)"
6033
7223
  if [[ "$force_state" == APPLIED\ * ]]; then
6034
7224
  has_pin_record="true"
6035
7225
  last_pin_model="${force_state#APPLIED }"
@@ -6121,38 +7311,174 @@ weave_refresh_on_price_miss() {
6121
7311
  }
6122
7312
  weave_refresh_on_price_miss "$requested_norm" "$transcript_model" 2>/dev/null || true
6123
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
7421
+
6124
7422
  # Brand color (#FF6C47) on terminals that grok 24-bit truecolor — that's
6125
7423
  # every modern one (iTerm2, Apple Terminal, vscode, ghostty, alacritty,
6126
7424
  # wezterm, kitty). Falls back gracefully on any escape-stripping terminal.
6127
7425
  brand=$'\033[38;2;255;108;71mWEAVE ROUTER\033[0m'
6128
7426
 
6129
- # Format helpers.
6130
- fmt_money() {
6131
- awk -v v="$1" 'BEGIN{
6132
- if (v == "" || v+0 == 0) { printf "$0.00"; exit }
6133
- if (v+0 < 0.005 && v+0 > -0.005){ printf "%s<$0.01", (v+0 < 0 ? "-" : ""); exit }
6134
- if (v+0 < 0) { printf "-$%.2f", -v+0; exit }
6135
- printf "$%.2f", v
6136
- }'
6137
- }
6138
7427
 
6139
- printf '%s' "$brand"
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")"
7436
+ fi
7437
+ status_text=""
6140
7438
  if [[ "$transcript_model" == "failure" ]]; then
6141
- printf ' · last response failed'
7439
+ status_text=" · last response failed"
6142
7440
  elif [[ "$transcript_model" == "weave-router" ]]; then
6143
- printf ' · control acknowledgement'
7441
+ status_text=" · control acknowledgement"
6144
7442
  elif [[ -n "$transcript_model" ]]; then
6145
- printf ' · response model: %s' "$transcript_model"
6146
- fi
6147
- if [[ -n "$selected_display" && "$selected_display" != "?" ]]; then
6148
- printf ' · selected: %s' "$selected_display"
7443
+ if [[ -n "$picked" && "$transcript_model" != "$requested_norm" ]]; then
7444
+ status_text=" · you picked $picked → served $(short_model "$transcript_model")"
7445
+ else
7446
+ status_text=" · served $(short_model "$transcript_model")"
7447
+ fi
7448
+ elif [[ -n "$picked" ]]; then
7449
+ status_text=" · you picked $picked"
6149
7450
  fi
6150
7451
  if [[ -n "$session_cost_difference" && "$session_cost_difference" != "unknown" && "$transcript_model" != "failure" && "$transcript_model" != "weave-router" ]]; then
6151
- printf ' · est. cost difference %s' "$(fmt_money "$session_cost_difference")"
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
+ }')"
6152
7460
  fi
6153
7461
  if [[ "$has_pin_record" == "true" ]]; then
6154
- printf ' · last pin: %s' "$last_pin_model"
7462
+ status_text="$status_text · last pin: $last_pin_model"
6155
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"
6156
7482
  STATUSLINE_EOF
6157
7483
  chmod +x "$statusline_file"
6158
7484
  printf '%s\n' "$CLAUDE_STATUSLINE_MARKER" >"$statusline_ownership_file"
@@ -6197,22 +7523,28 @@ write_claude_settings() {
6197
7523
  # Setting ANTHROPIC_BASE_URL makes Claude Code treat us as non-first-party.
6198
7524
  # Force tool-search deferral to match first-party Claude Code; "auto" can inline
6199
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
6200
7532
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
6201
- jq -n --arg url "$base_url" --arg sl "$statusline_path_for_settings" --arg statusline_install "$statusline_install" '{
6202
- env: { ANTHROPIC_BASE_URL: $url, ENABLE_TOOL_SEARCH: "true" },
6203
- 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: {
6204
7536
  commit: "Co-Authored-By: Weave Router <router@weaveos.com>",
6205
7537
  pr: "🤖 Generated with [Weave Router](https://router.workweave.ai)"
6206
- }
6207
- } + (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"
6208
7540
  else
6209
- jq -n --arg url "$base_url" --arg header "$custom_headers" --arg sl "$statusline_path_for_settings" --arg statusline_install "$statusline_install" '{
6210
- env: { ANTHROPIC_BASE_URL: $url, ANTHROPIC_CUSTOM_HEADERS: $header, ENABLE_TOOL_SEARCH: "true" },
6211
- 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: {
6212
7544
  commit: "Co-Authored-By: Weave Router <router@weaveos.com>",
6213
7545
  pr: "🤖 Generated with [Weave Router](https://router.workweave.ai)"
6214
- }
6215
- } + (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"
6216
7548
  fi
6217
7549
 
6218
7550
  # Merge with existing settings. Deep-merge env and replace statusLine only
@@ -6230,13 +7562,29 @@ write_claude_settings() {
6230
7562
  | (if (.env | length) == 0 then del(.env) else . end)
6231
7563
  | del(.apiKeyHelper)
6232
7564
  | (if $b.statusLine then .statusLine = $b.statusLine else . end)
6233
- | (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)
6234
7579
  ' "$settings_file" "$tmp_patch")"
6235
7580
  printf '%s\n' "$merged" >"$settings_file"
6236
7581
  else
6237
7582
  cp "$tmp_patch" "$settings_file"
6238
7583
  fi
6239
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
6240
7588
 
6241
7589
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
6242
7590
  jq -n --arg header "$custom_headers" --arg router_url "$base_url" '{
@@ -6315,4 +7663,4 @@ verify_install
6315
7663
  # ---------- done ----------
6316
7664
 
6317
7665
  announce_done "Claude Code"
6318
- [ "$mode" = "update" ] || print_uninstall_hint
7666
+ finish_install "Claude Code" claude