@weave-os/router 0.2.29 → 0.2.31

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
@@ -107,7 +111,9 @@ export PATH="$PATH:$HOME/.weave/bin"
107
111
  # ---------- defaults ----------
108
112
 
109
113
  # The public hosted Weave Router URL. Override with --base-url for self-hosted.
110
- HOSTED_BASE_URL="https://router.workweave.ai"
114
+ HOSTED_BASE_URL="https://router.weaveos.com"
115
+ # Pre-rebrand hosted endpoint; still vouched for in settings written by older installs.
116
+ LEGACY_HOSTED_BASE_URL="https://router.workweave.ai"
111
117
  DEFAULT_BASE_URL="${WEAVE_ROUTER_URL:-$HOSTED_BASE_URL}"
112
118
  # npm package name is supplied by the Node wrapper; direct shell installs keep
113
119
  # the current package name; WEAVE_ROUTER_NPM_PACKAGE remains an escape hatch for
@@ -126,6 +132,7 @@ email_explicit="false"
126
132
  return_url=""
127
133
  non_interactive="false"
128
134
  quiet="false"
135
+ attribution="true"
129
136
  router_key_header="X-Weave-Router-Key"
130
137
  # Target tool whose config we patch. "claude" (default) writes Claude Code
131
138
  # settings.json; "codex" writes ~/.codex/config.toml; "opencode" merges a
@@ -137,6 +144,10 @@ router_key_header="X-Weave-Router-Key"
137
144
  # prompt for the choice.
138
145
  target="claude"
139
146
  target_explicit="false"
147
+ # Wire format the Copilot CLI provider speaks to the router: anthropic
148
+ # (/v1/messages) or openai (/v1/responses).
149
+ copilot_wire="anthropic"
150
+ copilot_wire_explicit="false"
140
151
 
141
152
  # Operation mode. "install" (default) writes/refreshes config. "update" is a
142
153
  # never-prompting install that reuses the key already on disk. "off"/"on"/
@@ -155,6 +166,7 @@ setup_codex="false"
155
166
  # `set -u` would not. --json switches the output to the raw API payload.
156
167
  models_args=""
157
168
  models_json="false"
169
+ models_auto_target="false"
158
170
 
159
171
  # --lsp <langs>: comma-separated languages whose language servers to install
160
172
  # for the pi extension's `lsp` tool (pi target only). Empty = don't install any.
@@ -168,6 +180,11 @@ rotate_key="false"
168
180
  api_key_source=""
169
181
  # Set by verify_install; a return URL is opened only after both probes pass.
170
182
  install_verification_succeeded="false"
183
+ # Set by verify_install: valid | rejected | unverified (router unreachable),
184
+ # or empty when there was no key to check.
185
+ key_verdict=""
186
+ # Holds the HTTP status of the last /validate probe ("000" when unreachable).
187
+ validate_status_file=""
171
188
 
172
189
  # ---------- helpers ----------
173
190
 
@@ -215,6 +232,7 @@ uninstall_cmd() {
215
232
  codex) cmd="$cmd --codex" ;;
216
233
  opencode) cmd="$cmd --opencode" ;;
217
234
  pi) cmd="$cmd --pi" ;;
235
+ copilot) cmd="$cmd --copilot" ;;
218
236
  esac
219
237
  [ "$scope" = "project" ] && cmd="$cmd --scope project"
220
238
  [ -n "$install_dir" ] && cmd="$cmd --dir $(printf '%q' "$install_dir")"
@@ -229,6 +247,25 @@ print_uninstall_hint() {
229
247
  "$C_BOLD" "$C_RESET" "$C_CYAN" "$(uninstall_cmd)" "$C_RESET"
230
248
  }
231
249
 
250
+ # offer_launch asks to start the client named in $1 (command in the remaining
251
+ # args) so a working interactive install ends in the product. The client runs
252
+ # as a child, not via exec, so the EXIT trap still removes the temp files.
253
+ offer_launch() {
254
+ local label="$1"; shift
255
+ [ "${WEAVE_SETUP_DEFER_LAUNCH:-}" != "1" ] && [ "$non_interactive" = "false" ] && [ "$quiet" != "true" ] \
256
+ && [ -t 0 ] && [ -t 1 ] && command -v "${!#}" >/dev/null 2>&1 || return 0
257
+ local answer=""
258
+ printf "\n%sStart %s now?%s [Y/n] " "$C_BOLD" "$label" "$C_RESET" >/dev/tty
259
+ read -r answer </dev/tty || answer="n"
260
+ case "$answer" in
261
+ ""|y|Y|yes|Yes) ;;
262
+ *) return 0 ;;
263
+ esac
264
+ local launch_status=0
265
+ "$@" </dev/tty || launch_status=$?
266
+ exit "$launch_status"
267
+ }
268
+
232
269
  # ---------- banner ----------
233
270
  #
234
271
  # Print the WEAVE wordmark in brand orange. Skipped under --quiet or when
@@ -241,6 +278,7 @@ print_banner() {
241
278
  codex) target_label="Codex installer" ;;
242
279
  opencode) target_label="opencode installer" ;;
243
280
  pi) target_label="pi installer" ;;
281
+ copilot) target_label="GitHub Copilot CLI installer" ;;
244
282
  *) target_label="Claude Code installer" ;;
245
283
  esac
246
284
  printf '\n'
@@ -285,6 +323,9 @@ _spin_cleanup() {
285
323
  if [ -n "$spin_log" ]; then
286
324
  rm -f "$spin_log" 2>/dev/null || true
287
325
  fi
326
+ if [ -n "${validate_status_file:-}" ]; then
327
+ rm -f "$validate_status_file" 2>/dev/null || true
328
+ fi
288
329
  # Also restore stty echo in case we died mid-keypaste prompt. macOS
289
330
  # `[ -r /dev/tty ]` returns true even when the underlying device errors
290
331
  # on open (ENXIO "Device not configured") under `curl | sh` and CI, so
@@ -348,13 +389,38 @@ spin() {
348
389
  fi
349
390
  }
350
391
 
392
+ # usage is the short, task-grouped help. The comment block at the top of this
393
+ # file is the full reference.
351
394
  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
395
  print_banner
357
- awk 'NR<2 { next } /^set -euo/ { exit } { sub(/^# ?/, ""); print }' "$0"
396
+ local npx="npx $npm_package_name"
397
+ cat <<USAGE
398
+ Set up
399
+ $npx open the setup page to get a key
400
+ $npx --claude | --codex install for Claude Code or Codex
401
+ $npx setup --claude --codex install for both (one key prompt)
402
+ $npx --opencode | --pi install for opencode or pi
403
+ $npx --copilot add Weave Router to Copilot CLI's /model picker
404
+
405
+ Every day
406
+ $npx status is each tool routed, signed in, working?
407
+ $npx off --claude go direct to Anthropic (on --claude to undo)
408
+ $npx models which models the router can pick
409
+ $npx update --claude refresh an install without prompting
410
+
411
+ Accounts
412
+ $npx login claude | codex use your Claude or ChatGPT subscription
413
+ $npx accounts list show enrolled subscriptions
414
+
415
+ Options
416
+ --scope project | --dir <path> install for a repo or a throwaway dir
417
+ --base-url <url> | --local self-hosted or local router
418
+ --rotate-key replace the saved key
419
+ --no-attribution don't credit Weave Router in commits
420
+ --uninstall remove the router from every tool
421
+
422
+ Full reference: https://github.com/weave-os/router/blob/main/install/README.md
423
+ USAGE
358
424
  exit "${1:-0}"
359
425
  }
360
426
 
@@ -454,6 +520,17 @@ claude_statusline_configured() {
454
520
  jq -e 'has("statusLine") and (.statusLine != null)' "$settings_path" >/dev/null 2>&1
455
521
  }
456
522
 
523
+ # Git Bash rewrites $HOME's /c/... form to C:/... in arguments to native
524
+ # executables such as jq.exe, so the stored command can use either form.
525
+ statusline_commands_match() {
526
+ local first_mixed second_mixed
527
+ [ "$1" = "$2" ] && return 0
528
+ command -v cygpath >/dev/null 2>&1 || return 1
529
+ first_mixed="$(cygpath -m -- "$1" 2>/dev/null)" && [ -n "$first_mixed" ] || return 1
530
+ second_mixed="$(cygpath -m -- "$2" 2>/dev/null)" && [ -n "$second_mixed" ] || return 1
531
+ [ "$first_mixed" = "$second_mixed" ]
532
+ }
533
+
457
534
  # claude_statusline_router_owned reports whether a settings entry points at the
458
535
  # router's statusline. Existing scripts prove ownership with the marker; when a
459
536
  # script is missing, the adjacent ownership marker proves that the router wrote
@@ -462,7 +539,7 @@ claude_statusline_router_owned() {
462
539
  local settings_path="$1" expected_command="$2" script_path="$3" ownership_marker_path="$4" configured_command
463
540
  [ -f "$settings_path" ] || return 1
464
541
  configured_command="$(jq -r '.statusLine.command // empty' "$settings_path" 2>/dev/null || true)"
465
- [ "$configured_command" = "$expected_command" ] || return 1
542
+ statusline_commands_match "$configured_command" "$expected_command" || return 1
466
543
  if [ -f "$script_path" ]; then
467
544
  if grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$script_path" 2>/dev/null; then
468
545
  return 0
@@ -555,6 +632,10 @@ resolve_user_email() {
555
632
  printf '%s' "$candidate"
556
633
  return
557
634
  fi
635
+ if [ "${WEAVE_SETUP_IDENTITY_RESOLVED:-}" = "1" ]; then
636
+ normalize_email "${WEAVE_SETUP_SHARED_EMAIL:-}"
637
+ return
638
+ fi
558
639
  if [ -n "${WEAVE_USER_EMAIL:-}" ]; then
559
640
  candidate="$(normalize_email "$WEAVE_USER_EMAIL")"
560
641
  if [ -z "$candidate" ]; then
@@ -914,10 +995,20 @@ TOML
914
995
  type = "command"
915
996
  command = "${esc_status}"
916
997
 
998
+ [[hooks.UserPromptSubmit]]
999
+ [[hooks.UserPromptSubmit.hooks]]
1000
+ type = "command"
1001
+ command = "${esc_status}"
1002
+
917
1003
  [[hooks.Stop]]
918
1004
  [[hooks.Stop.hooks]]
919
1005
  type = "command"
920
1006
  command = "${esc_status}"
1007
+
1008
+ [[hooks.PreCompact]]
1009
+ [[hooks.PreCompact.hooks]]
1010
+ type = "command"
1011
+ command = "${esc_status}"
921
1012
  TOML
922
1013
  )${directive_hook_block}"
923
1014
  if [ "${WEAVE_CAPTURE_LLM_CLASSIFIER:-}" = "1" ]; then
@@ -929,10 +1020,6 @@ matcher = "spawn_agent"
929
1020
  type = "command"
930
1021
  command = "${esc_status}"
931
1022
 
932
- [[hooks.PreCompact]]
933
- [[hooks.PreCompact.hooks]]
934
- type = "command"
935
- command = "${esc_status}"
936
1023
  TOML
937
1024
  )"
938
1025
  fi
@@ -1279,10 +1366,12 @@ write_pi_models_config() {
1279
1366
  { id: "claude-sonnet-5-5", name: "Claude Sonnet 5.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 128000 },
1280
1367
  { id: "claude-opus-4-7", name: "Claude Opus 4.7 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 64000 },
1281
1368
  { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 64000 },
1369
+ { id: "claude-haiku-5-5", name: "Claude Haiku 5.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 128000 },
1282
1370
  { id: "claude-haiku-4-5", name: "Claude Haiku 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 200000, maxTokens: 32000 },
1283
1371
  { id: "gpt-6-astra", name: "GPT-6 Astra (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1284
1372
  { id: "gpt-6-sol", name: "GPT-6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1285
1373
  { id: "gpt-6.1-sol", name: "GPT-6.1 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1374
+ { id: "gpt-6.1-terra", name: "GPT-6.1 Terra (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1286
1375
  { id: "gpt-6-luna", name: "GPT-6 Luna (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1287
1376
  { id: "gpt-5.6-sol", name: "GPT-5.6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
1288
1377
  { id: "grok-4.5", name: "Grok 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 },
@@ -1425,6 +1514,146 @@ resolve_user_name() {
1425
1514
  printf '%s' "$candidate"
1426
1515
  }
1427
1516
 
1517
+ # write_copilot_providers merges a managed `weave` provider and its `weave/auto`
1518
+ # model into GitHub Copilot CLI's providers.json. Copilot lists providers.json
1519
+ # models in /model next to the GitHub-hosted ones, so nothing replaces
1520
+ # Copilot's own endpoint (unlike COPILOT_PROVIDER_BASE_URL, which switches the
1521
+ # whole CLI into single-provider BYOK mode). Other providers and models are kept.
1522
+ # The router authenticates off X-Weave-Router-Key, so no apiKey is set: Copilot
1523
+ # would forward it as x-api-key / Authorization, which the router reads as BYOK.
1524
+ # chmod 600 — the headers hold the key.
1525
+ #
1526
+ # Usage: write_copilot_providers <providers_file> <base_url> <api_key> [user_email] [user_name]
1527
+ write_copilot_providers() {
1528
+ local config_file="$1" block_url="$2" block_key="$3" block_email="${4:-}" block_name="${5:-}"
1529
+ local provider model merged
1530
+ provider="$(jq -n \
1531
+ --arg url "$block_url" \
1532
+ --arg wire "$copilot_wire" \
1533
+ --arg key "$block_key" \
1534
+ --arg email "$block_email" \
1535
+ --arg name "$block_name" '
1536
+ {
1537
+ name: "weave",
1538
+ headers: (
1539
+ {"X-Weave-Router-Key": $key, "X-App": "copilot"}
1540
+ | (if $email != "" then . + {"X-Weave-User-Email": $email} else . end)
1541
+ | (if $name != "" then . + {"X-Weave-User-Name": $name } else . end)
1542
+ )
1543
+ }
1544
+ + (if $wire == "openai"
1545
+ then {type: "openai", baseUrl: ($url + "/v1"), wireApi: "responses"}
1546
+ else {type: "anthropic", baseUrl: $url} end)
1547
+ ')"
1548
+ # modelId names a well-known Copilot model so the CLI applies its tool-use
1549
+ # and prompting defaults; the router still picks the real model every turn.
1550
+ model="$(jq -n --arg wire "$copilot_wire" '
1551
+ {
1552
+ id: "auto",
1553
+ provider: "weave",
1554
+ name: "Weave Router",
1555
+ modelId: (if $wire == "openai" then "gpt-5.4" else "claude-sonnet-4" end),
1556
+ maxPromptTokens: 400000,
1557
+ maxOutputTokens: 32000
1558
+ }
1559
+ ')"
1560
+ if [ -f "$config_file" ]; then
1561
+ merged="$(jq --argjson provider "$provider" --argjson model "$model" '
1562
+ .providers = ([(.providers // [])[] | select(.name != "weave")] + [$provider])
1563
+ | .models = ([(.models // [])[] | select(.provider != "weave")] + [$model])
1564
+ ' "$config_file")"
1565
+ else
1566
+ merged="$(jq -n --argjson provider "$provider" --argjson model "$model" \
1567
+ '{providers: [$provider], models: [$model]}')"
1568
+ fi
1569
+ (umask 077 && printf '%s\n' "$merged" >"$config_file")
1570
+ chmod 600 "$config_file"
1571
+ }
1572
+
1573
+ # set_copilot_default_model makes weave/auto Copilot's default model and parks
1574
+ # whatever default was there before, so off/uninstall can put it back.
1575
+ set_copilot_default_model() {
1576
+ local current="" direct="" merged
1577
+ if [ -f "$copilot_settings_file" ]; then
1578
+ current="$(jq -r '.model // empty' "$copilot_settings_file" 2>/dev/null || true)"
1579
+ fi
1580
+ if [ -f "$copilot_parked_file" ]; then
1581
+ direct="$(jq -r '.direct_model // empty' "$copilot_parked_file" 2>/dev/null || true)"
1582
+ fi
1583
+ case "$current" in ""|weave/*) ;; *) direct="$current" ;; esac
1584
+ jq -n --arg direct "$direct" '{direct_model: $direct, router_model: "weave/auto"}' >"$copilot_parked_file"
1585
+ chmod 600 "$copilot_parked_file"
1586
+ if [ -f "$copilot_settings_file" ]; then
1587
+ merged="$(jq '.model = "weave/auto"' "$copilot_settings_file")"
1588
+ else
1589
+ merged="$(jq -n '{model: "weave/auto"}')"
1590
+ fi
1591
+ printf '%s\n' "$merged" >"$copilot_settings_file"
1592
+ }
1593
+
1594
+ # copilot_skill_names lists the router directives installed as Copilot skills.
1595
+ # Copilot exposes ~/.copilot/skills/<name> as /<name>, so Codex's skill bodies
1596
+ # are reused with the sigil and client names rewritten. Codex-only toggles and
1597
+ # skills that depend on Codex session state are excluded.
1598
+ copilot_skill_names() {
1599
+ weave_registry_skill_assets codex | grep -vxE 'disable-routing|router-session|router-models|models' || true
1600
+ }
1601
+
1602
+ # install_copilot_skills installs each router directive as a Copilot skill.
1603
+ install_copilot_skills() {
1604
+ local canonical candidate skill_src dst_dir dst_file emit_src scope_args body installed=""
1605
+ scope_args=""
1606
+ [ -n "$install_dir" ] && scope_args=" --dir $(printf '%q' "$install_dir")"
1607
+ while IFS= read -r canonical; do
1608
+ [ -n "$canonical" ] || continue
1609
+ skill_src=""
1610
+ for candidate in \
1611
+ "$script_dir/codex-skills/$canonical/SKILL.md" \
1612
+ "$script_dir/../codex-skills/$canonical/SKILL.md"
1613
+ do
1614
+ [ -f "$candidate" ] || continue
1615
+ skill_src="$candidate"
1616
+ break
1617
+ done
1618
+ [ -n "$skill_src" ] || continue
1619
+ grep -Fq "<!-- weave-router managed $canonical skill -->" "$skill_src" || continue
1620
+ dst_dir="$copilot_dir/skills/$canonical"
1621
+ dst_file="$dst_dir/SKILL.md"
1622
+ if [ -L "$copilot_dir/skills" ] || [ -L "$dst_dir" ] || [ -L "$dst_file" ] || [ -L "$dst_dir/scripts" ] || [ -L "$dst_dir/scripts/emit.sh" ]; then
1623
+ warn "Copilot skill path contains a symlink; leaving /$canonical untouched."
1624
+ continue
1625
+ fi
1626
+ if [ -e "$dst_file" ] && { [ ! -f "$dst_file" ] || ! grep -Fq "<!-- weave-router managed $canonical skill -->" "$dst_file"; }; then
1627
+ warn "A user-owned Copilot $canonical skill already exists at $dst_file; leaving it untouched."
1628
+ continue
1629
+ fi
1630
+ mkdir -p "$dst_dir"
1631
+ body="$(<"$skill_src")"
1632
+ body="${body//\{\{SCOPE\}\}/$scope_args}"
1633
+ # shellcheck disable=SC2016 # literal backticks and $ in the sed patterns
1634
+ printf '%s\n' "$body" | sed \
1635
+ -e 's/`\$\([a-z][a-z-]*\)/`\/\1/g' \
1636
+ -e 's/(or \$\([a-z][a-z-]*\))/(or \/\1)/g' \
1637
+ -e 's/--codex/--copilot/g' \
1638
+ -e 's/`codex` launch/`copilot` launch/g' \
1639
+ -e 's/Codex/Copilot CLI/g' >"$dst_file"
1640
+ emit_src="${skill_src%/SKILL.md}/scripts/emit.sh"
1641
+ if [ -f "$emit_src" ]; then
1642
+ mkdir -p "$dst_dir/scripts"
1643
+ cp "$emit_src" "$dst_dir/scripts/emit.sh"
1644
+ chmod +x "$dst_dir/scripts/emit.sh"
1645
+ fi
1646
+ installed="${installed:+$installed }/$canonical"
1647
+ done <<EOF
1648
+ $(copilot_skill_names)
1649
+ EOF
1650
+ if [ -n "$installed" ]; then
1651
+ ok "Copilot skills installed: $installed"
1652
+ else
1653
+ skip "Copilot skills not installed (no skill files next to this installer; use the npx installer for /force-model and friends)."
1654
+ fi
1655
+ }
1656
+
1428
1657
  # ---------- uninstall delegation ----------
1429
1658
  #
1430
1659
  # `--uninstall` flips this script into a thin shim for uninstall.sh: the
@@ -1519,6 +1748,9 @@ while [ $# -gt 0 ]; do
1519
1748
  --quiet)
1520
1749
  quiet="true"; shift
1521
1750
  ;;
1751
+ --no-attribution)
1752
+ attribution="false"; shift
1753
+ ;;
1522
1754
  --rotate-key)
1523
1755
  rotate_key="true"; shift
1524
1756
  ;;
@@ -1536,6 +1768,14 @@ while [ $# -gt 0 ]; do
1536
1768
  --pi)
1537
1769
  target="pi"; target_explicit="true"; shift
1538
1770
  ;;
1771
+ --copilot)
1772
+ target="copilot"; target_explicit="true"; shift
1773
+ ;;
1774
+ --wire)
1775
+ copilot_wire="${2:-}"; shift 2
1776
+ [ "$copilot_wire" = "anthropic" ] || [ "$copilot_wire" = "openai" ] || { err "--wire must be 'anthropic' or 'openai'."; exit 2; }
1777
+ copilot_wire_explicit="true"
1778
+ ;;
1539
1779
  --lsp)
1540
1780
  lsp_langs="${2:-}"; shift 2
1541
1781
  [ -n "$lsp_langs" ] || { err "--lsp requires a comma-separated language list (go,typescript,python,rust)."; exit 2; }
@@ -1627,9 +1867,36 @@ if [ "$mode" = "setup" ]; then
1627
1867
  [ -n "$return_url" ] && setup_args+=(--return-url "$return_url")
1628
1868
  [ -n "$install_dir" ] && setup_args+=(--dir "$install_dir")
1629
1869
  [ "$quiet" = "true" ] && setup_args+=(--quiet)
1870
+ [ "$attribution" = "false" ] && setup_args+=(--no-attribution)
1630
1871
  [ "$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
1872
+ # With both clients, the Claude run leaves its key and identity in a private
1873
+ # handoff file so the Codex run doesn't ask again. The key travels by file
1874
+ # and environment, never argv.
1875
+ setup_handoff=""
1876
+ shared_key=""
1877
+ shared_email=""
1878
+ identity_resolved=""
1879
+ if [ "$setup_claude" = "true" ] && [ "$setup_codex" = "true" ]; then
1880
+ setup_handoff="$(mktemp -t weave-setup.XXXXXX)"
1881
+ chmod 600 "$setup_handoff"
1882
+ fi
1883
+ if [ "$setup_claude" = "true" ]; then
1884
+ WEAVE_SETUP_HANDOFF_FILE="$setup_handoff" WEAVE_SETUP_DEFER_LAUNCH="${setup_handoff:+1}" bash "$0" "${setup_args[@]}" --claude \
1885
+ || { setup_status=$?; [ -z "$setup_handoff" ] || rm -f "$setup_handoff"; exit "$setup_status"; }
1886
+ fi
1887
+ if [ -n "$setup_handoff" ]; then
1888
+ if [ -s "$setup_handoff" ]; then
1889
+ identity_resolved="1"
1890
+ { IFS= read -r shared_key || true; IFS= read -r shared_email || true; } <"$setup_handoff"
1891
+ fi
1892
+ rm -f "$setup_handoff"
1893
+ fi
1894
+ if [ "$setup_codex" = "true" ]; then
1895
+ WEAVE_SETUP_SHARED_KEY="$shared_key" WEAVE_SETUP_SHARED_EMAIL="$shared_email" \
1896
+ WEAVE_SETUP_IDENTITY_RESOLVED="$identity_resolved" WEAVE_SETUP_DEFER_LAUNCH="${setup_handoff:+1}" \
1897
+ bash "$0" "${setup_args[@]}" --codex
1898
+ fi
1899
+ [ -z "$shared_key" ] || [ -n "$install_dir" ] || offer_launch "Claude Code" claude
1633
1900
  exit 0
1634
1901
  fi
1635
1902
 
@@ -1637,6 +1904,15 @@ if [ -n "$return_url" ] && [ "$mode" != "install" ]; then
1637
1904
  err "--return-url is supported only for install (or setup with one explicit target)."
1638
1905
  exit 2
1639
1906
  fi
1907
+ # The Windows PowerShell command passes the URL by env: npx.cmd re-parses
1908
+ # arguments through cmd.exe, which splits a URL at '&'.
1909
+ if [ -z "$return_url" ] && [ "$mode" = "install" ] && [ -n "${WEAVE_ROUTER_RETURN_URL:-}" ]; then
1910
+ return_url="$WEAVE_ROUTER_RETURN_URL"
1911
+ case "$return_url" in
1912
+ http://*|https://*) ;;
1913
+ *) err "WEAVE_ROUTER_RETURN_URL must be an http:// or https:// URL."; exit 2 ;;
1914
+ esac
1915
+ fi
1640
1916
 
1641
1917
  # --lsp is a pi-extension feature, so it implies the pi target; combining it
1642
1918
  # with another explicit target is a contradiction, not a preference.
@@ -1667,6 +1943,11 @@ if [ "$mode" = "login" ]; then
1667
1943
  esac
1668
1944
  elif [ "$mode" = "accounts" ] || [ "$mode" = "status" ]; then
1669
1945
  target_explicit="true"
1946
+ elif [ "$mode" = "models" ] && [ "$target_explicit" != "true" ]; then
1947
+ # Model selection belongs to the installation, not the client, so any
1948
+ # installed client's endpoint and key will do: Claude Code, then Codex.
1949
+ models_auto_target="true"
1950
+ target_explicit="true"
1670
1951
  fi
1671
1952
 
1672
1953
  # Toggle verbs only flip config install.sh already wrote: no key, no identity,
@@ -1680,7 +1961,7 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ]; then
1680
1961
  if [ "$mode" = "models" ]; then
1681
1962
  err "'models' requires an explicit client: --claude or --codex."
1682
1963
  else
1683
- err "'$mode' requires an explicit client: --claude, --codex, or --opencode."
1964
+ err "'$mode' requires an explicit client: --claude, --codex, --opencode, or --copilot."
1684
1965
  fi
1685
1966
  exit 2
1686
1967
  fi
@@ -1727,6 +2008,17 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ] && [ "$target" = "pi" ];
1727
2008
  exit 2
1728
2009
  fi
1729
2010
 
2011
+ if [ "$copilot_wire_explicit" = "true" ] && [ "$target" != "copilot" ]; then
2012
+ err "--wire only applies to --copilot."
2013
+ exit 2
2014
+ fi
2015
+ # Copilot CLI reads providers.json from the user's COPILOT_HOME only, and the
2016
+ # file holds the router key in plain text, so there is no project scope.
2017
+ if [ "$target" = "copilot" ] && [ "$scope" = "project" ]; then
2018
+ 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."
2019
+ exit 2
2020
+ fi
2021
+
1730
2022
  if [ -z "$base_url" ]; then
1731
2023
  base_url="$DEFAULT_BASE_URL"
1732
2024
  fi
@@ -1747,13 +2039,15 @@ if [ "$target_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ -r
1747
2039
  printf " %s2)%s Codex %s— patches ~/.codex/config.toml (or <repo>/.codex/)%s\n" "$C_BRAND" "$C_RESET" "$C_DIM" "$C_RESET"
1748
2040
  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
2041
  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"
2042
+ 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"
2043
+ printf "Choose %s[1/2/3/4/5]%s (default %s1%s): " "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET"
1751
2044
  read -r target_choice </dev/tty || target_choice=""
1752
2045
  case "${target_choice:-1}" in
1753
2046
  1|""|claude|c|C) target="claude" ;;
1754
2047
  2|codex|x|X) target="codex" ;;
1755
2048
  3|opencode|o|O) target="opencode" ;;
1756
2049
  4|pi|p|P) target="pi" ;;
2050
+ 5|copilot|g|G) target="copilot" ;;
1757
2051
  *) err "Invalid choice: $target_choice."; exit 2 ;;
1758
2052
  esac
1759
2053
  fi
@@ -1763,6 +2057,11 @@ fi
1763
2057
  # not a bare "Install scope:" line. Target prompt above already finalized
1764
2058
  # $target, so the banner's per-target label reflects the user's choice.
1765
2059
  # Toggle verbs stay terse — skip the banner so `status` prints one clean line.
2060
+ if [ "$target" = "copilot" ] && [ "$scope" = "project" ]; then
2061
+ 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."
2062
+ exit 2
2063
+ fi
2064
+
1766
2065
  [ "$mode" = "install" ] && print_banner
1767
2066
 
1768
2067
  # ---------- interactive scope prompt ----------
@@ -1772,7 +2071,7 @@ fi
1772
2071
  # they keep the user-scope default unless the caller explicitly selects a
1773
2072
  # project scope. Non-interactive installs (CI, `curl | sh --non-interactive`)
1774
2073
  # silently use the "user" default.
1775
- if [ "$mode" = "install" ] && [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ -r /dev/tty ]; then
2074
+ if [ "$mode" = "install" ] && [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interactive" = "false" ] && [ "$target" != "copilot" ] && [ -r /dev/tty ]; then
1776
2075
  # Per-target paths so the prompt text matches what actually gets written.
1777
2076
  case "$target" in
1778
2077
  codex)
@@ -1863,7 +2162,7 @@ fi
1863
2162
  # payloads with jq regardless of which client's config supplied the endpoint,
1864
2163
  # so require it there too rather than dying mid-render on `jq: command not
1865
2164
  # found`. Installing Codex itself still needs no jq.
1866
- if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] \
2165
+ if [ "$target" = "claude" ] || [ "$target" = "opencode" ] || [ "$target" = "pi" ] || [ "$target" = "copilot" ] \
1867
2166
  || { [ "$mode" = "models" ] && [ "$target" = "codex" ]; }; then
1868
2167
  ensure_jq
1869
2168
  fi
@@ -1906,6 +2205,12 @@ case "$target" in
1906
2205
  warn "Continuing — models.json/settings.json will be written and take effect once pi is installed."
1907
2206
  fi
1908
2207
  ;;
2208
+ copilot)
2209
+ if ! command -v copilot >/dev/null 2>&1; then
2210
+ warn "'copilot' not found on PATH. Install with 'npm install -g @github/copilot', then re-run this script."
2211
+ warn "Continuing — providers.json will be written and take effect once Copilot CLI is installed."
2212
+ fi
2213
+ ;;
1909
2214
  esac
1910
2215
  fi
1911
2216
 
@@ -1924,6 +2229,7 @@ WEAVE_REGISTRY_DATA=$(cat <<'WEAVE_REGISTRY_EOF'
1924
2229
  # canonical|aliases|capability|claude|codex|opencode|pi|cursor|adapter
1925
2230
  # aliases are comma-separated; client columns are yes/no. adapter is the native asset kind.
1926
2231
  force-model|fm|prompt|yes|yes|yes|yes|manual|command,skill
2232
+ force-parent||prompt|yes|yes|yes|yes|manual|command,skill
1927
2233
  unforce-model|ufm|prompt|yes|yes|yes|yes|manual|command,skill
1928
2234
  router-feedback|rf|prompt|yes|yes|yes|no|manual|command,skill
1929
2235
  router-off||local-toggle|yes|yes|no|no|manual|command,skill
@@ -2183,6 +2489,23 @@ elif [ "$target" = "pi" ]; then
2183
2489
  fi
2184
2490
 
2185
2491
  mkdir -p "$pi_dir"
2492
+ elif [ "$target" = "copilot" ]; then
2493
+ # Copilot CLI reads $COPILOT_HOME (default ~/.copilot). --dir is a throwaway
2494
+ # COPILOT_HOME, launched with COPILOT_HOME=<dir>/.copilot.
2495
+ if [ -n "$install_dir" ]; then
2496
+ copilot_dir="$install_dir/.copilot"
2497
+ else
2498
+ copilot_dir="${COPILOT_HOME:-$settings_base/.copilot}"
2499
+ fi
2500
+ copilot_providers_file="$copilot_dir/providers.json"
2501
+ copilot_settings_file="$copilot_dir/settings.json"
2502
+ copilot_parked_file="$copilot_dir/.weave-parked.json"
2503
+ # providers.json holds the router key, so never write it through a link.
2504
+ refuse_if_symlink "$copilot_dir"
2505
+ refuse_if_symlink "$copilot_providers_file"
2506
+ refuse_if_symlink "$copilot_settings_file"
2507
+ refuse_if_symlink "$copilot_parked_file"
2508
+ mkdir -p "$copilot_dir"
2186
2509
  else
2187
2510
  # opencode discovers config in this order: $XDG_CONFIG_HOME/opencode/opencode.json
2188
2511
  # (or ~/.config/opencode/opencode.json) for user scope, and opencode.json /
@@ -2357,6 +2680,14 @@ read_pi_key() {
2357
2680
  printf '%s' "$key"
2358
2681
  }
2359
2682
 
2683
+ # read_copilot_key prints the router key from the managed `weave` provider in
2684
+ # Copilot CLI's providers.json, or nothing.
2685
+ read_copilot_key() {
2686
+ key_source_is_own "$copilot_providers_file" || return 0
2687
+ jq -r '[(.providers // [])[] | select(.name == "weave") | .headers["X-Weave-Router-Key"] // empty][0] // empty' \
2688
+ "$copilot_providers_file" 2>/dev/null || true
2689
+ }
2690
+
2360
2691
  # read_installed_key prints the router key this install already has on disk, or
2361
2692
  # nothing, for whichever client is being installed. Reading it back is what makes
2362
2693
  # a re-run painless — see the token-handling section below. Defined up here
@@ -2375,6 +2706,7 @@ models_config_file_for_target() {
2375
2706
  codex) printf '%s' "$codex_config_file" ;;
2376
2707
  opencode) printf '%s' "$opencode_config_file" ;;
2377
2708
  pi) printf '%s' "$pi_models_file" ;;
2709
+ copilot) printf '%s' "$copilot_providers_file" ;;
2378
2710
  esac
2379
2711
  }
2380
2712
 
@@ -2410,6 +2742,7 @@ read_installed_key() {
2410
2742
  codex) read_codex_key "$codex_config_file" ;;
2411
2743
  opencode) read_opencode_key "$opencode_config_file" ;;
2412
2744
  pi) read_pi_key ;;
2745
+ copilot) read_copilot_key ;;
2413
2746
  esac
2414
2747
  }
2415
2748
 
@@ -2525,6 +2858,13 @@ resolve_installed_endpoint() {
2525
2858
  found="$(json_get "$pi_models_file" '.providers.weave.baseUrl')"
2526
2859
  fi
2527
2860
  ;;
2861
+ copilot)
2862
+ if key_source_is_own "$copilot_providers_file"; then
2863
+ found="$(jq -r '[(.providers // [])[] | select(.name == "weave") | .baseUrl // empty][0] // empty' "$copilot_providers_file" 2>/dev/null || true)"
2864
+ fi
2865
+ found="${found%/}"
2866
+ found="${found%/v1}"
2867
+ ;;
2528
2868
  esac
2529
2869
  printf '%s' "${found%/}"
2530
2870
  }
@@ -2546,6 +2886,7 @@ models_endpoint_is_trusted() {
2546
2886
  normalized_url="$(strip_trailing_slashes "$url")"
2547
2887
  [ "$base_url_explicit" = "true" ] && return 0
2548
2888
  [ "$normalized_url" = "$(strip_trailing_slashes "$HOSTED_BASE_URL")" ] && return 0
2889
+ [ "$normalized_url" = "$(strip_trailing_slashes "$LEGACY_HOSTED_BASE_URL")" ] && return 0
2549
2890
  [ -n "$base_src" ] && [ "$base_src" = "$key_src" ] && return 0
2550
2891
  # Project-scoped self-hosted installs intentionally split the endpoint and
2551
2892
  # key. The installer writes a gitignored marker beside the key; require that
@@ -2666,7 +3007,7 @@ prepare_claude_context_window() {
2666
3007
  model="${model:-sonnet}"
2667
3008
  case "$model" in
2668
3009
  *'[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) ;;
3010
+ 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
3011
  *) err "Cannot assert 1M support for '$model'. Select a supported Sonnet/Opus/Fable model first; leaving it unchanged."; return 1 ;;
2671
3012
  esac
2672
3013
  context_managed_model="${model}[1m]"
@@ -2861,21 +3202,28 @@ toggle_claude() {
2861
3202
  esac
2862
3203
  }
2863
3204
 
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")"
3205
+ codex_routing_state() {
3206
+ local f="$codex_config_file"
3207
+ if [ ! -f "$f" ]; then
3208
+ printf 'absent\n'
3209
+ return 0
2878
3210
  fi
3211
+ awk '
3212
+ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*\]/ { has_weave = 1 }
3213
+ /^[[:space:]]*\[/ { in_section = 1 }
3214
+ !in_section && /^[[:space:]]*model_provider[[:space:]]*=[[:space:]]*"weave"[[:space:]]*$/ { active_weave = 1 }
3215
+ !in_section && /^[[:space:]]*model_provider[[:space:]]*=/ { has_active_provider = 1 }
3216
+ END {
3217
+ if (!has_weave) print "absent"
3218
+ else if (active_weave) print "on"
3219
+ else print (has_active_provider ? "absent" : "off")
3220
+ }
3221
+ ' "$f"
3222
+ }
3223
+
3224
+ toggle_codex() {
3225
+ local f="$codex_config_file" state tmp
3226
+ state="$(codex_routing_state)"
2879
3227
 
2880
3228
  case "$mode" in
2881
3229
  status)
@@ -3037,6 +3385,64 @@ toggle_opencode() {
3037
3385
  esac
3038
3386
  }
3039
3387
 
3388
+ # toggle_copilot flips Copilot CLI's default model between weave/auto and the
3389
+ # model it had before. The weave provider stays in providers.json either way,
3390
+ # so weave/auto remains selectable from /model while off.
3391
+ toggle_copilot() {
3392
+ local current="" direct="" has_weave="false" on="false" merged
3393
+ if [ -f "$copilot_settings_file" ]; then
3394
+ current="$(json_get "$copilot_settings_file" '.model')"
3395
+ fi
3396
+ if [ -f "$copilot_parked_file" ]; then
3397
+ direct="$(json_get "$copilot_parked_file" '.direct_model')"
3398
+ fi
3399
+ if [ -f "$copilot_providers_file" ] \
3400
+ && [ "$(jq -r '[(.providers // [])[] | select(.name == "weave")] | length > 0' "$copilot_providers_file" 2>/dev/null || true)" = "true" ]; then
3401
+ has_weave="true"
3402
+ fi
3403
+ case "$current" in weave/*) on="true" ;; esac
3404
+
3405
+ case "$mode" in
3406
+ status)
3407
+ if [ "$on" = "true" ]; then
3408
+ ok "Copilot CLI: ${C_BOLD}on${C_RESET} — default model is $current (via the Weave Router)."
3409
+ elif [ "$has_weave" = "true" ]; then
3410
+ ok "Copilot CLI: ${C_BOLD}off${C_RESET} — weave/auto is still in /model. Run 'on --copilot' to make it the default."
3411
+ else
3412
+ info "Copilot CLI: not configured for the router. Run the installer first."
3413
+ fi
3414
+ ;;
3415
+ off)
3416
+ if [ "$on" != "true" ]; then
3417
+ 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
3418
+ return 0
3419
+ fi
3420
+ if [ -n "$direct" ]; then
3421
+ merged="$(jq --arg model "$direct" '.model = $model' "$copilot_settings_file")"
3422
+ else
3423
+ merged="$(jq 'del(.model)' "$copilot_settings_file")"
3424
+ fi
3425
+ printf '%s\n' "$merged" >"$copilot_settings_file"
3426
+ if [ -n "$direct" ]; then
3427
+ ok "Copilot CLI is ${C_BOLD}off${C_RESET} — default model restored to $direct. weave/auto stays in /model."
3428
+ else
3429
+ ok "Copilot CLI is ${C_BOLD}off${C_RESET} — back to Copilot's default model. weave/auto stays in /model."
3430
+ fi
3431
+ report_client_event off
3432
+ ;;
3433
+ on)
3434
+ if [ "$on" = "true" ]; then ok "Copilot CLI is already on — nothing to do."; return 0; fi
3435
+ if [ "$has_weave" != "true" ]; then
3436
+ warn "Copilot CLI isn't configured for the router. Run the installer first."
3437
+ return 0
3438
+ fi
3439
+ set_copilot_default_model
3440
+ ok "Copilot CLI is ${C_BOLD}on${C_RESET} (default model weave/auto via the Weave Router). Takes effect on your next copilot run."
3441
+ report_client_event on
3442
+ ;;
3443
+ esac
3444
+ }
3445
+
3040
3446
  # ---------- model selection ----------
3041
3447
  #
3042
3448
  # `models` reads and edits the installation's model/provider selection through
@@ -3054,7 +3460,7 @@ toggle_opencode() {
3054
3460
  # Public, unauthed catalog of everything the router can route to. Mounted in
3055
3461
  # both deployment modes, so it is the one listing that always works.
3056
3462
  MODELS_CATALOG_PATH="/v1/router/models"
3057
- MODELS_DASHBOARD_URL="https://router.workweave.ai/dashboard/settings"
3463
+ MODELS_DASHBOARD_URL="https://router.weaveos.com/models"
3058
3464
 
3059
3465
  # Set by models_api on every call.
3060
3466
  models_http_status=""
@@ -3100,19 +3506,36 @@ models_api_error() {
3100
3506
  # models_fail turns the status left by models_api into a message that says what
3101
3507
  # to do next, then exits. $1 names the attempted operation.
3102
3508
  models_fail() {
3103
- local what="$1" detail
3509
+ local what="$1" detail repair_command
3104
3510
  detail="$(models_api_error)"
3511
+ case "$detail" in
3512
+ subscription_owner_unavailable|subscription_accounts_unavailable|subscription_account_update_failed|subscription_account_delete_failed)
3513
+ err "The router couldn't finish ${what} just now. Nothing changed; try again in a minute."
3514
+ return ;;
3515
+ subscription_account_not_found)
3516
+ err "No enrolled account has that id. Run 'npx $npm_package_name accounts list' to see the ids."
3517
+ return ;;
3518
+ subscription_account_rejected)
3519
+ err "The router didn't accept that sign-in. Run 'npx $npm_package_name login claude' or 'login codex' again."
3520
+ return ;;
3521
+ esac
3105
3522
  case "$models_http_status" in
3106
3523
  ""|000)
3107
3524
  err "Could not reach the router at $base_url. Is it running?"
3108
3525
  ;;
3109
3526
  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
3527
+ # Preserve policy errors; invalid_key needs local setup instructions.
3528
+ if [ -n "$detail" ] && [ "$detail" != "invalid_key" ]; then
3113
3529
  err "$detail"
3114
3530
  else
3115
- err "The router rejected this installation's key. Re-run 'npx $npm_package_name --$target --rotate-key' to install a current one."
3531
+ err "Weave Router is not set up with a valid API key for $target in the $scope scope."
3532
+ printf ' The router at %s rejected the Router API key for this install (HTTP %s).\n' "$base_url" "$models_http_status" >&2
3533
+ repair_command="npx $npm_package_name --$target --scope $scope --rotate-key --base-url $(printf '%q' "$base_url")"
3534
+ [ -n "$install_dir" ] && repair_command="$repair_command --dir $(printf '%q' "$install_dir")"
3535
+ printf " Run '%s' and paste the complete rk_... key from %s, then retry this command.\n" "$repair_command" "$base_url" >&2
3536
+ if [ -n "${WEAVE_ROUTER_KEY:-}" ]; then
3537
+ printf ' WEAVE_ROUTER_KEY is set and overrides saved keys; replace or unset it before retrying.\n' >&2
3538
+ fi
3116
3539
  fi
3117
3540
  ;;
3118
3541
  404)
@@ -3123,11 +3546,15 @@ models_fail() {
3123
3546
  "$C_DIM" "$C_RESET" >&2
3124
3547
  ;;
3125
3548
  *)
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
3549
+ case "$detail" in
3550
+ "")
3551
+ case "$models_http_status" in
3552
+ 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." ;;
3553
+ *) err "$what failed (HTTP $models_http_status)." ;;
3554
+ esac
3555
+ ;;
3556
+ *) err "$what failed (HTTP $models_http_status): $detail" ;;
3557
+ esac
3131
3558
  ;;
3132
3559
  esac
3133
3560
  exit 1
@@ -3196,6 +3623,7 @@ models_list_catalog() {
3196
3623
  return 0
3197
3624
  fi
3198
3625
  printf "%s%sWeave Router %s%s %s· %s%s\n" "$C_BOLD" "$C_BRAND" "$what" "$C_RESET" "$C_DIM" "$base_url" "$C_RESET"
3626
+ 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
3627
  printf "%severything this router can route to%s\n\n" "$C_DIM" "$C_RESET"
3200
3628
  if [ "$what" = "providers" ]; then
3201
3629
  printf '%s' "$models_http_body" | jq -r '[.models[].provider] | unique[] | " " + .'
@@ -3206,9 +3634,7 @@ models_list_catalog() {
3206
3634
  (.[] | " " + .model)
3207
3635
  '
3208
3636
  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"
3637
+ printf "\n%sThis list is everything the router supports, not what your organization has turned on.%s\n" "$C_DIM" "$C_RESET"
3212
3638
  }
3213
3639
 
3214
3640
  models_list() {
@@ -3414,13 +3840,10 @@ open_url_in_browser() {
3414
3840
  open "$url" >/dev/null 2>&1
3415
3841
  ;;
3416
3842
  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
3843
+ # explorer.exe can open a File Explorer window instead of the browser,
3844
+ # and cmd.exe /c start would parse URL query separators such as '&'.
3845
+ command -v rundll32.exe >/dev/null 2>&1 || return 1
3846
+ rundll32.exe url.dll,FileProtocolHandler "$url" >/dev/null 2>&1
3424
3847
  ;;
3425
3848
  *)
3426
3849
  command -v xdg-open >/dev/null 2>&1 || return 1
@@ -3602,55 +4025,297 @@ run_login() {
3602
4025
  [ -n "$provider" ] || { err "Use 'login claude' or 'login codex'."; exit 2; }
3603
4026
  [ -z "$extra" ] || { err "Login accepts exactly one provider."; exit 2; }
3604
4027
  ensure_jq
4028
+ case "$provider" in
4029
+ claude|codex) models_api GET "/validate" || models_fail "checking Router setup" ;;
4030
+ *) err "Unknown subscription provider: $provider."; exit 2 ;;
4031
+ esac
3605
4032
  require_cmd openssl "Install OpenSSL to enroll a subscription account."
3606
4033
  case "$provider" in
3607
4034
  claude) run_login_claude ;;
3608
4035
  codex) run_login_codex ;;
3609
- *) err "Unknown subscription provider: $provider."; exit 2 ;;
4036
+ esac
4037
+ }
4038
+
4039
+ # capture_bounded prints the stdout of "$@", giving up after $1 seconds so a
4040
+ # stuck client CLI cannot hang the installer. Output goes through a file, not a
4041
+ # pipe, so a descendant that keeps stdout open cannot block the caller.
4042
+ capture_bounded() {
4043
+ local seconds="$1"; shift
4044
+ local out_file status=0
4045
+ out_file="$(mktemp -t weave-capture.XXXXXX)" || return 1
4046
+ "$@" </dev/null >"$out_file" 2>/dev/null &
4047
+ local pid=$!
4048
+ ( sleep "$seconds"; kill "$pid" 2>/dev/null; sleep 1; kill -9 "$pid" 2>/dev/null ) >/dev/null 2>&1 &
4049
+ local watcher=$!
4050
+ wait "$pid" || status=$?
4051
+ kill "$watcher" 2>/dev/null || true
4052
+ cat "$out_file"
4053
+ rm -f "$out_file"
4054
+ return "$status"
4055
+ }
4056
+
4057
+ claude_login_missing() {
4058
+ command -v claude >/dev/null 2>&1 || return 1
4059
+ local auth_status
4060
+ auth_status="$(capture_bounded 10 claude auth status --json || true)"
4061
+ printf '%s' "$auth_status" | jq -e '.loggedIn == false' >/dev/null 2>&1
4062
+ }
4063
+
4064
+ codex_login_missing() {
4065
+ command -v codex >/dev/null 2>&1 || return 1
4066
+ local login_status
4067
+ login_status="$(capture_bounded 10 env CODEX_HOME="$codex_dir" sh -c 'codex login status 2>&1' || true)"
4068
+ grep -q '^Not logged in' <<<"$login_status"
4069
+ }
4070
+
4071
+ # claude_routing_state prints "on <endpoint>", "nokey <endpoint>", "off" or
4072
+ # "absent" for this scope's saved Claude Code settings. In project scope the
4073
+ # gitignored settings.local.json overrides the committed file.
4074
+ claude_routing_state() {
4075
+ local effective_base key_settings_file="$settings_file"
4076
+ effective_base="$(json_get "$settings_file" '.env.ANTHROPIC_BASE_URL')"
4077
+ if [ "$scope" = "project" ] && [ -f "$local_settings_file" ]; then
4078
+ if jq -e '.env | has("ANTHROPIC_BASE_URL")' "$local_settings_file" >/dev/null 2>&1; then
4079
+ effective_base="$(json_get "$local_settings_file" '.env.ANTHROPIC_BASE_URL')"
4080
+ fi
4081
+ if jq -e '.env | has("ANTHROPIC_CUSTOM_HEADERS")' "$local_settings_file" >/dev/null 2>&1; then
4082
+ key_settings_file="$local_settings_file"
4083
+ fi
4084
+ fi
4085
+ if router_shaped_url "$effective_base" && claude_key_present "$key_settings_file"; then
4086
+ printf 'on %s\n' "$effective_base"
4087
+ elif router_shaped_url "$effective_base"; then
4088
+ printf 'nokey %s\n' "$effective_base"
4089
+ elif [ -f "$settings_dir/.weave-parked.json" ] || [ -n "$effective_base" ]; then
4090
+ printf 'off\n'
4091
+ else
4092
+ printf 'absent\n'
4093
+ fi
4094
+ }
4095
+
4096
+ # codex_hooks_trusted fails when Codex has not recorded a trust hash for any
4097
+ # hook in this config yet, which means it will ask for a review on next launch.
4098
+ # Codex keys trust records "<config path>:<event>:<group>:<hook>"; Weave Router
4099
+ # always installs a Stop hook in this config, so only a trusted Stop record for
4100
+ # this file counts. The installer has no TOML parser (jq only); unusual quoting
4101
+ # can only make status suggest an extra review.
4102
+ codex_hooks_trusted() {
4103
+ awk -v state_prefix="[hooks.state.\"$codex_config_file:stop:" '
4104
+ /^[[:space:]]*\[/ { in_state = (index($0, state_prefix) > 0) }
4105
+ in_state && /^[[:space:]]*trusted_hash[[:space:]]*=/ { found = 1 }
4106
+ END { exit(found ? 0 : 1) }
4107
+ ' "$codex_config_file" 2>/dev/null
4108
+ }
4109
+
4110
+ file_mtime() {
4111
+ stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null
4112
+ }
4113
+
4114
+ # newest_file prints the newest regular file in directory $1 whose name ends in
4115
+ # $2. The directory stays quoted so a cache path with spaces still matches.
4116
+ newest_file() {
4117
+ local file newest="" newest_time=0 file_time
4118
+ for file in "$1"/*"$2"; do
4119
+ [ -f "$file" ] || continue
4120
+ file_time="$(file_mtime "$file")" || continue
4121
+ if [ "$file_time" -gt "$newest_time" ]; then
4122
+ newest="$file"; newest_time="$file_time"
4123
+ fi
4124
+ done
4125
+ [ -n "$newest" ] && printf '%s\n' "$newest"
4126
+ }
4127
+
4128
+ time_ago() {
4129
+ local seconds=$(( $(date +%s) - $1 ))
4130
+ if [ "$seconds" -lt 60 ]; then printf 'just now'
4131
+ elif [ "$seconds" -lt 3600 ]; then printf '%sm ago' "$((seconds / 60))"
4132
+ elif [ "$seconds" -lt 86400 ]; then printf '%sh ago' "$((seconds / 3600))"
4133
+ else printf '%sd ago' "$((seconds / 86400))"
4134
+ fi
4135
+ }
4136
+
4137
+ # last_routed_turn summarizes the newest turn a client's status hook recorded.
4138
+ last_routed_turn() {
4139
+ local cache="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router" file detail=""
4140
+ case "$1" in
4141
+ claude)
4142
+ file="$(newest_file "$cache/claude-status" .line)" || return 1
4143
+ detail="$(head -c 512 "$file" | head -n 1)"
4144
+ detail="${detail#WEAVE ROUTER · }"
4145
+ ;;
4146
+ codex)
4147
+ # Codex rewrites the state on command-only replies too, so its mtime is
4148
+ # when the session last updated, not proof of a routed turn.
4149
+ file="$(newest_file "$cache/codex" .state)" || return 1
4150
+ detail="$(sed -n 's/^routed_model=//p' "$file" | head -n 1)"
4151
+ if [ -n "$detail" ]; then
4152
+ printf 'served %s (session updated %s)' "$detail" "$(time_ago "$(file_mtime "$file")")"
4153
+ else
4154
+ printf 'unknown; a session updated %s without recording the served model' "$(time_ago "$(file_mtime "$file")")"
4155
+ fi
4156
+ return 0
4157
+ ;;
4158
+ esac
4159
+ printf '%s%s' "$(time_ago "$(file_mtime "$file")")" "${detail:+ ($detail)}"
4160
+ }
4161
+
4162
+ status_problem() {
4163
+ printf ' %s!%s %s\n' "$C_YELLOW" "$C_RESET" "$1"
4164
+ [ -z "${2:-}" ] || printf ' %sfix:%s %s\n' "$C_DIM" "$C_RESET" "$2"
4165
+ }
4166
+
4167
+ # run_router_status prints one block per client configured in this scope, each
4168
+ # problem followed by the command that fixes it. It describes saved config, not
4169
+ # a running session.
4170
+ # print_copilot_status_row reports Copilot CLI only when a weave provider is
4171
+ # installed, so the status of users without Copilot is unchanged.
4172
+ print_copilot_status_row() {
4173
+ local copilot_dir providers settings model
4174
+ if [ -n "$install_dir" ]; then copilot_dir="$install_dir/.copilot"; else copilot_dir="${COPILOT_HOME:-$settings_base/.copilot}"; fi
4175
+ providers="$copilot_dir/providers.json"
4176
+ settings="$copilot_dir/settings.json"
4177
+ [ -f "$providers" ] && [ ! -L "$providers" ] || return 0
4178
+ [ "$(jq -r '[(.providers // [])[] | select(.name == "weave")] | length > 0' "$providers" 2>/dev/null || true)" = "true" ] || return 0
4179
+ model="$(json_get "$settings" '.model')"
4180
+ case "$model" in
4181
+ weave/*) printf ' %sCopilot CLI%s on, default model %s %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$model" "$C_DIM" "$copilot_dir" "$C_RESET" ;;
4182
+ *)
4183
+ printf ' %sCopilot CLI%s off, weave/auto is in /model but not the default\n' "$C_BOLD" "$C_RESET"
4184
+ printf ' %sturn on:%s %s on --copilot\n' "$C_DIM" "$C_RESET" "npx $npm_package_name"
4185
+ ;;
3610
4186
  esac
3611
4187
  }
3612
4188
 
3613
4189
  run_router_status() {
3614
- local saved_target codex_endpoint redacted_key
3615
- saved_target="$target"
4190
+ local npx="npx $npm_package_name" scope_flags="" redacted_key key_ok="false"
4191
+ local claude_state claude_endpoint codex_state codex_endpoint last_turn
4192
+ if [ -n "$install_dir" ]; then
4193
+ scope_flags=" --dir $(printf '%q' "$install_dir")"
4194
+ elif [ "$scope" = "project" ]; then
4195
+ scope_flags=" --scope project"
4196
+ fi
3616
4197
  settings_dir="$settings_base/.claude"
3617
4198
  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"
4199
+ local_settings_file=""
4200
+ [ "$scope" != "project" ] || local_settings_file="$settings_dir/settings.local.json"
4201
+ codex_dir="$settings_base/.codex"
4202
+ codex_config_file="$codex_dir/config.toml"
3626
4203
  if [ "${#api_key}" -gt 8 ]; then
3627
4204
  redacted_key="${api_key:0:3}…${api_key: -4}"
3628
4205
  else
3629
4206
  redacted_key="redacted"
3630
4207
  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'
4208
+
4209
+ printf '%sWeave Router status%s %s(%s scope; saved settings, not a running session)%s\n' \
4210
+ "$C_BOLD" "$C_RESET" "$C_DIM" "$scope" "$C_RESET"
4211
+ if [ -z "$base_url" ]; then
4212
+ printf ' Router not set up for Claude Code or Codex\n'
4213
+ elif [ -z "$api_key" ]; then
4214
+ printf ' Router %s\n' "$base_url"
4215
+ printf ' Key none saved\n'
4216
+ status_problem "No router key is saved for this router." "$npx update --$target$scope_flags"
4217
+ elif models_api GET "/validate"; then
4218
+ printf ' Router %s\n' "$base_url"
4219
+ key_ok="true"
4220
+ printf ' Key %s accepted (inference not checked)\n' "$redacted_key"
4221
+ elif [ "$models_http_status" = "401" ] || [ "$models_http_status" = "403" ]; then
4222
+ printf ' Router %s\n' "$base_url"
4223
+ printf ' Key %s rejected\n' "$redacted_key"
4224
+ status_problem "The router rejected this key." "$npx --$target$scope_flags --rotate-key"
4225
+ elif [ -z "$models_http_status" ] || [ "$models_http_status" = "000" ]; then
4226
+ printf ' Router %s\n' "$base_url"
4227
+ printf ' Key %s not checked\n' "$redacted_key"
4228
+ status_problem "Could not reach $base_url." "check your network, or pass --base-url if the router moved"
3634
4229
  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'
4230
+ printf ' Router %s\n' "$base_url"
4231
+ printf ' Key %s not checked\n' "$redacted_key"
4232
+ status_problem "The router answered HTTP $models_http_status; try again in a minute."
4233
+ fi
4234
+
4235
+ printf '\n'
4236
+ target="claude"
4237
+ claude_state="$(claude_routing_state)"
4238
+ claude_endpoint="${claude_state#* }"
4239
+ case "$claude_state" in
4240
+ on\ *)
4241
+ printf ' %sClaude Code%s on %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$settings_dir" "$C_RESET"
4242
+ [ "${claude_endpoint%/}" = "${base_url%/}" ] \
4243
+ || status_problem "Uses a different router ($claude_endpoint) than the key check above." "$npx status --claude$scope_flags"
4244
+ if ! command -v claude >/dev/null 2>&1; then
4245
+ status_problem "The claude command isn't on PATH." "install Claude Code: https://docs.claude.com/en/docs/claude-code"
4246
+ elif claude_login_missing; then
4247
+ status_problem "Claude Code isn't signed in." "run claude and type /login"
4248
+ fi
4249
+ if last_turn="$(last_routed_turn claude)"; then
4250
+ printf ' last routed turn %s\n' "$last_turn"
4251
+ else
4252
+ printf ' no routed turn yet\n'
4253
+ fi
4254
+ ;;
4255
+ nokey\ *)
4256
+ printf ' %sClaude Code%s router key missing %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$settings_dir" "$C_RESET"
4257
+ 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"
4258
+ ;;
4259
+ off)
4260
+ printf ' %sClaude Code%s off, talks to Anthropic directly %s(%s)%s\n' "$C_BOLD" "$C_RESET" "$C_DIM" "$settings_dir" "$C_RESET"
4261
+ printf ' %sturn on:%s %s on --claude%s\n' "$C_DIM" "$C_RESET" "$npx" "$scope_flags"
4262
+ ;;
4263
+ *)
4264
+ 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"
4265
+ ;;
4266
+ esac
4267
+
4268
+ target="codex"
4269
+ codex_state="$(codex_routing_state)"
4270
+ codex_endpoint="$(resolve_installed_endpoint)"
4271
+ case "$codex_state" in
4272
+ on)
4273
+ printf ' %sCodex%s on\n' "$C_BOLD" "$C_RESET"
4274
+ if [ -z "$codex_endpoint" ]; then
4275
+ status_problem "Couldn't read Codex's router endpoint from $codex_config_file." "$npx update --codex$scope_flags"
4276
+ elif [ "${codex_endpoint%/}" != "${base_url%/}" ]; then
4277
+ status_problem "Uses a different router ($codex_endpoint) than the key check above." "$npx status --codex$scope_flags"
4278
+ fi
4279
+ if ! command -v codex >/dev/null 2>&1; then
4280
+ status_problem "The codex command isn't on PATH." "npm install -g @openai/codex"
4281
+ elif codex_login_missing; then
4282
+ status_problem "Codex isn't signed in." "codex login"
4283
+ fi
4284
+ if grep -q 'codex-status' "$codex_config_file" 2>/dev/null && ! codex_hooks_trusted; then
4285
+ 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"
4286
+ fi
4287
+ if last_turn="$(last_routed_turn codex)"; then
4288
+ printf ' last routed turn %s\n' "$last_turn"
4289
+ else
4290
+ printf ' no routed turn yet\n'
4291
+ fi
4292
+ ;;
4293
+ off)
4294
+ printf " %sCodex%s off (uses Codex's default provider)\n" "$C_BOLD" "$C_RESET"
4295
+ printf ' %sturn on:%s %s on --codex%s\n' "$C_DIM" "$C_RESET" "$npx" "$scope_flags"
4296
+ ;;
4297
+ *)
4298
+ 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"
4299
+ ;;
4300
+ esac
4301
+ print_copilot_status_row
4302
+
4303
+ if [ -z "$api_key" ]; then
4304
+ :
4305
+ elif models_api GET "/v1/subscriptions/accounts"; then
4306
+ printf '\n'
3644
4307
  if [ "$(printf '%s' "$models_http_body" | jq 'length')" -eq 0 ]; then
3645
- printf ' none enrolled\n'
4308
+ printf ' Subscriptions none enrolled %s(%s login claude | login codex)%s\n' "$C_DIM" "$npx" "$C_RESET"
3646
4309
  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)'
4310
+ printf ' Subscriptions\n'
4311
+ 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
4312
  fi
3649
4313
  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}"
4314
+ printf '\n Subscriptions not offered by this router\n'
4315
+ elif [ "$key_ok" = "true" ]; then
4316
+ printf "\n Subscriptions couldn't load them just now (HTTP %s)\n" "${models_http_status:-network error}"
3653
4317
  fi
4318
+ printf '\n%sRestart Claude Code after on/off; Codex picks changes up on its next run.%s\n' "$C_DIM" "$C_RESET"
3654
4319
  }
3655
4320
 
3656
4321
  if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] || [ "$mode" = "status" ]; then
@@ -3691,12 +4356,25 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
3691
4356
  fi
3692
4357
  if [ "$base_url_explicit" != "true" ]; then
3693
4358
  models_base="$(resolve_installed_endpoint)"
3694
- if [ -z "$models_base" ] && { [ "$mode" = "accounts" ] || [ "$mode" = "status" ]; } && [ "$target" = "claude" ]; then
4359
+ if [ -z "$models_base" ] && { [ "$mode" = "accounts" ] || [ "$mode" = "status" ] || [ "$models_auto_target" = "true" ]; } && [ "$target" = "claude" ]; then
3695
4360
  target="codex"
3696
4361
  models_base="$(resolve_installed_endpoint)"
3697
4362
  fi
4363
+ # status reports a missing install as a per-tool row instead of failing.
4364
+ if [ -z "$models_base" ] && [ "$mode" = "status" ]; then
4365
+ base_url=""
4366
+ api_key=""
4367
+ run_router_status
4368
+ exit 0
4369
+ fi
4370
+ if [ -z "$models_base" ] && [ "$models_auto_target" = "true" ]; then
4371
+ err "Weave Router is not installed for Claude Code or Codex in the $scope scope."
4372
+ 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
4373
+ exit 1
4374
+ fi
3698
4375
  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."
4376
+ err "Weave Router is not installed for $target in the $scope scope."
4377
+ 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
4378
  exit 1
3701
4379
  fi
3702
4380
  base_url="$models_base"
@@ -3753,6 +4431,26 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
3753
4431
  target="$login_target"
3754
4432
  fi
3755
4433
 
4434
+ # A Claude install that lost its key must not hide a working Codex install
4435
+ # from status: check Codex's own endpoint+key pair instead, and leave the
4436
+ # Claude row to report the missing key.
4437
+ if [ "$mode" = "status" ] && [ -z "$api_key" ] && [ "$target" = "claude" ] && [ "$base_url_explicit" != "true" ]; then
4438
+ target="codex"
4439
+ status_codex_base="$(resolve_installed_endpoint)"
4440
+ status_codex_key="$(read_installed_key)"
4441
+ if [ -n "$status_codex_base" ] && [ -n "$status_codex_key" ]; then
4442
+ base_url="$status_codex_base"
4443
+ api_key="$status_codex_key"
4444
+ models_base_source="$(models_config_file_for_target)"
4445
+ models_key_source="$models_base_source"
4446
+ else
4447
+ target="claude"
4448
+ fi
4449
+ fi
4450
+ if [ -z "$api_key" ] && [ "$mode" = "status" ]; then
4451
+ run_router_status
4452
+ exit 0
4453
+ fi
3756
4454
  if [ -z "$api_key" ]; then
3757
4455
  err "No router key found for $target in this scope. Re-run 'npx $npm_package_name --$target', or export WEAVE_ROUTER_KEY."
3758
4456
  exit 1
@@ -3789,6 +4487,7 @@ if [ "$mode" != "install" ] && [ "$mode" != "update" ]; then
3789
4487
  claude) toggle_claude ;;
3790
4488
  codex) toggle_codex ;;
3791
4489
  opencode) toggle_opencode ;;
4490
+ copilot) toggle_copilot ;;
3792
4491
  esac
3793
4492
  exit 0
3794
4493
  fi
@@ -3862,6 +4561,10 @@ elif [ -n "$installed_key" ]; then
3862
4561
  api_key="$installed_key"
3863
4562
  api_key_source="disk"
3864
4563
  [ "$quiet" = "true" ] || info "Reusing the router key already installed (pass --rotate-key to replace it)."
4564
+ elif [ -n "${WEAVE_SETUP_SHARED_KEY:-}" ]; then
4565
+ api_key="$WEAVE_SETUP_SHARED_KEY"
4566
+ api_key_source="setup"
4567
+ [ "$quiet" = "true" ] || info "Using the router key from the Claude Code setup above."
3865
4568
  elif [ "$mode" = "update" ]; then
3866
4569
  err "No router key found for $target. Export WEAVE_ROUTER_KEY, or run the installer once to set one up."
3867
4570
  exit 1
@@ -4197,7 +4900,43 @@ EOF
4197
4900
  # Wrapped in a function so the spinner's exec form sees a single command argv.
4198
4901
  validate_key() {
4199
4902
  printf '%s: %s\n' "$router_key_header" "$api_key" \
4200
- | curl -fsS --max-time 5 --header @- "$base_url/validate"
4903
+ | curl -fsS --max-time 5 --header @- -o /dev/null -w '%{http_code}' \
4904
+ "$base_url/validate" >"$validate_status_file" 2>/dev/null
4905
+ }
4906
+
4907
+ validate_status() {
4908
+ cat "$validate_status_file" 2>/dev/null || true
4909
+ }
4910
+
4911
+ # key_problem explains, in plain words, why the last validate_key call failed.
4912
+ key_problem() {
4913
+ case "$(validate_status)" in
4914
+ 401) printf 'the router did not recognize this key' ;;
4915
+ 403) printf '%s does not serve this key; it likely belongs to a different Weave Router deployment' "$base_url" ;;
4916
+ ""|000) printf 'could not reach %s' "$base_url" ;;
4917
+ *) printf '%s answered HTTP %s' "$base_url" "$(validate_status)" ;;
4918
+ esac
4919
+ }
4920
+
4921
+ # key_fix_hint prints the command that resolves key_problem for the target
4922
+ # flag in $1 (e.g. --codex).
4923
+ key_fix_hint() {
4924
+ case "$(validate_status)" in
4925
+ 401) printf 'copy the full key from the dashboard and run: npx @weave-os/router %s --rotate-key' "$1" ;;
4926
+ 403) printf 're-run with the router URL shown next to your key: npx @weave-os/router %s --base-url <url>' "$1" ;;
4927
+ ""|000) printf 'check your network (or --base-url), then run: npx @weave-os/router update %s' "$1" ;;
4928
+ *) printf 'once the router is healthy, run: npx @weave-os/router update %s' "$1" ;;
4929
+ esac
4930
+ }
4931
+
4932
+ # record_key_verdict sets key_verdict from the last validate_key call. Only an
4933
+ # auth answer (401/403) is evidence that the key is wrong; an unreachable or
4934
+ # failing router leaves the key unverified.
4935
+ record_key_verdict() {
4936
+ case "$(validate_status)" in
4937
+ 401|403) key_verdict="rejected" ;;
4938
+ *) key_verdict="unverified" ;;
4939
+ esac
4201
4940
  }
4202
4941
 
4203
4942
  # rewrite_installed_key rewrites this target's managed config with the key in $1.
@@ -4214,6 +4953,7 @@ rewrite_installed_key() {
4214
4953
  printf '%s\n' "$key" >"$pi_key_file"
4215
4954
  chmod 600 "$pi_key_file"
4216
4955
  ;;
4956
+ copilot) write_copilot_providers "$copilot_providers_file" "$base_url" "$key" "$user_email" "$user_name" ;;
4217
4957
  esac
4218
4958
  }
4219
4959
 
@@ -4233,26 +4973,31 @@ verify_install() {
4233
4973
 
4234
4974
  [ -n "$api_key" ] || return 0
4235
4975
 
4976
+ [ -n "$validate_status_file" ] || validate_status_file="$(mktemp -t weave-validate.XXXXXX)"
4236
4977
  if spin "Validating API key" validate_key; then
4978
+ key_verdict="valid"
4237
4979
  [ "$health_verified" = "true" ] && install_verification_succeeded="true"
4238
4980
  return 0
4239
4981
  fi
4982
+ record_key_verdict
4240
4983
 
4241
4984
  # A key we read back off disk can have been revoked or rotated since it was
4242
4985
  # installed, and reusing it silently would leave a broken install behind
4243
4986
  # exactly where the old behavior (always prompt) would have fixed it. Ask
4244
4987
  # once, then rewrite the config with whatever the user pastes. Anywhere a
4245
4988
  # 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)."
4989
+ # key that didn't come from disk — continue, and announce_done reports the
4990
+ # failure instead of claiming success.
4991
+ if [ "$key_verdict" = "rejected" ] && [ "$api_key_source" = "disk" ] \
4992
+ && [ "$non_interactive" != "true" ] && [ "$quiet" != "true" ] && [ -r /dev/tty ]; then
4993
+ warn "The router key already installed was rejected: $(key_problem)."
4250
4994
  prompt_for_key
4251
4995
  rewrite_installed_key "$api_key"
4252
4996
  if spin "Validating API key" validate_key; then
4997
+ key_verdict="valid"
4253
4998
  [ "$health_verified" = "true" ] && install_verification_succeeded="true"
4254
4999
  else
4255
- warn "Router rejected the API key (check it matches the dashboard at $base_url)."
5000
+ record_key_verdict
4256
5001
  fi
4257
5002
  return 0
4258
5003
  fi
@@ -4263,14 +5008,13 @@ verify_install() {
4263
5008
  # of the nonzero exit — a scheduled run that reports success here would
4264
5009
  # hide a revoked key indefinitely.
4265
5010
  if [ "$quiet" = "true" ]; then
4266
- warn "Router rejected the installed API key. Re-run the installer to set a new one."
5011
+ warn "Router could not verify the installed API key: $(key_problem). Re-run the installer to set a new one."
4267
5012
  else
4268
- err "Router rejected the installed API key. Re-run the installer to set a new one."
5013
+ err "Router could not verify the installed API key: $(key_problem). Re-run the installer to set a new one."
4269
5014
  fi
4270
5015
  exit 1
4271
5016
  fi
4272
5017
 
4273
- warn "Router rejected the API key (check it matches the dashboard at $base_url)."
4274
5018
  }
4275
5019
 
4276
5020
  # announce_done prints the closing line for the client named in $1. `update`
@@ -4278,17 +5022,92 @@ verify_install() {
4278
5022
  # skips the uninstall hint — that run was never the user's first contact with
4279
5023
  # the installer.
4280
5024
  announce_done() {
5025
+ write_setup_handoff
4281
5026
  printf "\n"
4282
5027
  if [ "$mode" = "update" ]; then
4283
5028
  printf "%s✓%s %s%sWeave Router config refreshed for %s.%s\n" \
4284
5029
  "$C_GREEN" "$C_RESET" "$C_BOLD" "$C_BRAND" "$1" "$C_RESET"
4285
5030
  return 0
4286
5031
  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"
5032
+ case "$key_verdict" in
5033
+ rejected|unverified)
5034
+ printf "%s✗%s %sWeave Router is configured for %s, but not working yet:%s %s.\n" \
5035
+ "$C_RED" "$C_RESET" "$C_BOLD" "$1" "$C_RESET" "$(key_problem)"
5036
+ printf " Fix: %s\n" "$(key_fix_hint "--$target")"
5037
+ ;;
5038
+ *)
5039
+ printf "%s✓%s %s%sWeave Router installed for %s.%s\n" \
5040
+ "$C_GREEN" "$C_RESET" "$C_BOLD" "$C_BRAND" "$1" "$C_RESET"
5041
+ ;;
5042
+ esac
4289
5043
  open_return_url_if_verified
4290
5044
  }
4291
5045
 
5046
+ # write_setup_handoff passes this run's key and identity choice to the next
5047
+ # client a multi-client `setup` installs, so each is asked for only once. A key
5048
+ # the router did not accept is not passed on.
5049
+ write_setup_handoff() {
5050
+ [ -n "${WEAVE_SETUP_HANDOFF_FILE:-}" ] && [ -f "$WEAVE_SETUP_HANDOFF_FILE" ] || return 0
5051
+ local shared_key=""
5052
+ [ "$key_verdict" = "valid" ] && shared_key="$api_key"
5053
+ printf '%s\n%s\n' "$shared_key" "$user_email" >"$WEAVE_SETUP_HANDOFF_FILE"
5054
+ }
5055
+
5056
+
5057
+
5058
+
5059
+ # print_next_steps tells a first-time user what stands between this install and
5060
+ # their first routed prompt: the client's own login and, for Codex, the hook
5061
+ # review it shows on first launch.
5062
+ print_next_steps() {
5063
+ printf "\n"
5064
+ case "$target" in
5065
+ claude)
5066
+ if claude_login_missing; then
5067
+ 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" \
5068
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET"
5069
+ else
5070
+ printf "%sNext:%s run %sclaude%s; your next prompt goes through Weave Router.\n" \
5071
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$C_RESET"
5072
+ fi
5073
+ ;;
5074
+ codex)
5075
+ local codex_cmd="codex"
5076
+ [ "$scope" = "project" ] && codex_cmd="CODEX_HOME=$codex_dir codex"
5077
+ if codex_login_missing; then
5078
+ 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" \
5079
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$codex_cmd" "$C_RESET"
5080
+ else
5081
+ printf "%sNext:%s run %s%s%s; your next prompt goes through Weave Router.\n" \
5082
+ "$C_BOLD" "$C_RESET" "$C_BOLD" "$codex_cmd" "$C_RESET"
5083
+ fi
5084
+ 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" \
5085
+ "$C_BOLD" "$C_RESET"
5086
+ ;;
5087
+ esac
5088
+ }
5089
+
5090
+ # finish_install closes a Claude Code or Codex run. Only a working first install
5091
+ # gets onboarding; a failed check or an update must not invite the user in.
5092
+ finish_install() {
5093
+ local label="$1"; shift
5094
+ if [ "$mode" = "install" ] && [ "$quiet" != "true" ] && [ -z "$install_dir" ] && [ "$key_verdict" = "valid" ]; then
5095
+ local pkg="npx $npm_package_name" flags="--$target" feedback="type /rf <what happened> in Claude Code"
5096
+ [ "$scope" = "project" ] && flags="$flags --scope project"
5097
+ [ "$target" = "codex" ] && feedback="type \$rf <what happened> in Codex"
5098
+ print_next_steps
5099
+ printf "\n"
5100
+ printf " %-14s %s\n" "Check routing" "$pkg status $flags"
5101
+ printf " %-14s %s\n" "Turn off" "$pkg off $flags"
5102
+ printf " %-14s %s\n" "Turn back on" "$pkg on $flags"
5103
+ printf " %-14s %s\n" "Give feedback" "$feedback"
5104
+ printf " %-14s %s\n" "Uninstall" "$(uninstall_cmd)"
5105
+ offer_launch "$label" "$@"
5106
+ elif [ "$mode" != "update" ]; then
5107
+ print_uninstall_hint
5108
+ fi
5109
+ }
5110
+
4292
5111
  # ---------- codex install path (dispatch + exit before the Claude-only writes) ----------
4293
5112
 
4294
5113
  # Install the Codex lifecycle helper that reflects the active router and the
@@ -4439,6 +5258,9 @@ weave_self_refresh() {
4439
5258
  return 0
4440
5259
  }
4441
5260
 
5261
+ async_title_enabled=0
5262
+ [ ! -t 2 ] || async_title_enabled=1
5263
+
4442
5264
  state_root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/codex"
4443
5265
  helper_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
4444
5266
  disabled_marker="$helper_dir/.weave-router-disabled"
@@ -4448,7 +5270,7 @@ emit_title() {
4448
5270
  local title="$1"
4449
5271
  if [ -n "${WEAVE_CODEX_STATUS_TITLE_FILE:-}" ]; then
4450
5272
  printf '%s\n' "$title" >"$WEAVE_CODEX_STATUS_TITLE_FILE"
4451
- elif [ -t 2 ] && [ -w /dev/tty ]; then
5273
+ elif { [ -t 2 ] || [ "${async_title_enabled:-0}" = "1" ]; } && [ -w /dev/tty ]; then
4452
5274
  printf '\033]0;%s\007' "$title" >/dev/tty
4453
5275
  fi
4454
5276
  return 0
@@ -4464,13 +5286,14 @@ safe_session_id() {
4464
5286
  }
4465
5287
 
4466
5288
  safe_display_value() {
4467
- printf '%s' "$1" | sed 's/[^A-Za-z0-9._:\/-]//g' | cut -c1-128
5289
+ printf '%s' "$1" | sed 's/[^A-Za-z0-9._:\/-]//g' | cut -c1-64
4468
5290
  }
4469
5291
 
4470
5292
  state_file_for() {
4471
- local id
5293
+ local id scope
4472
5294
  id="$(safe_session_id "$1")" || return 1
4473
- printf '%s/%s.state' "$state_root" "$id"
5295
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5296
+ printf '%s/%s-%s.state' "$state_root" "$scope" "$id"
4474
5297
  }
4475
5298
 
4476
5299
  read_state() {
@@ -4479,6 +5302,8 @@ read_state() {
4479
5302
  while IFS='=' read -r key value; do
4480
5303
  case "$key" in
4481
5304
  routed_model) routed_model="$value" ;;
5305
+ last_pin_model) last_pin_model="$value" ;;
5306
+ command_ids) command_ids="$value" ;;
4482
5307
  esac
4483
5308
  done <"$file"
4484
5309
  }
@@ -4488,7 +5313,7 @@ write_state() {
4488
5313
  mkdir -p "$state_root"
4489
5314
  chmod 700 "$state_root"
4490
5315
  tmp="$(mktemp "$state_root/.state.XXXXXX")"
4491
- printf 'requested_model=%s\nrouted_model=%s\n' "$requested_model" "$routed_model" >"$tmp"
5316
+ 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
5317
  chmod 600 "$tmp"
4493
5318
  mv "$tmp" "$file"
4494
5319
  }
@@ -4499,6 +5324,99 @@ cost_file_for() {
4499
5324
  printf '%s/%s.cost' "$state_root" "$id"
4500
5325
  }
4501
5326
 
5327
+ context_file_for() {
5328
+ local id scope
5329
+ id="$(safe_session_id "$1")" || return 1
5330
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5331
+ printf '%s/%s-%s.context' "$state_root" "$scope" "$id"
5332
+ }
5333
+
5334
+ generation_file_for() {
5335
+ local id scope
5336
+ id="$(safe_session_id "$1")" || return 1
5337
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5338
+ printf '%s/active-%s-%s' "$state_root" "$scope" "$id"
5339
+ }
5340
+
5341
+ state_lock_for() {
5342
+ local id scope
5343
+ id="$(safe_session_id "$1")" || return 1
5344
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
5345
+ printf '%s/state-%s-%s.lock' "$state_root" "$scope" "$id"
5346
+ }
5347
+
5348
+ acquire_state_lock() {
5349
+ local lock="$1" attempt=0 lock_mtime now dead
5350
+ while ! mkdir "$lock" 2>/dev/null; do
5351
+ lock_mtime="$(stat -c %Y "$lock" 2>/dev/null || stat -f %m "$lock" 2>/dev/null)" || lock_mtime=0
5352
+ now="$(date +%s 2>/dev/null)" || now=0
5353
+ if [ "$lock_mtime" -gt 0 ] && [ $((now - lock_mtime)) -gt 30 ]; then
5354
+ dead="${lock}.dead.$$"
5355
+ mv "$lock" "$dead" 2>/dev/null || continue
5356
+ rmdir "$dead" 2>/dev/null || true
5357
+ continue
5358
+ fi
5359
+ attempt=$((attempt + 1))
5360
+ [ "$attempt" -lt 1000 ] || return 1
5361
+ sleep 0.01
5362
+ done
5363
+ return 0
5364
+ }
5365
+
5366
+ release_state_lock() {
5367
+ rmdir "$1" 2>/dev/null || true
5368
+ }
5369
+
5370
+ context_snapshot() {
5371
+ local file="$1" id="$2" now
5372
+ [ -f "$file" ] || return 0
5373
+ [ "$(wc -c <"$file")" -le 4096 ] || return 0
5374
+ now="$(date +%s)"
5375
+ jq -ce --arg session "$id" --argjson now "$now" '
5376
+
5377
+ def tokens: type == "number" and floor == . and . > 0 and . <= 2147483647;
5378
+ def epoch: sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601;
5379
+ .context_snapshot as $s |
5380
+ select(.session_id == $session and $s.version == 1 and $s.estimate_kind == "approximate") |
5381
+ select(($s.estimate_tokens | tokens) and ($s.context_window | tokens) and ($s.output_reserve_tokens | tokens)) |
5382
+ select(($s.served_model | type) == "string" and ($s.served_model | test("^[A-Za-z0-9._:/-]{1,128}$"))) |
5383
+ select(($s.request_id | type) == "string" and ($s.request_id | length) > 0 and ($s.request_id | length) <= 128) |
5384
+ ($s.recorded_at | epoch) as $recorded | ($s.requested_at | epoch) as $requested |
5385
+ select($requested > 0 and $requested <= $recorded and $recorded <= $now and $now - $recorded <= 300) |
5386
+ $s
5387
+ ' "$file" 2>/dev/null || true
5388
+ }
5389
+
5390
+ # The Stop payload preserves this exact router wire record in raw Markdown.
5391
+ # A general Markdown parser would add a runtime dependency to standalone installs.
5392
+ command_outcome() {
5393
+ printf '%s' "$1" | jq -Rsec '
5394
+ def safe_identifier: type == "string" and test("^[A-Za-z0-9._:/-]{1,128}$");
5395
+ capture("(?:^|\n)\\[weave-router-command-v1\\]: <weave-router:(?<encoded>[A-Za-z0-9_-]{1,8192})>(?:\n|$)").encoded |
5396
+ gsub("-"; "+") | gsub("_"; "/") | @base64d | fromjson |
5397
+ 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}$"))) |
5398
+ select(.command == "force_model" or .command == "router_session" or .command == "router_models" or .command == "router_feedback" or .command == "loop_stop") |
5399
+ select(.disposition == "accepted" or .disposition == "rejected") |
5400
+ select(.pin.transition == "unchanged" or
5401
+ (.command == "force_model" and .disposition == "accepted" and
5402
+ (.pin.transition == "cleared" or (.pin.transition == "applied" and
5403
+ (.pin.model | safe_identifier) and (.pin.provider | safe_identifier) and
5404
+ (.pin.effort == null or (.pin.effort | safe_identifier))))))
5405
+ ' 2>/dev/null || true
5406
+ }
5407
+
5408
+ pin_clause() {
5409
+ [ -z "$last_pin_model" ] || printf ' · last pin: %s' "$(safe_display_value "$last_pin_model")"
5410
+ }
5411
+
5412
+ context_clause() {
5413
+ local snapshot="$1"
5414
+ [ -n "$snapshot" ] || return 0
5415
+ awk -v estimate="$(jq -r '.estimate_tokens' <<<"$snapshot")" -v window="$(jq -r '.context_window' <<<"$snapshot")" 'BEGIN {
5416
+ printf " · last Router ctx est. ~%s/%s", (estimate < 1000 ? estimate : sprintf("%.0fk", estimate/1000)), (window < 1000 ? window : sprintf("%.0fk", window/1000))
5417
+ }'
5418
+ }
5419
+
4502
5420
  # Reads the router base URL and key out of the Codex config this install owns.
4503
5421
  # Resolved from the helper's own location first so a project-scope install never
4504
5422
  # reads (or leaks) the user-scope key: the project helper lives in the same
@@ -4576,11 +5494,11 @@ read_codex_endpoint() {
4576
5494
  # Fire-and-forget on purpose — a slow or unreachable router must never stall a
4577
5495
  # Codex turn, and every failure simply leaves the previous cache in place.
4578
5496
  refresh_session_cost() {
4579
- local id="$1" file="$2"
4580
- [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && return 0
5497
+ local id="$1" file="$2" context_file="$3" generation="$4"
5498
+ [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" = "0" ] && return 0
4581
5499
  command -v curl >/dev/null 2>&1 || return 0
4582
5500
 
4583
- local endpoint base_url key
5501
+ local endpoint base_url key active_file state_lock
4584
5502
  endpoint="$(read_codex_endpoint)" || return 0
4585
5503
  base_url="$(printf '%s' "$endpoint" | sed -n 1p)"
4586
5504
  key="$(printf '%s' "$endpoint" | sed -n 2p)"
@@ -4588,6 +5506,8 @@ refresh_session_cost() {
4588
5506
 
4589
5507
  mkdir -p "$state_root" 2>/dev/null || return 0
4590
5508
  chmod 700 "$state_root" 2>/dev/null || true
5509
+ active_file="$(generation_file_for "$id")" || return 0
5510
+ state_lock="$(state_lock_for "$id")" || return 0
4591
5511
 
4592
5512
  (
4593
5513
  exec </dev/null
@@ -4612,29 +5532,112 @@ refresh_session_cost() {
4612
5532
  file://*) ;;
4613
5533
  *) url="${url%/v1}/v1/sessions/$id/cost" ;;
4614
5534
  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
5535
+ header_file="$(mktemp "$state_root/.headers.XXXXXX")" || exit 0
5536
+ chmod 600 "$header_file"
5537
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
5538
+ if ! body="$(curl -fsS --max-time 5 --max-filesize 8192 -K "$header_file" "$url" 2>/dev/null)"; then
5539
+ rm -f "$header_file"
5540
+ exit 0
4627
5541
  fi
4628
- rm -f "$tmp" 2>/dev/null
5542
+ rm -f "$header_file"
5543
+ [ "$(printf '%s' "$body" | wc -c)" -le 8192 ] || exit 0
5544
+ response_session="$(jq -r '.session_id // empty' <<<"$body" 2>/dev/null)" || exit 0
5545
+ [ -z "$response_session" ] || [ "$response_session" = "$id" ] || exit 0
5546
+ context_tmp=""
5547
+ fresh_snapshot=""
5548
+ fresh_title=""
5549
+ savings_tmp=""
5550
+ savings=""
5551
+ fresh_model=""
5552
+ fresh_requested=""
5553
+ if [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" != "0" ]; then
5554
+ context_tmp="$(mktemp "$state_root/.context.XXXXXX")" || exit 0
5555
+ chmod 600 "$context_tmp"
5556
+ printf '%s' "$body" >"$context_tmp" || { rm -f "$context_tmp"; exit 0; }
5557
+ fresh_snapshot="$(context_snapshot "$context_tmp" "$id")"
5558
+ if [ -n "$fresh_snapshot" ]; then
5559
+ fresh_model="$(safe_display_value "$(jq -r '.served_model' <<<"$fresh_snapshot")")"
5560
+ fresh_requested="$(jq -r '.requested_model // empty' <<<"$fresh_snapshot")"
5561
+ if { [ -z "$requested_model" ] || [ "$fresh_requested" = "$requested_model" ]; } \
5562
+ && { [ -z "$force_model" ] || [ "$fresh_model" = "$(safe_display_value "$force_model")" ]; } \
5563
+ && { [ -z "$marker_model" ] || [ "$fresh_model" = "$routed_model" ]; }; then
5564
+ shown_requested="$requested_model"
5565
+ [ -n "$shown_requested" ] || shown_requested="$(safe_display_value "$fresh_requested")"
5566
+ if [ -n "$shown_requested" ] && [ "$fresh_model" != "$shown_requested" ]; then
5567
+ fresh_title="Weave Router · $shown_requested → $fresh_model"
5568
+ else
5569
+ fresh_title="Weave Router · $fresh_model"
5570
+ fi
5571
+ fi
5572
+ fi
5573
+ fi
5574
+ if [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" != "0" ]; then
5575
+ # savings_usd is the router's own (requested - actual). A body without it
5576
+ # (404, error envelope, older router) leaves the cache untouched.
5577
+ savings="$(printf '%s' "$body" | jq -r '.savings_usd // empty' 2>/dev/null)" || savings=""
5578
+ case "$savings" in ''|*[!0-9.eE+-]*) savings="" ;; esac
5579
+ if [ -n "$savings" ]; then
5580
+ savings_tmp="$(mktemp "$state_root/.cost.XXXXXX")" || savings=""
5581
+ if [ -n "$savings" ]; then
5582
+ if ! chmod 600 "$savings_tmp" 2>/dev/null || ! printf '%s' "$savings" >"$savings_tmp" 2>/dev/null; then
5583
+ rm -f "$savings_tmp"
5584
+ savings_tmp=""
5585
+ fi
5586
+ fi
5587
+ fi
5588
+ fi
5589
+ if ! acquire_state_lock "$state_lock"; then
5590
+ rm -f "$context_tmp" "$savings_tmp"
5591
+ exit 0
5592
+ fi
5593
+ trap 'release_state_lock "$state_lock"; rmdir "$lock" 2>/dev/null || true' EXIT
5594
+ if [ "$(cat "$active_file" 2>/dev/null)" = "$generation" ]; then
5595
+ if [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" != "0" ]; then
5596
+ if [ -n "$fresh_snapshot" ]; then
5597
+ existing_snapshot="$(context_snapshot "$context_file" "$id")"
5598
+ if [ -n "$existing_snapshot" ] && ! jq -en --argjson incoming "$fresh_snapshot" --argjson existing "$existing_snapshot" '
5599
+ def instant:
5600
+ capture("^(?<whole>[0-9-]+T[0-9:]+)(?:\\.(?<fraction>[0-9]{1,9}))?Z$") |
5601
+ [.whole, ((.fraction // "") + "000000000" | .[:9])];
5602
+ [($incoming.requested_at | instant), ($incoming.recorded_at | instant)] as $incoming_time |
5603
+ [($existing.requested_at | instant), ($existing.recorded_at | instant)] as $existing_time |
5604
+ $incoming_time > $existing_time or
5605
+ ($incoming_time == $existing_time and $incoming.request_id == $existing.request_id)
5606
+ ' >/dev/null 2>&1; then
5607
+ rm -f "$context_tmp" "$savings_tmp"
5608
+ exit 0
5609
+ elif mv "$context_tmp" "$context_file" 2>/dev/null; then
5610
+ context_tmp=""
5611
+ else
5612
+ fresh_title=""
5613
+ fi
5614
+ else
5615
+ rm -f "$context_file"
5616
+ fi
5617
+ fi
5618
+ if [ -n "$savings_tmp" ]; then
5619
+ if mv "$savings_tmp" "$file" 2>/dev/null; then
5620
+ savings_tmp=""
5621
+ else
5622
+ rm -f "$savings_tmp"
5623
+ savings_tmp=""
5624
+ fi
5625
+ fi
5626
+ if [ -n "$fresh_title" ] && [ ! -f "$disabled_marker" ]; then
5627
+ emit_title "$fresh_title$(savings_clause "$file")$(context_clause "$fresh_snapshot")$(pin_clause)"
5628
+ fi
5629
+ fi
5630
+ release_state_lock "$state_lock"
5631
+ rm -f "$context_tmp" "$savings_tmp"
4629
5632
  ) >/dev/null 2>&1 &
4630
5633
  disown 2>/dev/null || true
4631
5634
  }
4632
5635
 
4633
5636
  # Renders the cached savings as a display clause, or nothing. Values below a
4634
5637
  # 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.
5638
+ # from "the router ran and did not beat your selection". A negative total means
5639
+ # the router upgraded hard turns past the requested model; it reads as "cost
5640
+ # $X more" rather than a negative saving.
4638
5641
  savings_clause() {
4639
5642
  local file="$1" raw
4640
5643
  [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && return 0
@@ -4645,6 +5648,8 @@ savings_clause() {
4645
5648
  esac
4646
5649
  awk -v v="$raw" 'BEGIN{
4647
5650
  v = v + 0
5651
+ if (v <= -0.01) { printf " · cost $%.2f more", -v; exit }
5652
+ if (v <= -0.005) { printf " · cost <$0.01 more"; exit }
4648
5653
  if (v < 0.005) { exit }
4649
5654
  if (v < 0.01) { printf " · saved <$0.01"; exit }
4650
5655
  printf " · saved $%.2f", v
@@ -4694,6 +5699,38 @@ if [ "${WEAVE_CAPTURE_LLM_CLASSIFIER:-}" = "1" ] && [ -n "${WEAVE_CAPTURE_HOOK_T
4694
5699
  esac
4695
5700
  fi
4696
5701
  fi
5702
+ session_id="$(safe_session_id "$(jq -r '.session_id // empty' <<<"$payload")")" || exit 0
5703
+ active_file="$(generation_file_for "$session_id")"
5704
+ state_lock="$(state_lock_for "$session_id")"
5705
+ mkdir -p "$state_root"
5706
+ chmod 700 "$state_root"
5707
+ acquire_state_lock "$state_lock" || exit 0
5708
+ trap 'release_state_lock "$state_lock"' EXIT
5709
+ turn_file="${active_file}.turn"
5710
+ turn_id="$(safe_session_id "$(jq -r '.turn_id // empty' <<<"$payload")")" || turn_id=""
5711
+ if [ "$hook_event_name" = "SessionStart" ]; then
5712
+ rm -f "$turn_file"
5713
+ elif [ "$hook_event_name" = "UserPromptSubmit" ]; then
5714
+ if [ -n "$turn_id" ]; then
5715
+ printf '%s' "$turn_id" >"$turn_file"
5716
+ chmod 600 "$turn_file"
5717
+ else
5718
+ rm -f "$turn_file"
5719
+ fi
5720
+ elif [ "$hook_event_name" = "Stop" ] && [ -n "$turn_id" ] && [ -f "$turn_file" ] && [ "$(cat "$turn_file")" != "$turn_id" ]; then
5721
+ exit 0
5722
+ fi
5723
+ generation="$(mktemp "$state_root/.generation.XXXXXX")"
5724
+ printf '%s' "$generation" >"$generation"
5725
+ chmod 600 "$generation"
5726
+ mv "$generation" "$active_file"
5727
+ if [ "$hook_event_name" = "SessionStart" ] || [ "$hook_event_name" = "PreCompact" ]; then
5728
+ reset_context="$(context_file_for "$session_id")" || reset_context=""
5729
+ [ -z "$reset_context" ] || rm -f "$reset_context"
5730
+ fi
5731
+ if [ "$hook_event_name" = "UserPromptSubmit" ]; then
5732
+ exit 0
5733
+ fi
4697
5734
  if [ "$hook_event_name" = "SessionStart" ]; then
4698
5735
  if [ -f "$disabled_marker" ]; then
4699
5736
  emit_title "Codex · direct"
@@ -4703,7 +5740,11 @@ if [ "$hook_event_name" = "SessionStart" ]; then
4703
5740
  exit 0
4704
5741
  fi
4705
5742
 
4706
- if [ "$hook_event_name" = "PreToolUse" ] || [ "$hook_event_name" = "PreCompact" ]; then
5743
+ if [ "$hook_event_name" = "PreCompact" ]; then
5744
+ [ -f "$disabled_marker" ] || emit_title "Weave Router · active"
5745
+ exit 0
5746
+ fi
5747
+ if [ "$hook_event_name" = "PreToolUse" ]; then
4707
5748
  exit 0
4708
5749
  fi
4709
5750
 
@@ -4713,6 +5754,8 @@ fi
4713
5754
 
4714
5755
  requested_model="$(safe_display_value "$(jq -r '.model // ""' <<<"$payload")")"
4715
5756
  routed_model=""
5757
+ last_pin_model=""
5758
+ command_ids=""
4716
5759
  session_id="$(jq -r '.session_id // ""' <<<"$payload")"
4717
5760
  last_assistant_message="$(jq -r '.last_assistant_message // ""' <<<"$payload")"
4718
5761
 
@@ -4721,31 +5764,52 @@ if file="$(state_file_for "$session_id" 2>/dev/null)"; then
4721
5764
  read_state "$file"
4722
5765
  fi
4723
5766
 
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
5767
  first_line="${last_assistant_message%%$'\n'*}"
4727
5768
  marker_model=""
4728
5769
  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
- ;;
5770
+ structured_command=0
5771
+ case "$last_assistant_message" in
5772
+ *'[weave-router-command-v'*) structured_command=1 ;;
4744
5773
  esac
5774
+ if [ "$structured_command" = 1 ]; then
5775
+ outcome="$(command_outcome "$last_assistant_message")"
5776
+ if [ -n "$outcome" ]; then
5777
+ outcome_id="$(jq -r '.id' <<<"$outcome")"
5778
+ case " $command_ids " in
5779
+ *" $outcome_id "*) ;;
5780
+ *)
5781
+ command_ids="${command_ids:+$command_ids }$outcome_id"
5782
+ case "$(jq -r '.pin.transition' <<<"$outcome")" in
5783
+ applied)
5784
+ last_pin_model="$(jq -r '.pin.model + (if (.pin.effort // "") == "" then "" else ":" + .pin.effort end)' <<<"$outcome")"
5785
+ force_model="$(jq -r '.pin.model' <<<"$outcome")"
5786
+ ;;
5787
+ cleared) last_pin_model="" ;;
5788
+ esac
5789
+ ;;
5790
+ esac
5791
+ fi
5792
+ else
5793
+ # Legacy acknowledgments remain readable; only explicit force and clear mutate history.
5794
+ case "$first_line" in
5795
+ "Weave Router: force-model applied: "*" ("*|"✦ **Weave Router** → force-model applied: "*" ("*|"Weave Router: force-parent applied: "*" ("*|"✦ **Weave Router** → force-parent applied: "*" ("*)
5796
+ force_model="${first_line#*applied: }"
5797
+ force_model="${force_model%% (*}"
5798
+ last_pin_model="$(safe_display_value "$force_model")"
5799
+ ;;
5800
+ "Weave Router: force-model cleared"*|"✦ **Weave Router** → force-model cleared"*) last_pin_model="" ;;
5801
+ *)
5802
+ case "$first_line" in
5803
+ "${router_badge_sentinel}✦ **Weave Router** → "*) marker_model="${first_line#"${router_badge_sentinel}✦ **Weave Router** → "}" ;;
5804
+ "✦ **Weave Router** → "*) marker_model="${first_line#"✦ **Weave Router** → "}" ;;
5805
+ esac
5806
+ marker_model="${marker_model%% ·*}"
5807
+ case "$marker_model" in ''|*[!A-Za-z0-9._:/-]*) marker_model="" ;; esac
5808
+ ;;
5809
+ esac
5810
+ fi
4745
5811
  if [ -n "$marker_model" ]; then
4746
5812
  routed_model="$(safe_display_value "$marker_model")"
4747
- elif [ -n "$force_model" ]; then
4748
- routed_model="$(safe_display_value "$force_model")"
4749
5813
  else
4750
5814
  routed_model="$(safe_display_value "$routed_model")"
4751
5815
  fi
@@ -4759,22 +5823,41 @@ fi
4759
5823
  # turn would not be included even in a blocking read — reading first and
4760
5824
  # refreshing after costs a turn of freshness and buys never blocking Codex.
4761
5825
  savings=""
5826
+ context=""
5827
+ context_file="$(context_file_for "$session_id" 2>/dev/null)" || context_file=""
5828
+ if [ -n "$context_file" ] && [ "${WEAVE_CODEX_STATUS_CONTEXT:-1}" != "0" ]; then
5829
+ snapshot="$(context_snapshot "$context_file" "$session_id")"
5830
+ if [ -n "$snapshot" ]; then
5831
+ snapshot_model="$(safe_display_value "$(jq -r '.served_model' <<<"$snapshot")")"
5832
+ snapshot_requested="$(jq -r '.requested_model // empty' <<<"$snapshot")"
5833
+ 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
5834
+ routed_model="$snapshot_model"
5835
+ [ -n "$requested_model" ] || requested_model="$(safe_display_value "$snapshot_requested")"
5836
+ context="$(context_clause "$snapshot")"
5837
+ fi
5838
+ fi
5839
+ fi
4762
5840
  cost_file=""
4763
5841
  if cost_file="$(cost_file_for "$session_id" 2>/dev/null)"; then
4764
5842
  savings="$(savings_clause "$cost_file")"
4765
- refresh_session_cost "$(safe_session_id "$session_id")" "$cost_file"
5843
+
4766
5844
  fi
4767
5845
 
4768
5846
  if [ -n "$routed_model" ] && [ -n "$requested_model" ] && [ "$routed_model" != "$requested_model" ]; then
4769
- title="Weave Router · $routed_model ← $requested_model$savings"
5847
+ title="Weave Router · $requested_model → $routed_model$savings"
4770
5848
  elif [ -n "$routed_model" ]; then
4771
5849
  title="Weave Router · $routed_model$savings"
4772
5850
  elif [ -n "$requested_model" ]; then
4773
- title="Weave Router · active ← $requested_model$savings"
5851
+ title="Weave Router · $requested_model → active$savings"
4774
5852
  else
4775
5853
  title="Weave Router · active$savings"
4776
5854
  fi
4777
- emit_title "$title"
5855
+ emit_title "$title$context$(pin_clause)"
5856
+ release_state_lock "$state_lock"
5857
+ trap - EXIT
5858
+ if [ -n "$cost_file" ] && [ -n "$context_file" ]; then
5859
+ refresh_session_cost "$(safe_session_id "$session_id")" "$cost_file" "$context_file" "$generation"
5860
+ fi
4778
5861
  CODEX_STATUS_EOF
4779
5862
  fi
4780
5863
  chmod 700 "$codex_status_file"
@@ -4992,7 +6075,7 @@ trap "rm -f '$out_file'" EXIT
4992
6075
  # word-split at runtime -- the braces are a template token, not an expansion.
4993
6076
  # shellcheck disable=SC1083
4994
6077
  run_bounded "$WEAVE_TOGGLE_TIMEOUT" "$out_file" \
4995
- npx --package @weave-os/router -y -- weave-router "$toggle" --codex{{SCOPE}}
6078
+ env NPM_CONFIG_UPDATE_NOTIFIER=false npx --package @weave-os/router -y -- weave-router "$toggle" --codex{{SCOPE}}
4996
6079
  status=$?
4997
6080
 
4998
6081
  output="$(cat "$out_file" 2>/dev/null || true)"
@@ -5108,6 +6191,39 @@ if [ "$target" = "codex" ]; then
5108
6191
  # point CODEX_HOME at the directory we wrote so Codex finds our config.
5109
6192
  info "Run Codex with CODEX_HOME=$codex_dir codex so it picks up this config."
5110
6193
  fi
6194
+ if [ "$scope" = "project" ]; then
6195
+ finish_install "Codex" env CODEX_HOME="$codex_dir" codex
6196
+ else
6197
+ finish_install "Codex" codex
6198
+ fi
6199
+ exit 0
6200
+ fi
6201
+
6202
+ # ---------- copilot install path (dispatch + exit before the Claude-only writes) ----------
6203
+
6204
+ if [ "$target" = "copilot" ]; then
6205
+ # A re-install or update keeps the wire format already installed unless
6206
+ # --wire picks a new one.
6207
+ if [ "$copilot_wire_explicit" != "true" ] && [ -f "$copilot_providers_file" ] \
6208
+ && [ "$(jq -r '[(.providers // [])[] | select(.name == "weave") | .type][0] // empty' "$copilot_providers_file" 2>/dev/null || true)" = "openai" ]; then
6209
+ copilot_wire="openai"
6210
+ fi
6211
+ write_copilot_providers "$copilot_providers_file" "$base_url" "$api_key" "$user_email" "$user_name"
6212
+ ok "Copilot CLI provider weave/auto written to $copilot_providers_file ($copilot_wire wire)"
6213
+ set_copilot_default_model
6214
+ ok "Copilot CLI default model set to weave/auto in $copilot_settings_file"
6215
+ install_copilot_skills
6216
+
6217
+ verify_install
6218
+
6219
+ announce_done "GitHub Copilot CLI"
6220
+ if [ "$mode" = "install" ] && [ "$quiet" != "true" ]; then
6221
+ info "GitHub models stay available: switch any time with /model in Copilot CLI."
6222
+ info "Router directives are Copilot skills: /force-model <id>, /unforce-model, /rf <feedback>, /router-off, /router-on."
6223
+ fi
6224
+ if [ -n "$install_dir" ]; then
6225
+ info "Run Copilot CLI with COPILOT_HOME=$copilot_dir copilot so it picks up this config."
6226
+ fi
5111
6227
  [ "$mode" = "update" ] || print_uninstall_hint
5112
6228
  exit 0
5113
6229
  fi
@@ -5243,7 +6359,7 @@ cat > "$statusline_file" << 'STATUSLINE_EOF'
5243
6359
  # { "statusLine": { "type": "command", "command": "/abs/path/to/cc-statusline.sh" } }
5244
6360
  #
5245
6361
  # Renders:
5246
- # WEAVE ROUTER · response model: claude-sonnet-4-5 · selected: claude-opus-4-7 · est. cost difference $1.23
6362
+ # WEAVE ROUTER · you picked opus-4-7 → served sonnet-4-5 · saved ~$1.23 this session
5247
6363
  #
5248
6364
  # Pricing source of truth: internal/router/catalog. Input/output prices and
5249
6365
  # cache-read multipliers are generated by cmd/genprices. Cache creation remains
@@ -5252,6 +6368,48 @@ cat > "$statusline_file" << 'STATUSLINE_EOF'
5252
6368
  set -euo pipefail
5253
6369
  export PATH="$PATH:$HOME/.weave/bin"
5254
6370
 
6371
+ # ---------- /router-status prompt hook ----------
6372
+ #
6373
+ # Registered as a UserPromptSubmit hook with --prompt-hook. Every other prompt
6374
+ # passes through untouched; /router-status is answered from local state and
6375
+ # stopped before it reaches a model, so checking the router never spends a
6376
+ # turn. The settings env (router URL and key header) is inherited by hooks, and
6377
+ # the session's last statusline render is cached by the statusline below.
6378
+ weave_router_status_hook() {
6379
+ command -v jq >/dev/null 2>&1 || return 0
6380
+ local payload prompt session line="" root report scope_suffix=""
6381
+ [ "$#" -eq 0 ] || scope_suffix="$(printf ' %q' "$@")"
6382
+ payload="$(cat)"
6383
+ prompt="$(jq -r '.prompt // empty' <<<"$payload" 2>/dev/null)" || return 0
6384
+ [[ "$prompt" =~ ^[[:space:]]*/router-status[[:space:]]*$ ]] || return 0
6385
+ if [[ "${ANTHROPIC_BASE_URL:-}" == https://api.anthropic.com* ]]; then
6386
+ report="Weave Router is off: Claude Code talks to Anthropic directly. Turn it back on with /router-on."
6387
+ elif [[ -n "${ANTHROPIC_BASE_URL:-}" && "${ANTHROPIC_CUSTOM_HEADERS:-}" == *"X-Weave-Router-Key:"* ]]; then
6388
+ report="Weave Router is on: Claude Code sends requests to ${ANTHROPIC_BASE_URL}."
6389
+ elif [[ -n "${ANTHROPIC_BASE_URL:-}" ]]; then
6390
+ 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}"
6391
+ else
6392
+ report="Weave Router is off: Claude Code talks to Anthropic directly. Turn it back on with /router-on."
6393
+ fi
6394
+ session="$(jq -r '.session_id // empty' <<<"$payload" 2>/dev/null)" || session=""
6395
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-status"
6396
+ if [[ "$session" =~ ^[A-Za-z0-9._-]{1,128}$ && -f "$root/$session.line" ]]; then
6397
+ line="$(head -c 512 "$root/$session.line" | head -n 1)"
6398
+ fi
6399
+ if [[ -n "$line" ]]; then
6400
+ report="$report"$'\n'"This session: $line"
6401
+ else
6402
+ report="$report"$'\n'"No routed turn yet in this session."
6403
+ fi
6404
+ report="$report"$'\n'"Full check (key, login, endpoint): npx @weave-os/router status --claude${scope_suffix}"
6405
+ jq -n --arg reason "$report" '{continue: false, stopReason: $reason, suppressOutput: true}'
6406
+ }
6407
+ if [ "${1:-}" = "--prompt-hook" ]; then
6408
+ shift
6409
+ weave_router_status_hook "$@" || true
6410
+ exit 0
6411
+ fi
6412
+
5255
6413
  # ---------- background self-refresh ----------
5256
6414
  #
5257
6415
  # Once every WEAVE_STATUSLINE_UPDATE_INTERVAL_DAYS (default 7), check
@@ -5652,7 +6810,14 @@ weave_hidden_gate() {
5652
6810
  file://*) ;;
5653
6811
  *) url="$url/v1/display-settings" ;;
5654
6812
  esac
5655
- body="$(curl -fsS --max-time 5 -H "X-Weave-Router-Key: $key" "$url" 2>/dev/null)" || exit 0
6813
+ header_file="$(mktemp "$cache_dir/.headers.XXXXXX")" || exit 0
6814
+ chmod 600 "$header_file"
6815
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
6816
+ if ! body="$(curl -fsS --max-time 5 -K "$header_file" "$url" 2>/dev/null)"; then
6817
+ rm -f "$header_file"
6818
+ exit 0
6819
+ fi
6820
+ rm -f "$header_file"
5656
6821
  hidden="$(printf '%s' "$body" | jq -r '.hide_terminal_surfaces // false' 2>/dev/null)"
5657
6822
  tmp="$cache.tmp.$$"
5658
6823
  if [ "$hidden" = "true" ]; then
@@ -5671,6 +6836,7 @@ if weave_hidden_gate </dev/null; then
5671
6836
  fi
5672
6837
 
5673
6838
  input="$(cat)"
6839
+ jq -e 'type == "object"' >/dev/null 2>&1 <<<"$input" || exit 0
5674
6840
  transcript_path="$(printf '%s' "$input" | jq -r '.transcript_path // empty')"
5675
6841
  # Prefer model.id over display_name: pricing keys + the response model id in
5676
6842
  # the transcript are canonical ids (e.g. claude-opus-4-7), while display_name
@@ -5678,6 +6844,19 @@ transcript_path="$(printf '%s' "$input" | jq -r '.transcript_path // empty')"
5678
6844
  # preventing a price comparison. id passes through normalize_model cleanly.
5679
6845
  selected_display="$(printf '%s' "$input" | jq -r '.model.id // .model.display_name // "?"')"
5680
6846
 
6847
+ # Claude owns this percentage and its window; session totals never establish it.
6848
+ context_clause="$(jq -r '
6849
+ .context_window as $c |
6850
+ if ($c.context_window_size | type) == "number" and $c.context_window_size > 0 and $c.context_window_size <= 2147483647
6851
+ and ($c.context_window_size | floor) == $c.context_window_size
6852
+ and ($c.used_percentage | type) == "number" and $c.used_percentage >= 0 and $c.used_percentage <= 100
6853
+ then " · Context " + ($c.used_percentage | floor | tostring) + "%" +
6854
+ (if $c.used_percentage >= 90 then " !" else "" end)
6855
+ else "" end
6856
+ ' <<<"$input" 2>/dev/null)" || context_clause=""
6857
+
6858
+ [ "${WEAVE_STATUSLINE_CONTEXT:-1}" != "0" ] || context_clause=""
6859
+
5681
6860
  # Normalize a model id to a pricing-table key. CC + the decisions log carry
5682
6861
  # two flavors of annotation we don't want in the lookup:
5683
6862
  # * date suffix: claude-opus-4-7-20260101 → claude-opus-4-7
@@ -5696,6 +6875,7 @@ prices='{
5696
6875
  "claude-fable-5": 0.01,
5697
6876
  "claude-fable-5-1": 0.01,
5698
6877
  "claude-haiku-4-5": 0.001,
6878
+ "claude-haiku-5-5": 0.0001,
5699
6879
  "claude-opus-4-0": 0.015,
5700
6880
  "claude-opus-4-1": 0.015,
5701
6881
  "claude-opus-4-5": 0.005,
@@ -5706,7 +6886,7 @@ prices='{
5706
6886
  "claude-opus-5-5": 0.004,
5707
6887
  "claude-sonnet-4-5": 0.003,
5708
6888
  "claude-sonnet-4-6": 0.003,
5709
- "claude-sonnet-5": 0.003,
6889
+ "claude-sonnet-5": 0.002,
5710
6890
  "claude-sonnet-5-5": 0.002,
5711
6891
  "deepseek/deepseek-v4-flash": 0.00014,
5712
6892
  "deepseek/deepseek-v4-pro": 0.00174,
@@ -5726,6 +6906,7 @@ prices='{
5726
6906
  "gemini-3.6-flash": 0.0015,
5727
6907
  "gemini-3.7-flash": 0.0015,
5728
6908
  "gemini-3.8-flash": 0.0015,
6909
+ "gemini-4-argon": 0.002,
5729
6910
  "google/gemma-4-26b-a4b-it": 0.00015,
5730
6911
  "gpt-4.1": 0.002,
5731
6912
  "gpt-4.1-mini": 0.0004,
@@ -5753,17 +6934,20 @@ prices='{
5753
6934
  "gpt-6-luna": 0.0001,
5754
6935
  "gpt-6-sol": 0.002,
5755
6936
  "gpt-6.1-sol": 0.002,
6937
+ "gpt-6.1-terra": 0.001,
5756
6938
  "grok-4.5": 0.002,
5757
6939
  "grok-4.6": 0.002,
5758
6940
  "grok-4.7": 0.002,
5759
6941
  "inclusionai/ling-3.0-flash": 0.00006,
5760
6942
  "minimax/minimax-m2.7": 0.0003,
5761
6943
  "minimax/minimax-m3": 0.0003,
6944
+ "minimax/minimax-m3.1-flash": 0.00015,
5762
6945
  "mistralai/mistral-small-2603": 0.0002,
5763
6946
  "moonshotai/kimi-k2.5": 0.0006,
5764
6947
  "moonshotai/kimi-k2.6": 0.00095,
5765
6948
  "moonshotai/kimi-k2.7": 0.00095,
5766
6949
  "moonshotai/kimi-k3": 0.003,
6950
+ "moonshotai/kimi-k3.1": 0.002,
5767
6951
  "muse-spark-1.3": 0.00125,
5768
6952
  "qwen/qwen3-235b-a22b-2507": 0.0002266,
5769
6953
  "qwen/qwen3-30b-a3b-instruct-2507": 0.00015,
@@ -5775,7 +6959,7 @@ prices='{
5775
6959
  "qwen/qwen3.7-plus": 0.0004,
5776
6960
  "qwen/qwen3.8-max": 0.002,
5777
6961
  "xiaomi/mimo-v2.5-pro": 0.001,
5778
- "xiaomi/mimo-v2.6-flash": 0.00014,
6962
+ "xiaomi/mimo-v2.6-flash": 0.00013,
5779
6963
  "xiaomi/mimo-v2.6-pro": 0.000435,
5780
6964
  "z-ai/glm-5": 0.001,
5781
6965
  "z-ai/glm-5.1": 0.0014,
@@ -5787,6 +6971,7 @@ prices='{
5787
6971
  "claude-fable-5": 0.05,
5788
6972
  "claude-fable-5-1": 0.05,
5789
6973
  "claude-haiku-4-5": 0.005,
6974
+ "claude-haiku-5-5": 0.0005,
5790
6975
  "claude-opus-4-0": 0.075,
5791
6976
  "claude-opus-4-1": 0.075,
5792
6977
  "claude-opus-4-5": 0.025,
@@ -5797,7 +6982,7 @@ prices='{
5797
6982
  "claude-opus-5-5": 0.02,
5798
6983
  "claude-sonnet-4-5": 0.015,
5799
6984
  "claude-sonnet-4-6": 0.015,
5800
- "claude-sonnet-5": 0.015,
6985
+ "claude-sonnet-5": 0.01,
5801
6986
  "claude-sonnet-5-5": 0.01,
5802
6987
  "deepseek/deepseek-v4-flash": 0.00028,
5803
6988
  "deepseek/deepseek-v4-pro": 0.00348,
@@ -5817,6 +7002,7 @@ prices='{
5817
7002
  "gemini-3.6-flash": 0.0075,
5818
7003
  "gemini-3.7-flash": 0.0075,
5819
7004
  "gemini-3.8-flash": 0.0075,
7005
+ "gemini-4-argon": 0.01,
5820
7006
  "google/gemma-4-26b-a4b-it": 0.0006,
5821
7007
  "gpt-4.1": 0.008,
5822
7008
  "gpt-4.1-mini": 0.0016,
@@ -5844,17 +7030,20 @@ prices='{
5844
7030
  "gpt-6-luna": 0.0005,
5845
7031
  "gpt-6-sol": 0.01,
5846
7032
  "gpt-6.1-sol": 0.01,
7033
+ "gpt-6.1-terra": 0.005,
5847
7034
  "grok-4.5": 0.006,
5848
7035
  "grok-4.6": 0.006,
5849
7036
  "grok-4.7": 0.006,
5850
7037
  "inclusionai/ling-3.0-flash": 0.00018,
5851
7038
  "minimax/minimax-m2.7": 0.0012,
5852
7039
  "minimax/minimax-m3": 0.0012,
7040
+ "minimax/minimax-m3.1-flash": 0.0006,
5853
7041
  "mistralai/mistral-small-2603": 0.0006,
5854
7042
  "moonshotai/kimi-k2.5": 0.003,
5855
7043
  "moonshotai/kimi-k2.6": 0.004,
5856
7044
  "moonshotai/kimi-k2.7": 0.004,
5857
7045
  "moonshotai/kimi-k3": 0.015,
7046
+ "moonshotai/kimi-k3.1": 0.01,
5858
7047
  "muse-spark-1.3": 0.00425,
5859
7048
  "qwen/qwen3-235b-a22b-2507": 0.0009064,
5860
7049
  "qwen/qwen3-30b-a3b-instruct-2507": 0.0006,
@@ -5878,6 +7067,7 @@ prices='{
5878
7067
  "claude-fable-5": 0.1,
5879
7068
  "claude-fable-5-1": 0.025,
5880
7069
  "claude-haiku-4-5": 0.1,
7070
+ "claude-haiku-5-5": 0.1,
5881
7071
  "claude-opus-4-0": 0.1,
5882
7072
  "claude-opus-4-1": 0.1,
5883
7073
  "claude-opus-4-5": 0.1,
@@ -5908,6 +7098,7 @@ prices='{
5908
7098
  "gemini-3.6-flash": 0.1,
5909
7099
  "gemini-3.7-flash": 0.1,
5910
7100
  "gemini-3.8-flash": 0.1,
7101
+ "gemini-4-argon": 0.1,
5911
7102
  "google/gemma-4-26b-a4b-it": 0.1,
5912
7103
  "gpt-4.1": 0.25,
5913
7104
  "gpt-4.1-mini": 0.25,
@@ -5935,17 +7126,20 @@ prices='{
5935
7126
  "gpt-6-luna": 0.1,
5936
7127
  "gpt-6-sol": 0.1,
5937
7128
  "gpt-6.1-sol": 0.05,
7129
+ "gpt-6.1-terra": 0.05,
5938
7130
  "grok-4.5": 0.25,
5939
7131
  "grok-4.6": 0.25,
5940
7132
  "grok-4.7": 0.25,
5941
7133
  "inclusionai/ling-3.0-flash": 0.2,
5942
7134
  "minimax/minimax-m2.7": 0.2,
5943
7135
  "minimax/minimax-m3": 0.2,
7136
+ "minimax/minimax-m3.1-flash": 0.1,
5944
7137
  "mistralai/mistral-small-2603": 0.1,
5945
7138
  "moonshotai/kimi-k2.5": 0.5,
5946
7139
  "moonshotai/kimi-k2.6": 0.1684,
5947
7140
  "moonshotai/kimi-k2.7": 0.2,
5948
7141
  "moonshotai/kimi-k3": 0.1,
7142
+ "moonshotai/kimi-k3.1": 0.1,
5949
7143
  "muse-spark-1.3": 0.12,
5950
7144
  "qwen/qwen3-235b-a22b-2507": 0.5,
5951
7145
  "qwen/qwen3-30b-a3b-instruct-2507": 0.1684,
@@ -5957,7 +7151,7 @@ prices='{
5957
7151
  "qwen/qwen3.7-plus": 0.2,
5958
7152
  "qwen/qwen3.8-max": 0.125,
5959
7153
  "xiaomi/mimo-v2.5-pro": 0.1,
5960
- "xiaomi/mimo-v2.6-flash": 0.02,
7154
+ "xiaomi/mimo-v2.6-flash": 0.015384615384615385,
5961
7155
  "xiaomi/mimo-v2.6-pro": 0.00827586,
5962
7156
  "z-ai/glm-5": 0.2,
5963
7157
  "z-ai/glm-5.1": 0.18571428571428572,
@@ -5998,38 +7192,37 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
5998
7192
  transcript_model="$(normalize_model "$transcript_model")"
5999
7193
  fi
6000
7194
 
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)"
7195
+ # Fold acknowledged transitions in transcript order. Content-block copies and
7196
+ # replayed outcome IDs are the same event, not a newer state change.
7197
+ force_state="$(jq -nRr '
7198
+ def model: type == "string" and test("^[A-Za-z0-9._:/-]{1,128}$");
7199
+ def valid_command_outcome:
7200
+ 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}$"))
7201
+ and (.command | IN("force_model", "router_session", "router_models", "router_feedback", "loop_stop"))
7202
+ and (.disposition | IN("accepted", "rejected"))
7203
+ and (.pin.transition | IN("unchanged", "applied", "cleared"))
7204
+ and (if .pin.transition == "unchanged" then true else
7205
+ .command == "force_model" and .disposition == "accepted" end)
7206
+ and (if .pin.transition == "applied" then (.pin.model | model)
7207
+ and (.pin.provider | model)
7208
+ and ((.pin.effort // "") | type == "string" and test("^[A-Za-z0-9_-]{0,32}$")) else true end)) catch false;
7209
+ reduce (inputs | fromjson? | objects) as $entry ({seen:{}, pin:null};
7210
+ if $entry.type != "assistant" or $entry.message.model != "weave-router" then .
7211
+ elif ($entry.message | has("router_command")) then
7212
+ $entry.message.router_command as $o |
7213
+ if ($o | valid_command_outcome) and (.seen[$o.id] != true) then
7214
+ .seen[$o.id] = true |
7215
+ if $o.pin.transition == "applied" then
7216
+ .pin = ($o.pin.model + (if ($o.pin.effort // "") == "" then "" else ":" + $o.pin.effort end))
7217
+ elif $o.pin.transition == "cleared" then .pin = null else . end
7218
+ else . end
7219
+ else
7220
+ ([$entry.message.content[]? | select(.type? == "text") | .text] | join(" ") | sub("^(?:✦ \\*\\*Weave Router\\*\\* →|Weave Router:)[[:space:]]*"; "")) as $t |
7221
+ if ($t | test("^force-(model|parent) applied: [A-Za-z0-9._:/-]+")) then
7222
+ .pin = ($t | capture("force-(?:model|parent) applied: (?<m>[A-Za-z0-9._:/-]+)").m)
7223
+ elif ($t | test("^force-model cleared\\b")) then .pin = null else . end
7224
+ end) | if .pin then "APPLIED " + .pin else "CLEARED" end
7225
+ ' "$transcript_path" 2>/dev/null || true)"
6033
7226
  if [[ "$force_state" == APPLIED\ * ]]; then
6034
7227
  has_pin_record="true"
6035
7228
  last_pin_model="${force_state#APPLIED }"
@@ -6121,38 +7314,174 @@ weave_refresh_on_price_miss() {
6121
7314
  }
6122
7315
  weave_refresh_on_price_miss "$requested_norm" "$transcript_model" 2>/dev/null || true
6123
7316
 
7317
+ router_context_fallback() {
7318
+ [ -z "$context_clause" ] || return 0
7319
+ [ "${WEAVE_STATUSLINE_CONTEXT:-1}" != "0" ] || return 0
7320
+ local session helper_dir scope cache root now snapshot
7321
+ session="$(jq -r '.session_id // empty' <<<"$input")"
7322
+ case "$session" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
7323
+ [ "${#session}" -le 128 ] || return 0
7324
+ helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
7325
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
7326
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-context"
7327
+ cache="$root/$scope-$session.json"
7328
+ mkdir -p "$root" 2>/dev/null || return 0
7329
+ chmod 700 "$root"
7330
+ local generation active_file
7331
+ active_file="$cache.active"
7332
+ now="$(date +%s)"
7333
+ if [ -f "$cache" ] && [ "$(wc -c <"$cache")" -le 8192 ]; then
7334
+ snapshot="$(jq -ce --arg session "$session" --argjson now "$now" '
7335
+
7336
+ def tokens: type == "number" and floor == . and . > 0 and . <= 2147483647;
7337
+ def epoch: sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601;
7338
+ .context_snapshot as $s |
7339
+ select(.session_id == $session and $s.version == 1 and $s.estimate_kind == "approximate") |
7340
+ select(($s.estimate_tokens | tokens) and ($s.context_window | tokens) and ($s.output_reserve_tokens | tokens)) |
7341
+ select(($s.served_model | type) == "string" and ($s.served_model | test("^[A-Za-z0-9._:/-]{1,128}$"))) |
7342
+ select(($s.request_id | type) == "string" and ($s.request_id | length) > 0 and ($s.request_id | length) <= 128) |
7343
+ ($s.recorded_at | epoch) as $recorded | ($s.requested_at | epoch) as $requested |
7344
+ select($requested > 0 and $requested <= $recorded and $recorded <= $now and $now - $recorded <= 300) |
7345
+ $s
7346
+ ' "$cache" 2>/dev/null)" || snapshot=""
7347
+ if [ -n "$snapshot" ]; then
7348
+ local served requested
7349
+ served="$(normalize_model "$(jq -r '.served_model' <<<"$snapshot")")"
7350
+ requested="$(normalize_model "$(jq -r '.requested_model // empty' <<<"$snapshot")")"
7351
+ if [ "$served" = "$transcript_model" ] && [ "$requested" = "$requested_norm" ]; then
7352
+ context_clause="$(awk -v e="$(jq -r '.estimate_tokens' <<<"$snapshot")" -v w="$(jq -r '.context_window' <<<"$snapshot")" 'BEGIN {
7353
+ printf " · last Router ctx est. ~%s/%s", (e < 1000 ? e : sprintf("%.0fk", e/1000)), (w < 1000 ? w : sprintf("%.0fk", w/1000))
7354
+ }')"
7355
+ fi
7356
+ fi
7357
+ fi
7358
+ command -v curl >/dev/null 2>&1 || return 0
7359
+ mkdir -p "$root" 2>/dev/null || return 0
7360
+ chmod 700 "$root"
7361
+ (
7362
+ exec </dev/null
7363
+ # Serialize refreshes; a timeout cannot delay the status-line process.
7364
+ if ! mkdir "$cache.lock" 2>/dev/null; then
7365
+ lock_mtime="$(stat -c %Y "$cache.lock" 2>/dev/null || stat -f %m "$cache.lock" 2>/dev/null)" || lock_mtime=0
7366
+ [ $(( $(date +%s) - lock_mtime )) -gt 30 ] || exit 0
7367
+ dead="$cache.lock.dead.$$"
7368
+ mv "$cache.lock" "$dead" 2>/dev/null || exit 0
7369
+ rm -rf "$dead"
7370
+ mkdir "$cache.lock" 2>/dev/null || exit 0
7371
+ fi
7372
+ trap 'rmdir "$cache.lock" 2>/dev/null' EXIT
7373
+ generation="$(mktemp "$root/.generation.XXXXXX")" || exit 0
7374
+ printf '%s' "$generation" >"$generation"
7375
+ chmod 600 "$generation"
7376
+ mv "$generation" "$active_file"
7377
+ settings_base="$HOME"
7378
+ case "$helper_dir" in */.claude) settings_base="${helper_dir%/.claude}" ;; esac
7379
+ settings="$settings_base/.claude/settings.json"
7380
+ local_settings="$settings_base/.claude/settings.local.json"
7381
+ base=""
7382
+ key=""
7383
+ for settings_file in "$settings" "$local_settings"; do
7384
+ [ -f "$settings_file" ] || continue
7385
+ if jq -e '.env | has("ANTHROPIC_BASE_URL")' "$settings_file" >/dev/null 2>&1; then
7386
+ base="$(jq -r '.env.ANTHROPIC_BASE_URL // empty' "$settings_file" 2>/dev/null)"
7387
+ fi
7388
+ if jq -e '.env | has("ANTHROPIC_CUSTOM_HEADERS")' "$settings_file" >/dev/null 2>&1; then
7389
+ 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)"
7390
+ fi
7391
+ done
7392
+ base="${WEAVE_ROUTER_BASE_URL:-${ANTHROPIC_BASE_URL:-$base}}"
7393
+ key="${WEAVE_ROUTER_KEY:-$key}"
7394
+ [ -n "$base" ] && [ -n "$key" ] || exit 0
7395
+ url="${base%/}"
7396
+ case "$url" in file://*) ;; *) url="${url%/v1}/v1/sessions/$session/cost" ;; esac
7397
+ tmp="$(mktemp "$root/.snapshot.XXXXXX")" || exit 0
7398
+ header_file="$(mktemp "$root/.headers.XXXXXX")" || { rm -f "$tmp"; exit 0; }
7399
+ chmod 600 "$tmp"
7400
+ chmod 600 "$header_file"
7401
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
7402
+ if curl -fsS --max-time 5 --max-filesize 8192 -K "$header_file" "$url" -o "$tmp" 2>/dev/null \
7403
+ && [ "$(wc -c <"$tmp")" -le 8192 ] \
7404
+ && [ "$(jq -r '.session_id // empty' "$tmp" 2>/dev/null)" = "$session" ]; then
7405
+ # Request observation order is independent of fetch completion order.
7406
+ # Fraction padding preserves RFC3339Nano order within the same second.
7407
+ previous="$cache"
7408
+ [ -f "$previous" ] || previous=/dev/null
7409
+ if [ "$(cat "$active_file" 2>/dev/null)" = "$generation" ] && jq -e -s '
7410
+ def timestamp_parts: split(".") as $p |
7411
+ [($p[0] | sub("Z$"; "")), ((($p[1] // "") | sub("Z$"; "")) + "000000000")[0:9]];
7412
+ def observation: [.context_snapshot.requested_at | timestamp_parts] + [.context_snapshot.recorded_at | timestamp_parts];
7413
+ (.[0] | observation) as $fresh |
7414
+ 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
7415
+ ' "$tmp" "$previous" 2>/dev/null; then
7416
+ mv "$tmp" "$cache"
7417
+ fi
7418
+ fi
7419
+ rm -f "$tmp" "$header_file"
7420
+ ) >/dev/null 2>&1 &
7421
+ disown 2>/dev/null || true
7422
+ }
7423
+ router_context_fallback 2>/dev/null || true
7424
+
6124
7425
  # Brand color (#FF6C47) on terminals that grok 24-bit truecolor — that's
6125
7426
  # every modern one (iTerm2, Apple Terminal, vscode, ghostty, alacritty,
6126
7427
  # wezterm, kitty). Falls back gracefully on any escape-stripping terminal.
6127
7428
  brand=$'\033[38;2;255;108;71mWEAVE ROUTER\033[0m'
6128
7429
 
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
7430
 
6139
- printf '%s' "$brand"
7431
+ # "you picked" is Claude Code's selection; "served" is the latest response
7432
+ # model in the transcript. The cost clause is the whole session priced at the
7433
+ # served models versus the pick, so an upgrade reads as "more", not a negative
7434
+ # saving.
7435
+ short_model() { printf '%s' "${1#claude-}"; }
7436
+ picked=""
7437
+ if [[ -n "$selected_display" && "$selected_display" != "?" ]]; then
7438
+ picked="$(short_model "$requested_norm")"
7439
+ fi
7440
+ status_text=""
6140
7441
  if [[ "$transcript_model" == "failure" ]]; then
6141
- printf ' · last response failed'
7442
+ status_text=" · last response failed"
6142
7443
  elif [[ "$transcript_model" == "weave-router" ]]; then
6143
- printf ' · control acknowledgement'
7444
+ status_text=" · control acknowledgement"
6144
7445
  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"
7446
+ if [[ -n "$picked" && "$transcript_model" != "$requested_norm" ]]; then
7447
+ status_text=" · you picked $picked → served $(short_model "$transcript_model")"
7448
+ else
7449
+ status_text=" · served $(short_model "$transcript_model")"
7450
+ fi
7451
+ elif [[ -n "$picked" ]]; then
7452
+ status_text=" · you picked $picked"
6149
7453
  fi
6150
7454
  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")"
7455
+ status_text="$status_text$(awk -v v="$session_cost_difference" -v pick="$picked" 'BEGIN{
7456
+ v = v + 0
7457
+ if (v >= 0.005) printf " · saved ~$%.2f this session", v
7458
+ else if (v > 0) printf " · saved <$0.01 this session"
7459
+ else if (v == 0) printf " · no savings yet this session"
7460
+ else if (v > -0.005) printf " · cost <$0.01 more than %s this session", pick
7461
+ else printf " · cost ~$%.2f more than %s this session (upgraded hard turns)", -v, pick
7462
+ }')"
6152
7463
  fi
6153
7464
  if [[ "$has_pin_record" == "true" ]]; then
6154
- printf ' · last pin: %s' "$last_pin_model"
7465
+ status_text="$status_text · last pin: $last_pin_model"
6155
7466
  fi
7467
+
7468
+ # /router-status reads this back through the prompt hook, so it can answer
7469
+ # without a model turn.
7470
+ weave_cache_status_line() {
7471
+ local session root
7472
+ session="$(jq -r '.session_id // empty' <<<"$input")"
7473
+ case "$session" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
7474
+ [ "${#session}" -le 128 ] || return 0
7475
+ [ -n "$transcript_model" ] || return 0
7476
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-status"
7477
+ mkdir -p "$root" && chmod 700 "$root" || return 0
7478
+ printf '%s\n' "${status_text# · }" >"$root/$session.line.$$" \
7479
+ && mv -f "$root/$session.line.$$" "$root/$session.line"
7480
+ }
7481
+ weave_cache_status_line 2>/dev/null || true
7482
+
7483
+ printf '%s%s' "$brand" "$status_text"
7484
+ printf '%s' "$context_clause"
6156
7485
  STATUSLINE_EOF
6157
7486
  chmod +x "$statusline_file"
6158
7487
  printf '%s\n' "$CLAUDE_STATUSLINE_MARKER" >"$statusline_ownership_file"
@@ -6197,22 +7526,28 @@ write_claude_settings() {
6197
7526
  # Setting ANTHROPIC_BASE_URL makes Claude Code treat us as non-first-party.
6198
7527
  # Force tool-search deferral to match first-party Claude Code; "auto" can inline
6199
7528
  # every tool schema when the custom endpoint advertises a 200K context window.
7529
+ local prompt_hook_scope=""
7530
+ if [ -n "$install_dir" ]; then
7531
+ prompt_hook_scope=" --dir $(printf '%q' "$install_dir")"
7532
+ elif [ "$scope" = "project" ]; then
7533
+ prompt_hook_scope=" --scope project"
7534
+ fi
6200
7535
  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: {
7536
+ 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" '{
7537
+ env: { ANTHROPIC_BASE_URL: $url, ENABLE_TOOL_SEARCH: "true" }
7538
+ } + (if $attribution == "true" then {attribution: {
6204
7539
  commit: "Co-Authored-By: Weave Router <router@weaveos.com>",
6205
- 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"
7540
+ pr: "🤖 Generated with [Weave Router](https://router.weaveos.com)"
7541
+ }} else {} end) + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl },
7542
+ hooks: {UserPromptSubmit: [{hooks: [{type: "command", command: ("[ ! -x \"" + $sl + "\" ] || \"" + $sl + "\" --prompt-hook" + $prompt_hook_scope)}]}]}} else {} end)' >"$tmp_patch"
6208
7543
  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: {
7544
+ 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" '{
7545
+ env: { ANTHROPIC_BASE_URL: $url, ANTHROPIC_CUSTOM_HEADERS: $header, ENABLE_TOOL_SEARCH: "true" }
7546
+ } + (if $attribution == "true" then {attribution: {
6212
7547
  commit: "Co-Authored-By: Weave Router <router@weaveos.com>",
6213
- 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"
7548
+ pr: "🤖 Generated with [Weave Router](https://router.weaveos.com)"
7549
+ }} else {} end) + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl },
7550
+ hooks: {UserPromptSubmit: [{hooks: [{type: "command", command: ("[ ! -x \"" + $sl + "\" ] || \"" + $sl + "\" --prompt-hook" + $prompt_hook_scope)}]}]}} else {} end)' >"$tmp_patch"
6216
7551
  fi
6217
7552
 
6218
7553
  # Merge with existing settings. Deep-merge env and replace statusLine only
@@ -6230,13 +7565,29 @@ write_claude_settings() {
6230
7565
  | (if (.env | length) == 0 then del(.env) else . end)
6231
7566
  | del(.apiKeyHelper)
6232
7567
  | (if $b.statusLine then .statusLine = $b.statusLine else . end)
6233
- | (if $b.attribution then .attribution = $b.attribution else . end)
7568
+ | (if $b.hooks then .hooks = ((.hooks // {})
7569
+ | .UserPromptSubmit = (((.UserPromptSubmit // [])
7570
+ | 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)))
7571
+ + $b.hooks.UserPromptSubmit))
7572
+ else . end)
7573
+ | (($a.attribution.commit // "") | startswith("Co-Authored-By: Weave Router")) as $ours
7574
+ | (($a.env // {} | has("ANTHROPIC_BASE_URL")) and $a.attribution == null) as $opted_out
7575
+ | (if $b.attribution and ($ours or ($a.attribution == null and ($opted_out | not)))
7576
+ then .attribution = $b.attribution
7577
+ elif ($b.attribution | not) and $ours then
7578
+ .attribution |= (del(.commit)
7579
+ | if (.pr == "🤖 Generated with [Weave Router](https://router.weaveos.com)" or .pr == "🤖 Generated with [Weave Router](https://router.workweave.ai)") then del(.pr) else . end)
7580
+ | (if (.attribution | length) == 0 then del(.attribution) else . end)
7581
+ else . end)
6234
7582
  ' "$settings_file" "$tmp_patch")"
6235
7583
  printf '%s\n' "$merged" >"$settings_file"
6236
7584
  else
6237
7585
  cp "$tmp_patch" "$settings_file"
6238
7586
  fi
6239
7587
  ok "Settings written to $settings_file"
7588
+ if [ "$quiet" != "true" ] && jq -e '(.attribution.commit // "") | startswith("Co-Authored-By: Weave Router")' "$settings_file" >/dev/null 2>&1; then
7589
+ info "Claude Code will credit Weave Router in commits (Co-Authored-By) and PR descriptions. To turn this off, re-run with --no-attribution."
7590
+ fi
6240
7591
 
6241
7592
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
6242
7593
  jq -n --arg header "$custom_headers" --arg router_url "$base_url" '{
@@ -6315,4 +7666,4 @@ verify_install
6315
7666
  # ---------- done ----------
6316
7667
 
6317
7668
  announce_done "Claude Code"
6318
- [ "$mode" = "update" ] || print_uninstall_hint
7669
+ finish_install "Claude Code" claude