@weave-os/router 0.2.18 → 0.2.20

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
@@ -5,17 +5,21 @@
5
5
  # Configures Claude Code (default), the OpenAI Codex CLI (`--codex`),
6
6
  # opencode (`--opencode`), or pi (`--pi`) to permanently route through the
7
7
  # Weave Router. For Claude Code this writes the router base URL, router auth
8
- # header, and a status line into Claude Code's settings.json. For Codex it
9
- # writes a `model_providers.weave` entry plus `model_provider = "weave"` into
10
- # ~/.codex/config.toml (managed block delimited by markers). For opencode
11
- # it merges a `provider.weave` block (anthropic-compatible) into
12
- # opencode.json — since the file is JSON, install/uninstall are structural
13
- # (jq) rather than marker-delimited. For pi it merges a `weave` provider into
8
+ # header, and a status line into Claude Code's settings.json unless Claude Code
9
+ # already has an active statusline configured. For Codex it writes a
10
+ # `model_providers.weave` entry plus `model_provider = "weave"` into
11
+ # ~/.codex/config.toml (managed block delimited by markers). For opencode it
12
+ # merges a Responses-format `provider.weave` block into opencode.json — since
13
+ # the file is JSON, install/uninstall are structural (jq) rather than
14
+ # marker-delimited. For pi it merges a `weave` provider into
14
15
  # ~/.pi/agent/models.json, sets it as the default in settings.json, and adds
15
16
  # the @weave-os/router extension (which also adds a parallel subagent
16
17
  # `dispatch` tool) — all structural (jq) merges.
17
18
  #
18
19
  # Two scopes (apply to all targets):
20
+ # --context-window 1m Opt Claude Code into its selected model's 1M variant.
21
+ # Preserves the prior setting for off/uninstall; never disables compaction.
22
+ #
19
23
  # - user (default): ~/.claude/settings.json + ~/.weave/cc-statusline.sh
20
24
  # ~/.codex/config.toml (with --codex)
21
25
  # ~/.config/opencode/opencode.json (with --opencode)
@@ -48,6 +52,7 @@
48
52
  # npx @weave-os/router --dir /tmp/my-sandbox # isolated throwaway install
49
53
  # npx @weave-os/router --local # local router on localhost:8080
50
54
  # npx @weave-os/router --base-url http://localhost:8080 # self-hosted, custom port
55
+ # npx @weave-os/router --email you@example.com # set the router identity email without prompting
51
56
  # npx @weave-os/router --non-interactive # require WEAVE_ROUTER_KEY env var (defaults target to claude)
52
57
  # npx @weave-os/router --quiet # suppress banner, ping check, and trailing tips
53
58
  # npx @weave-os/router --rotate-key # ignore the installed key and prompt for a new one
@@ -73,11 +78,11 @@
73
78
  # Cursor's base URL lives in its own settings UI (no file we own), so there's
74
79
  # nothing to toggle here — flip "Override OpenAI Base URL" in Cursor settings.
75
80
  #
76
- # Which router directives each client gets is declared once in
81
+ # Which router integrations each client gets is declared once in
77
82
  # install/directives.tsv and installed from there: Claude Code and opencode get
78
- # Markdown slash commands, Codex gets native `$name` skills (it reserves `/…`
79
- # for built-ins), pi registers /fm and /ufm in its extension, and Cursor is
80
- # manual. See install/README.md for the full matrix.
83
+ # Markdown slash commands, Codex gets native `$name` skills, pi registers /fm
84
+ # and /ufm in its extension, and Cursor is manual. See install/README.md for
85
+ # the full matrix.
81
86
  #
82
87
  # Inspect and edit which models this installation lets the router pick from —
83
88
  # the same lists the router dashboard's settings page renders. The endpoint and
@@ -109,10 +114,13 @@ npm_package_name="${WEAVE_ROUTER_NPM_PACKAGE:-@weave-os/router}"
109
114
 
110
115
 
111
116
  scope="user"
117
+ context_window=""
112
118
  scope_explicit="false"
113
119
  install_dir=""
114
120
  base_url=""
115
121
  base_url_explicit="false"
122
+ email=""
123
+ email_explicit="false"
116
124
  non_interactive="false"
117
125
  quiet="false"
118
126
  router_key_header="X-Weave-Router-Key"
@@ -120,9 +128,9 @@ router_key_header="X-Weave-Router-Key"
120
128
  # settings.json; "codex" writes ~/.codex/config.toml; "opencode" merges a
121
129
  # provider block into opencode.json. Each target carries its own
122
130
  # credential-passthrough story in the router: Claude Code's logged-in
123
- # Anthropic key flows through unchanged, Codex's `OPENAI_API_KEY` flows
124
- # through via the same header path, and opencode talks to the router via
125
- # its anthropic-compatible API surface. target_explicit tracks whether
131
+ # Anthropic key flows through unchanged, Codex's ChatGPT credential flows
132
+ # through its native provider, and opencode uses the Responses API plus
133
+ # dedicated subscription headers. target_explicit tracks whether
126
134
  # --claude / --codex / --opencode was passed so an interactive run can
127
135
  # prompt for the choice.
128
136
  target="claude"
@@ -362,6 +370,37 @@ refuse_if_symlink() {
362
370
  fi
363
371
  }
364
372
 
373
+ # The marker is part of the installed script, so a user-owned script at the
374
+ # same conventional path can be distinguished from one managed by the router.
375
+ CLAUDE_STATUSLINE_MARKER="# Claude Code statusline for the Weave Router."
376
+
377
+ # claude_statusline_configured reports whether Claude Code has a non-null
378
+ # statusline setting in a settings file.
379
+ claude_statusline_configured() {
380
+ local settings_path="$1"
381
+ [ -f "$settings_path" ] || return 1
382
+ jq -e 'has("statusLine") and (.statusLine != null)' "$settings_path" >/dev/null 2>&1
383
+ }
384
+
385
+ # claude_statusline_router_owned reports whether a settings entry points at the
386
+ # router's statusline. Existing scripts prove ownership with the marker; when a
387
+ # script is missing, the adjacent ownership marker proves that the router wrote
388
+ # it and should recreate it.
389
+ claude_statusline_router_owned() {
390
+ local settings_path="$1" expected_command="$2" script_path="$3" ownership_marker_path="$4" configured_command
391
+ [ -f "$settings_path" ] || return 1
392
+ configured_command="$(jq -r '.statusLine.command // empty' "$settings_path" 2>/dev/null || true)"
393
+ [ "$configured_command" = "$expected_command" ] || return 1
394
+ if [ -f "$script_path" ]; then
395
+ if grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$script_path" 2>/dev/null; then
396
+ return 0
397
+ fi
398
+ [ -r "$script_path" ] && return 1
399
+ fi
400
+ [ -f "$ownership_marker_path" ] \
401
+ && grep -Fq "$CLAUDE_STATUSLINE_MARKER" "$ownership_marker_path"
402
+ }
403
+
365
404
  # Markers that delimit the block this installer manages inside Codex's
366
405
  # config.toml. Kept on disk verbatim so a re-install (or uninstall.sh
367
406
  # --codex) can find and replace the block instead of duplicating it.
@@ -430,12 +469,20 @@ normalize_name() {
430
469
 
431
470
  # resolve_user_email picks the email to plant in router request headers so the
432
471
  # router can attribute traffic to a person even on shared API keys. Priority:
433
- # WEAVE_USER_EMAIL env override → git config user.email → interactive prompt
434
- # (pre-filled with whatever we found). In --non-interactive mode we never
435
- # prompt, so unset/invalid means we ship no header (router treats that as
436
- # account_uuid-only, same as today). Echoes the validated email on stdout.
472
+ # explicit --email → WEAVE_USER_EMAIL env override → git config user.email →
473
+ # interactive prompt (pre-filled with whatever we found). In --non-interactive
474
+ # mode we never prompt, so unset/invalid means we ship no header (router treats
475
+ # that as account_uuid-only, same as today). Echoes the validated email on stdout.
437
476
  resolve_user_email() {
438
477
  local candidate=""
478
+ if [ "$email_explicit" = "true" ]; then
479
+ candidate="$(normalize_email "$email")"
480
+ if [ -z "$candidate" ]; then
481
+ warn "--email=\"$email\" is not a valid email; ignoring."
482
+ fi
483
+ printf '%s' "$candidate"
484
+ return
485
+ fi
439
486
  if [ -n "${WEAVE_USER_EMAIL:-}" ]; then
440
487
  candidate="$(normalize_email "$WEAVE_USER_EMAIL")"
441
488
  if [ -z "$candidate" ]; then
@@ -552,6 +599,11 @@ weave_owns_codex_helper() {
552
599
  weave_owned_codex_helpers() {
553
600
  weave_owns_codex_helper "${codex_status_file:-}" '<!-- weave-router managed codex status -->' rewrite \
554
601
  && printf '%s\n' "$codex_status_file"
602
+ # delete, not rewrite: unlike the status helper, a symlink at the directive
603
+ # path is never ours even when its target carries the marker. Classifying it
604
+ # rewrite-owned made a reinstall follow the link and overwrite whatever it
605
+ # pointed at. install_codex_directive_script skips symlinks for the same
606
+ # reason, so the two stay consistent.
555
607
  weave_owns_codex_helper "${codex_directive_file:-}" '<!-- weave-router managed codex directive -->' delete \
556
608
  && printf '%s\n' "$codex_directive_file"
557
609
  return 0
@@ -662,6 +714,7 @@ write_codex_config() {
662
714
  esc_name="$(toml_escape "$block_name")"
663
715
  esc_url="$(toml_escape "$block_url")"
664
716
  esc_status="$(toml_escape "$codex_status_file")"
717
+ esc_directive="$(toml_escape "$codex_directive_file")"
665
718
 
666
719
  # Plant whichever identity values we have alongside the router key so the
667
720
  # router can attribute Codex traffic to a person on shared keys. Build the
@@ -701,6 +754,25 @@ write_codex_config() {
701
754
  hook_feature_line=""
702
755
  fi
703
756
  if [ "$codex_hooks_enabled" = "true" ]; then
757
+ # UserPromptSubmit is registered only when OUR hook is actually on disk.
758
+ # Existence alone is the wrong test: install_codex_directive_script leaves
759
+ # a user-owned file at that path untouched, and registering it would hand
760
+ # someone else's script every prompt. Registering a command that is not
761
+ # there is the other failure -- Codex then fails every prompt rather than
762
+ # every toggle -- so the file must exist and carry our marker. -L is
763
+ # checked first because -f follows the link: a symlink to a marked file is
764
+ # still not a file we may point Codex at.
765
+ local directive_hook_block=""
766
+ if [ ! -L "$codex_directive_file" ] && [ -f "$codex_directive_file" ] && grep -Fq '<!-- weave-router managed codex directive -->' "$codex_directive_file"; then
767
+ directive_hook_block="$(cat <<TOML
768
+
769
+ [[hooks.UserPromptSubmit]]
770
+ [[hooks.UserPromptSubmit.hooks]]
771
+ type = "command"
772
+ command = "${esc_directive}"
773
+ TOML
774
+ )"
775
+ fi
704
776
  hook_block="$(cat <<TOML
705
777
 
706
778
  [[hooks.SessionStart]]
@@ -713,7 +785,7 @@ command = "${esc_status}"
713
785
  type = "command"
714
786
  command = "${esc_status}"
715
787
  TOML
716
- )"
788
+ )${directive_hook_block}"
717
789
  fi
718
790
  local block
719
791
  block="$(cat <<TOML
@@ -886,6 +958,9 @@ write_opencode_config() {
886
958
  # upstream model for every request, so presenting pinned model names would
887
959
  # imply a choice that the router intentionally does not honor. Whichever
888
960
  # model serves a turn uses its matching subscription when one is connected.
961
+ # OpenCode interprets omitted custom-model limits as zero, which disables its
962
+ # overflow compaction. The 128K/32K virtual contract is the router's
963
+ # conservative compatibility floor and leaves 96K for model-visible input.
889
964
  #
890
965
  # npm is @ai-sdk/openai and baseURL KEEPS its /v1 here: opencode's
891
966
  # @ai-sdk/openai provider appends /responses, yielding the router's
@@ -902,10 +977,16 @@ write_opencode_config() {
902
977
  --argjson headers "$headers_json" '
903
978
  {
904
979
  npm: "@ai-sdk/openai",
905
- name: "Weave Router",
980
+ name: "Weave Router — Codex plan",
906
981
  options: { apiKey: $key, baseURL: $url, headers: $headers },
907
982
  models: {
908
- auto: { name: "Auto" }
983
+ auto: {
984
+ name: "Auto",
985
+ reasoning: true,
986
+ attachment: true,
987
+ modalities: { input: ["text", "image", "pdf"], output: ["text"] },
988
+ limit: { context: 128000, output: 32000 }
989
+ }
909
990
  }
910
991
  }
911
992
  ')"
@@ -944,20 +1025,43 @@ write_opencode_config() {
944
1025
  plugin_dir="$(cd "$(dirname "$config_file")" && pwd)/.weave"
945
1026
  plugin_spec="$plugin_dir/opencode-weave.ts"
946
1027
  plugin_src="$script_dir/opencode-weave/src/index.ts"
1028
+ plugin_directives_src="$script_dir/opencode-weave/src/directives.ts"
947
1029
  if [ -f "$plugin_src" ]; then
948
1030
  mkdir -p "$plugin_dir"
949
1031
  cp "$plugin_src" "$plugin_spec"
950
1032
  chmod 644 "$plugin_spec"
1033
+ if [ -f "$plugin_directives_src" ]; then
1034
+ cp "$plugin_directives_src" "$plugin_dir/directives.ts"
1035
+ chmod 644 "$plugin_dir/directives.ts"
1036
+ fi
951
1037
  plugin_arg="$plugin_spec"
952
1038
  else
953
1039
  warn "opencode subscription plugin source not found at $plugin_src — skipping the Claude login + subscription routing. (Use a packaged 'npx $npm_package_name' install.)"
954
1040
  fi
955
1041
 
1042
+ # Installing must actually activate the router. Preserve a prior direct model
1043
+ # beside the config so off/uninstall can restore the user's exact choice.
1044
+ local parked_file previous_model
1045
+ parked_file="$(dirname "$config_file")/.weave-parked.json"
1046
+ if [ -f "$config_file" ]; then
1047
+ previous_model="$(json_get "$config_file" '.model')"
1048
+ case "$previous_model" in
1049
+ ""|weave/*|weave-codex/*|weave-claude/*) ;;
1050
+ *)
1051
+ if [ "$scope" = "project" ] || [ -n "$install_dir" ]; then
1052
+ refuse_if_symlink "$parked_file"
1053
+ fi
1054
+ jq -n --arg direct "$previous_model" --arg router "weave/auto" \
1055
+ '{direct_model: $direct, router_model: $router}' >"$parked_file"
1056
+ chmod 600 "$parked_file"
1057
+ ;;
1058
+ esac
1059
+ fi
1060
+
956
1061
  # Merge into any existing opencode.json. We always overwrite provider.weave
957
1062
  # so re-install reflects the latest key/identity, but we leave the rest of the
958
- # file (other providers, mcp, agent settings) untouched. A previously
959
- # installed `weave/*` model is migrated to `weave/auto`; unrelated provider
960
- # choices stay untouched.
1063
+ # file (other providers, mcp, agent settings) untouched. The managed model is
1064
+ # always weave/auto; a prior direct choice was parked above for exact restore.
961
1065
  #
962
1066
  # The weave-claude login provider AND the plugin entry are written together
963
1067
  # only when the bundled plugin was present and copied ($plugin non-empty): the
@@ -985,12 +1089,7 @@ write_opencode_config() {
985
1089
  then (.plugin -= [$pluginspec]) | (if (.plugin | length) == 0 then del(.plugin) else . end)
986
1090
  else . end)
987
1091
  end)
988
- | (if (.model // "") == "" then .model = "weave/auto" else . end)
989
- # Replace any legacy Weave model choice with the single auto-routing
990
- # choice. Models from unrelated providers remain unchanged.
991
- | (if (.model // "" | tostring) as $model
992
- | ($model | startswith("weave/") or startswith("weave-codex/") or startswith("weave-claude/"))
993
- then .model = "weave/auto" else . end)
1092
+ | .model = "weave/auto"
994
1093
  | (.["$schema"] //= "https://opencode.ai/config.json")
995
1094
  ' "$config_file")"
996
1095
  else
@@ -1276,11 +1375,21 @@ while [ $# -gt 0 ]; do
1276
1375
  [ "$scope" = "user" ] || [ "$scope" = "project" ] || { err "--scope must be 'user' or 'project'."; exit 2; }
1277
1376
  scope_explicit="true"
1278
1377
  ;;
1378
+ --context-window)
1379
+ context_window="${2:-}"
1380
+ [ "$context_window" = "1m" ] || { err "--context-window requires '1m'."; exit 2; }
1381
+ shift 2
1382
+ ;;
1279
1383
  --base-url)
1280
1384
  base_url="${2:-}"; shift 2
1281
1385
  [ -n "$base_url" ] || { err "--base-url requires a value."; exit 2; }
1282
1386
  base_url_explicit="true"
1283
1387
  ;;
1388
+ --email)
1389
+ email="${2:-}"; shift 2
1390
+ [ -n "$email" ] || { err "--email requires a value."; exit 2; }
1391
+ email_explicit="true"
1392
+ ;;
1284
1393
  --local)
1285
1394
  # Shorthand for local dev: localhost:8080 (matches `wv mr` / `make dev` default PORT).
1286
1395
  base_url="http://localhost:8080"
@@ -1374,6 +1483,14 @@ while [ $# -gt 0 ]; do
1374
1483
  esac
1375
1484
  done
1376
1485
 
1486
+ if [ -n "$context_window" ]; then
1487
+ if [ "$target" != "claude" ] || { [ "$mode" != "install" ] && [ "$mode" != "update" ]; }; then
1488
+ err "--context-window is supported only for Claude Code install/update."
1489
+ exit 2
1490
+ fi
1491
+ target_explicit="true"
1492
+ fi
1493
+
1377
1494
  if [ "$mode" = "setup" ]; then
1378
1495
  if [ "$setup_claude" != "true" ] && [ "$setup_codex" != "true" ]; then
1379
1496
  setup_claude="true"
@@ -1385,6 +1502,7 @@ if [ "$mode" = "setup" ]; then
1385
1502
  setup_args=(--scope "$scope")
1386
1503
  [ "$non_interactive" = "true" ] && setup_args+=(--non-interactive)
1387
1504
  [ "$base_url_explicit" = "true" ] && setup_args+=(--base-url "$base_url")
1505
+ [ "$email_explicit" = "true" ] && setup_args+=(--email "$email")
1388
1506
  [ -n "$install_dir" ] && setup_args+=(--dir "$install_dir")
1389
1507
  [ "$quiet" = "true" ] && setup_args+=(--quiet)
1390
1508
  [ "$rotate_key" = "true" ] && setup_args+=(--rotate-key)
@@ -1806,6 +1924,10 @@ else
1806
1924
  fi
1807
1925
 
1808
1926
  if [ "$target" = "claude" ]; then
1927
+ statusline_install="true"
1928
+ statusline_source_file=""
1929
+ statusline_expected_command=""
1930
+ statusline_candidate_file=""
1809
1931
  case "$scope" in
1810
1932
  user)
1811
1933
  settings_dir="$settings_base/.claude"
@@ -1830,6 +1952,37 @@ if [ "$target" = "claude" ]; then
1830
1952
  fi
1831
1953
  ;;
1832
1954
  esac
1955
+ statusline_ownership_file="$statusline_file.weave-router"
1956
+
1957
+ # Check the effective settings layer. A user-owned statusline blocks the
1958
+ # install; a router-owned one is refreshed so reinstall repairs its script.
1959
+ if [ "$scope" = "project" ] \
1960
+ && claude_statusline_configured "$local_settings_file"; then
1961
+ statusline_source_file="$local_settings_file"
1962
+ statusline_expected_command="$statusline_path_for_settings"
1963
+ statusline_candidate_file="$statusline_file"
1964
+ elif claude_statusline_configured "$settings_file"; then
1965
+ statusline_source_file="$settings_file"
1966
+ statusline_expected_command="$statusline_path_for_settings"
1967
+ statusline_candidate_file="$statusline_file"
1968
+ elif [ "$scope" = "project" ] \
1969
+ && claude_statusline_configured "$HOME/.claude/settings.json"; then
1970
+ statusline_source_file="$HOME/.claude/settings.json"
1971
+ statusline_expected_command="$HOME/.weave/cc-statusline.sh"
1972
+ statusline_candidate_file="$HOME/.weave/cc-statusline.sh"
1973
+ fi
1974
+ if [ -n "$statusline_source_file" ] \
1975
+ && ! claude_statusline_router_owned \
1976
+ "$statusline_source_file" "$statusline_expected_command" \
1977
+ "$statusline_candidate_file" "$statusline_candidate_file.weave-router"; then
1978
+ statusline_install="false"
1979
+ skip "Existing Claude Code statusline detected; leaving it unchanged."
1980
+ fi
1981
+ if [ "$statusline_install" = "true" ] \
1982
+ && [ -f "$statusline_candidate_file" ] \
1983
+ && [ ! -w "$statusline_candidate_file" ]; then
1984
+ chmod u+rw "$statusline_candidate_file"
1985
+ fi
1833
1986
 
1834
1987
  # Symlink containment: refuse if any target path is a symlink. User-scope
1835
1988
  # paths under $HOME are trusted; project-scope and --dir paths come from a
@@ -1838,10 +1991,16 @@ if [ "$target" = "claude" ]; then
1838
1991
  refuse_if_symlink "$settings_dir"
1839
1992
  refuse_if_symlink "$settings_file"
1840
1993
  refuse_if_symlink "$local_settings_file"
1841
- refuse_if_symlink "$statusline_file"
1994
+ if [ "$statusline_install" = "true" ]; then
1995
+ refuse_if_symlink "$statusline_file"
1996
+ refuse_if_symlink "$statusline_ownership_file"
1997
+ fi
1842
1998
  fi
1843
1999
 
1844
- mkdir -p "$settings_dir" "$statusline_dir"
2000
+ mkdir -p "$settings_dir"
2001
+ if [ "$statusline_install" = "true" ]; then
2002
+ mkdir -p "$statusline_dir"
2003
+ fi
1845
2004
  elif [ "$target" = "codex" ]; then
1846
2005
  # Codex CLI reads config from ~/.codex/config.toml by default. For project
1847
2006
  # scope we write to <repo>/.codex/config.toml; the user invokes Codex with
@@ -2294,6 +2453,74 @@ gitignore_add() {
2294
2453
  fi
2295
2454
  }
2296
2455
 
2456
+ prepare_claude_context_window() {
2457
+ context_settings_file="$settings_file"
2458
+ if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
2459
+ context_settings_file="$local_settings_file"
2460
+ fi
2461
+ context_state_file="$settings_dir/.weave-context-window.json"
2462
+ refuse_if_symlink "$context_state_file"
2463
+ [ -n "$context_window" ] || return 0
2464
+
2465
+ local source model="" disabled="${CLAUDE_CODE_DISABLE_1M_CONTEXT:-}" env_model="${ANTHROPIC_MODEL:-}"
2466
+ # Highest-priority settings first; project opt-in is written only locally.
2467
+ for source in "$context_settings_file" "$settings_file" "$HOME/.claude/settings.json"; do
2468
+ [ -f "$source" ] || continue
2469
+ [ -n "$model" ] || model="$(json_get "$source" '.model')"
2470
+ [ -n "$disabled" ] || disabled="$(json_get "$source" '.env.CLAUDE_CODE_DISABLE_1M_CONTEXT')"
2471
+ [ -n "$env_model" ] || env_model="$(json_get "$source" '.env.ANTHROPIC_MODEL')"
2472
+ done
2473
+ if [ -n "$disabled" ] && [ "$disabled" != "0" ] && [ "$disabled" != "false" ]; then
2474
+ err "1M context is disabled in your Claude Code settings; remove that opt-out before using --context-window."
2475
+ return 1
2476
+ fi
2477
+ if [ -n "$env_model" ]; then
2478
+ err "ANTHROPIC_MODEL overrides the model setting. Select its [1m] variant there instead; leaving it unchanged."
2479
+ return 1
2480
+ fi
2481
+ model="${model:-sonnet}"
2482
+ case "$model" in
2483
+ *'[1m]') context_window=""; return 0 ;;
2484
+ sonnet|opus|fable|claude-sonnet-4-6|claude-sonnet-5|claude-opus-4-6|claude-opus-4-7|claude-opus-4-8|claude-opus-5|claude-fable-5|claude-fable-5-1) ;;
2485
+ *) err "Cannot assert 1M support for '$model'. Select a supported Sonnet/Opus/Fable model first; leaving it unchanged."; return 1 ;;
2486
+ esac
2487
+ context_managed_model="${model}[1m]"
2488
+ }
2489
+
2490
+ apply_claude_context_window() {
2491
+ local action="$1" active="$2" state="$settings_dir/.weave-context-window.json" merged tmp
2492
+ refuse_if_symlink "$state"
2493
+ [ -f "$active" ] || return 0
2494
+ if [ "$action" = "install" ] && [ -n "$context_window" ]; then
2495
+ tmp="$(mktemp "$settings_dir/.weave-context.XXXXXX")"
2496
+ jq --arg managed "$context_managed_model" '{had_model: has("model"), original: .model, managed: $managed}' "$active" >"$tmp"
2497
+ chmod 600 "$tmp"
2498
+ mv "$tmp" "$state"
2499
+ merged="$(jq --arg model "$context_managed_model" '.model = $model' "$active")"
2500
+ else
2501
+ [ -f "$state" ] || return 0
2502
+ merged="$(jq --slurpfile state "$state" --arg action "$action" '
2503
+ $state[0] as $s |
2504
+ if $action == "off" then
2505
+ if .model == $s.managed then
2506
+ if $s.had_model then .model = $s.original else del(.model) end
2507
+ else . end
2508
+ elif has("model") == $s.had_model and .model == $s.original then .model = $s.managed
2509
+ else . end
2510
+ ' "$active")"
2511
+ fi
2512
+ tmp="$(mktemp "$settings_dir/.weave-context.XXXXXX")"
2513
+ printf '%s\n' "$merged" >"$tmp"
2514
+ chmod 600 "$tmp"
2515
+ mv "$tmp" "$active"
2516
+ if [ "$action" = "install" ] && [ -n "$context_window" ]; then
2517
+ ok "Claude Code model set to $context_managed_model; automatic compaction stays enabled. Restart Claude Code."
2518
+ if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
2519
+ gitignore_add ".claude/.weave-context-window.json"
2520
+ fi
2521
+ fi
2522
+ }
2523
+
2297
2524
  toggle_claude() {
2298
2525
  local parked="$settings_dir/.weave-parked.json"
2299
2526
  local proj="false" active committed_base local_base parked_env merged
@@ -2357,6 +2584,7 @@ toggle_claude() {
2357
2584
  info "Claude Code isn't configured for the router. Run the installer first."
2358
2585
  return 0
2359
2586
  fi
2587
+ apply_claude_context_window off "$active"
2360
2588
  if [ "$proj" = "true" ]; then
2361
2589
  # Park the whole local env (carries the key header), then override the
2362
2590
  # base URL to Anthropic in the local file only — committed settings.json
@@ -2442,6 +2670,7 @@ toggle_claude() {
2442
2670
  merged="$(jq --argjson p "$parked_env" '.env = (((.env // {}) | del(.ANTHROPIC_BASE_URL)) + $p)' "$active")"
2443
2671
  printf '%s\n' "$merged" >"$active"
2444
2672
  [ "$proj" = "true" ] && chmod 600 "$active"
2673
+ apply_claude_context_window on "$active"
2445
2674
  rm -f "$parked"
2446
2675
  ok "Claude Code is ${C_BOLD}on${C_RESET} (routing through the Weave Router). Restart Claude Code for it to take effect."
2447
2676
  ;;
@@ -2509,20 +2738,22 @@ toggle_codex() {
2509
2738
 
2510
2739
  toggle_opencode() {
2511
2740
  local f="$opencode_config_file" parked="$opencode_dir/.weave-parked.json"
2512
- local model="" has_weave="false" parked_present="false" on="false" restore_model merged
2741
+ local model="" direct_model="" router_model="weave/auto" has_weave="false" parked_present="false" on="false" merged model_id
2513
2742
  # Symlink containment for the parked sidecar — `off` writes it via shell
2514
2743
  # redirection; a hostile project repo could pre-place it as a symlink. The
2515
2744
  # opencode.json itself is already guarded during path resolution.
2516
2745
  if [ "$scope" = "project" ] || [ -n "$install_dir" ]; then
2517
2746
  refuse_if_symlink "$parked"
2518
2747
  fi
2519
- if [ -f "$parked" ]; then parked_present="true"; fi
2748
+ if [ -f "$parked" ]; then
2749
+ parked_present="true"
2750
+ direct_model="$(json_get "$parked" '.direct_model')"
2751
+ router_model="$(jq -r '.router_model // .model // "weave/auto"' "$parked" 2>/dev/null || echo "weave/auto")"
2752
+ fi
2520
2753
  if [ -f "$f" ]; then
2521
- model="$(jq -r '.model // empty' "$f" 2>/dev/null || true)"
2754
+ model="$(json_get "$f" '.model')"
2522
2755
  if [ "$(jq -r '((.provider // {}) | has("weave"))' "$f" 2>/dev/null || true)" = "true" ]; then has_weave="true"; fi
2523
2756
  fi
2524
- # A managed model counts as router-on: the Responses-shaped `weave/…` default,
2525
- # or a legacy `weave-codex/…` model parked by a pre-upgrade install.
2526
2757
  case "$model" in weave/* | weave-codex/*) on="true" ;; esac
2527
2758
 
2528
2759
  case "$mode" in
@@ -2540,52 +2771,48 @@ toggle_opencode() {
2540
2771
  if [ "$has_weave" = "true" ]; then ok "opencode is already off — nothing to do."; else info "opencode isn't configured for the router. Run the installer first."; fi
2541
2772
  return 0
2542
2773
  fi
2543
- jq '{model: .model}' "$f" >"$parked"
2774
+ router_model="$model"
2775
+ jq -n --arg direct "$direct_model" --arg router "$router_model" \
2776
+ '{direct_model: $direct, router_model: $router}' >"$parked"
2544
2777
  chmod 600 "$parked"
2545
- merged="$(jq 'del(.model)' "$f")"
2778
+ if [ -n "$direct_model" ]; then
2779
+ merged="$(jq --arg model "$direct_model" '.model = $model' "$f")"
2780
+ else
2781
+ merged="$(jq 'del(.model)' "$f")"
2782
+ fi
2546
2783
  printf '%s\n' "$merged" >"$f"
2547
2784
  chmod 600 "$f"
2548
2785
  gitignore_add ".weave-parked.json"
2549
- ok "opencode is ${C_BOLD}off${C_RESET} — pick a non-Weave model with /models. Takes effect on your next opencode run."
2786
+ if [ -n "$direct_model" ]; then
2787
+ ok "opencode is ${C_BOLD}off${C_RESET} — restored $direct_model. Takes effect on your next opencode run."
2788
+ else
2789
+ ok "opencode is ${C_BOLD}off${C_RESET} — choose a direct model with /models. Takes effect on your next opencode run."
2790
+ fi
2550
2791
  ;;
2551
2792
  on)
2552
2793
  if [ "$on" = "true" ]; then ok "opencode is already on — nothing to do."; return 0; fi
2553
- restore_model="weave/auto"
2554
- if [ "$parked_present" = "true" ]; then
2555
- restore_model="$(jq -r '.model // "weave/auto"' "$parked")"
2556
- elif [ "$has_weave" != "true" ]; then
2557
- warn "opencode isn't configured for the router. Run the installer first."; return 0
2558
- else
2559
- # No parked model (sidecar deleted by hand). Derive the default from the
2560
- # installed provider.weave.models block rather than a hardcoded literal
2561
- # that silently diverges when the installer's default changes — prefer
2562
- # the auto-routing entry, else the first model the installer registered.
2563
- restore_model="$(jq -r '
2564
- (.provider.weave.models // {} | keys) as $k
2565
- | (([$k[] | select(. == "auto")] | first) // $k[0] // "auto")
2566
- | "weave/" + .
2567
- ' "$f" 2>/dev/null || echo "weave/auto")"
2794
+ if [ "$has_weave" != "true" ]; then
2795
+ warn "opencode isn't configured for the router. Run the installer first."
2796
+ return 0
2568
2797
  fi
2569
- # Restore only a registered `weave` model. Legacy installations may have
2570
- # parked a pinned model, but a current install exposes only `weave/auto`.
2571
- case "$restore_model" in
2798
+ case "$model" in ""|weave/*|weave-codex/*) ;; *) direct_model="$model" ;; esac
2799
+ case "$router_model" in
2572
2800
  weave/*)
2573
- local model_id="${restore_model#weave/}"
2801
+ model_id="${router_model#weave/}"
2574
2802
  if ! jq -e --arg id "$model_id" '(.provider.weave.models // {}) | has($id)' "$f" >/dev/null 2>&1; then
2575
- restore_model="weave/auto"
2576
- fi
2577
- ;;
2578
- weave-codex/*)
2579
- if [ "$(jq -r '((.provider // {}) | has("weave-codex"))' "$f" 2>/dev/null || true)" != "true" ]; then
2580
- restore_model="weave/auto"
2803
+ router_model="weave/auto"
2581
2804
  fi
2582
2805
  ;;
2806
+ *) router_model="weave/auto" ;;
2583
2807
  esac
2584
- merged="$(jq --arg m "$restore_model" '.model = $m' "$f")"
2808
+ merged="$(jq --arg model "$router_model" '.model = $model' "$f")"
2585
2809
  printf '%s\n' "$merged" >"$f"
2586
2810
  chmod 600 "$f"
2587
- rm -f "$parked"
2588
- ok "opencode is ${C_BOLD}on${C_RESET} (default model $restore_model via the Weave Router). Takes effect on your next opencode run."
2811
+ jq -n --arg direct "$direct_model" --arg router "$router_model" \
2812
+ '{direct_model: $direct, router_model: $router}' >"$parked"
2813
+ chmod 600 "$parked"
2814
+ gitignore_add ".weave-parked.json"
2815
+ ok "opencode is ${C_BOLD}on${C_RESET} (default model $router_model via the Weave Router). Takes effect on your next opencode run."
2589
2816
  ;;
2590
2817
  esac
2591
2818
  }
@@ -3439,28 +3666,37 @@ EOF
3439
3666
  src="$commands_src_dir/$cmd.md"
3440
3667
  dst="$dst_dir/$cmd.md"
3441
3668
  [ -f "$src" ] || continue
3442
- if [ "$scope" = "project" ] || [ -n "$install_dir" ]; then
3443
- refuse_if_symlink "$dst"
3444
- fi
3445
3669
  # Substitute the {{SCOPE}} placeholder (only the router-* wrappers carry it;
3446
3670
  # cp-equivalent for the others since the token is absent).
3447
3671
  local body; body="$(cat "$src")"
3448
3672
  body="${body//\{\{SCOPE\}\}/$scope_args}"
3673
+ ownership_file="$dst.weave-router"
3674
+ if [ "$scope" = "project" ] || [ -n "$install_dir" ]; then
3675
+ refuse_if_symlink "$dst"
3676
+ refuse_if_symlink "$ownership_file"
3677
+ fi
3449
3678
  # Wrappers installed before ownership markers existed carry no marker. A
3450
3679
  # file whose body still matches what this installer would write is one of
3451
3680
  # ours from an older version, so adopt it rather than treating it as
3452
3681
  # user-owned — otherwise every pre-marker install is stranded: never
3453
3682
  # refreshed, never uninstalled, and skipped by the statusline refresh.
3454
- # Anything that does not match byte-for-byte is left alone.
3683
+ # The sidecar comparison also recognizes a router-owned wrapper after its
3684
+ # bundled body changes, while a user edit breaks that comparison.
3455
3685
  if [ -e "$dst" ] && { [ ! -f "$dst" ] || ! grep -Fq "<!-- weave-router managed command: $cmd -->" "$dst"; }; then
3456
3686
  if [ -f "$dst" ] && [ "$(cat "$dst")" = "$body" ]; then
3457
3687
  : # an unmarked copy of our own wrapper; fall through and adopt it
3688
+ elif [ -f "$ownership_file" ] \
3689
+ && [ "$(sed -n '1p' "$ownership_file")" = "weave-router managed command: $cmd" ] \
3690
+ && [ "$(sed '1d' "$ownership_file")" = "$(cat "$dst")" ]; then
3691
+ : # a markerless wrapper whose sidecar still matches its body
3458
3692
  else
3459
3693
  warn "A user-owned $target command already exists at $dst; leaving it untouched."
3460
3694
  continue
3461
3695
  fi
3462
3696
  fi
3463
- printf '%s\n<!-- weave-router managed command: %s -->' "$body" "$cmd" >"$dst"
3697
+ printf '%s\n' "$body" >"$dst"
3698
+ # Keep ownership metadata in a sidecar so Claude Code never sends it as prompt text.
3699
+ printf 'weave-router managed command: %s\n%s\n' "$cmd" "$body" >"$ownership_file"
3464
3700
  done
3465
3701
  seed_command_baseline "$commands_src_dir" "$cmds"
3466
3702
  ok "Slash commands written to $dst_dir ($installed)"
@@ -3702,11 +3938,12 @@ announce_done() {
3702
3938
  # latest known routed model in the terminal title. The embedded copy keeps the
3703
3939
  # standalone curl installer feature-complete; packaged installs use the
3704
3940
  # canonical sibling asset.
3705
- # remove_codex_directive_helper deletes the UserPromptSubmit helper shipped in
3706
- # 0.2.17. The router now answers those directives itself, so the hook is dead
3707
- # weight — and a registration left pointing at a deleted script would make Codex
3708
- # run a missing command on every prompt, so the two must go together.
3709
- # strip_weave_codex_hooks removes the registration; this removes the file.
3941
+ # remove_codex_directive_helper deletes the UserPromptSubmit helper. Install no
3942
+ # longer calls it — install_codex_directive_script writes the local-toggle hook
3943
+ # in its place — but uninstall still does, and a registration left pointing at a
3944
+ # deleted script would make Codex run a missing command on every prompt, so the
3945
+ # two must go together. strip_weave_codex_hooks removes the registration; this
3946
+ # removes the file.
3710
3947
  remove_codex_directive_helper() {
3711
3948
  [ -e "$codex_directive_file" ] || return 0
3712
3949
  # Skip, do not exit: a symlink here is the user's, and aborting would leave
@@ -4164,20 +4401,302 @@ CODEX_STATUS_EOF
4164
4401
  ok "Codex status integration installed at $codex_status_file"
4165
4402
  }
4166
4403
 
4404
+ # Install the UserPromptSubmit hook that answers the four local-config toggles
4405
+ # ($router-on/off/status, $disable-routing) without an inference turn.
4406
+ #
4407
+ # Only these four. Everything the router can answer it already answers itself,
4408
+ # and a hook that also intercepted those would re-open the duplicate-path
4409
+ # problem #1257 closed. What is left here cannot move server-side at all: they
4410
+ # rewrite this machine's config.toml, and $router-off in particular must keep
4411
+ # working when the router is the thing that is broken.
4412
+ #
4413
+ # Mirrors install_codex_status_script, with one addition: the {{SCOPE}} token
4414
+ # is substituted the same way install_slash_commands does it, because the
4415
+ # installed hook cannot discover at run time which install it belongs to.
4416
+ install_codex_directive_script() {
4417
+ local candidate directive_src=""
4418
+ for candidate in \
4419
+ "$script_dir/codex-toggle.sh" \
4420
+ "$script_dir/../codex-toggle.sh"
4421
+ do
4422
+ if [ -f "$candidate" ]; then
4423
+ directive_src="$candidate"
4424
+ break
4425
+ fi
4426
+ done
4427
+ # Every bail-out below is a skip, never a failure. Unlike the status helper,
4428
+ # this hook has a working fallback -- the toggle skills still shell out to
4429
+ # the same installer -- so refusing to install the router because of a stray
4430
+ # file would cost the user far more than the two turns the hook saves.
4431
+ #
4432
+ # No sibling asset means a standalone `curl | sh` install, which has only
4433
+ # this file. The embedded copy below keeps that path feature-complete;
4434
+ # install/tests/codex-toggle_test.sh diffs the two and fails on drift.
4435
+ local embedded_src=""
4436
+ if [ -z "$directive_src" ]; then
4437
+ embedded_src="$(mktemp -t weave-codex-toggle.XXXXXX)" || return 0
4438
+ cat >"$embedded_src" <<'CODEX_TOGGLE_EOF'
4439
+ #!/usr/bin/env bash
4440
+ # <!-- weave-router managed codex directive -->
4441
+ #
4442
+ # Codex UserPromptSubmit hook for the Weave Router's LOCAL config toggles.
4443
+ # Codex passes a JSON object on stdin carrying the RAW prompt text, before
4444
+ # `$skill` expansion and before any inference.
4445
+ #
4446
+ # Why this exists. The other directives ($fm, $ufm, $rf, $router-session,
4447
+ # a bare $router-models) are router state, and the router answers them itself
4448
+ # with no model turn. These four are not: they rewrite config.toml on this
4449
+ # machine, which a remote HTTP service cannot do. Left as skills they cost two
4450
+ # inference turns each -- one for the model to read the skill and decide to
4451
+ # exec, one to report the tool result.
4452
+ #
4453
+ # The second reason matters more than the cost. $router-off and
4454
+ # $disable-routing are what you reach for when the router is slow, broken, or
4455
+ # out of credits -- and as skills they need a model turn, which is served
4456
+ # THROUGH the router. The off switch depended on the thing it turns off. This
4457
+ # hook runs locally before any network call, so it works when the router does
4458
+ # not.
4459
+ #
4460
+ # Scope: only the four local toggles. Everything the router can answer is
4461
+ # deliberately absent -- a hook that intercepted those would re-open the
4462
+ # duplicate-path problem #1257 closed.
4463
+ #
4464
+ # FAIL OPEN. Every unexpected condition -- no jq, no npx, a malformed payload,
4465
+ # a command that errors -- must let the prompt through untouched. A directive
4466
+ # that silently swallows the user's prompt is far worse than one that does not
4467
+ # fire.
4468
+
4469
+ set -uo pipefail
4470
+
4471
+ # How long the toggle may take before the hook gives up and passes the prompt
4472
+ # through. npx resolves from cache after first use; the budget covers a cold
4473
+ # fetch without letting a dead network hang the turn indefinitely.
4474
+ #
4475
+ # Validated, not trusted. `[ "$waited" -ge "$seconds" ]` does not compare a
4476
+ # bound it cannot parse -- it errors -- so the cap would never fire and the
4477
+ # hook would hang until npx exited on its own. Two ways to get there: a
4478
+ # non-numeric value, and a digit-only value too large for the shell's integer
4479
+ # type ("[: 99999999999999999999: integer expression expected"). The length
4480
+ # bound covers the second; 4 digits is already ~2.7h, far past anything
4481
+ # meaningful for a prompt hook.
4482
+ #
4483
+ # The diagnostic goes to stderr, never stdout: stdout is the hook protocol
4484
+ # channel and any stray byte there corrupts the JSON. Codex discards stderr,
4485
+ # so this costs a user nothing and tells whoever set the variable why it was
4486
+ # ignored.
4487
+ WEAVE_TOGGLE_TIMEOUT_DEFAULT=45
4488
+ # Resolved into a local first: under `set -u`, ${#WEAVE_TOGGLE_TIMEOUT} on an
4489
+ # unset variable aborts the hook outright -- which would swallow every prompt,
4490
+ # the one failure this script must never have.
4491
+ weave_timeout="${WEAVE_TOGGLE_TIMEOUT:-$WEAVE_TOGGLE_TIMEOUT_DEFAULT}"
4492
+ weave_timeout_invalid=""
4493
+ case "$weave_timeout" in
4494
+ ''|*[!0-9]*|0) weave_timeout_invalid=1 ;;
4495
+ *) [ "${#weave_timeout}" -gt 4 ] && weave_timeout_invalid=1 ;;
4496
+ esac
4497
+ if [ -n "$weave_timeout_invalid" ]; then
4498
+ printf 'weave-router: ignoring invalid WEAVE_TOGGLE_TIMEOUT=%s; using %ss\n' \
4499
+ "$weave_timeout" "$WEAVE_TOGGLE_TIMEOUT_DEFAULT" >&2
4500
+ weave_timeout="$WEAVE_TOGGLE_TIMEOUT_DEFAULT"
4501
+ fi
4502
+ WEAVE_TOGGLE_TIMEOUT="$weave_timeout"
4503
+
4504
+ # ---------- responses ----------
4505
+
4506
+ # pass_through hands the prompt to Codex unchanged. Every failure path ends here.
4507
+ pass_through() {
4508
+ printf '{"continue":true}\n'
4509
+ exit 0
4510
+ }
4511
+
4512
+ # block stops the turn before any inference and shows the text to the user.
4513
+ # Codex renders `reason`; nothing reaches the model.
4514
+ #
4515
+ # Setting only `decision` is deliberate: `continue:false` alongside it wins and
4516
+ # renders a bare "Hook stopped" with the reason discarded.
4517
+ block() {
4518
+ local reason="$1" payload
4519
+ payload="$(jq -cn --arg r "$reason" '{decision:"block", reason:$r}' 2>/dev/null)" \
4520
+ || pass_through
4521
+ printf '%s\n' "$payload"
4522
+ exit 0
4523
+ }
4524
+
4525
+ command -v jq >/dev/null 2>&1 || pass_through
4526
+
4527
+ payload="$(cat)" || pass_through
4528
+ [ -n "$payload" ] || pass_through
4529
+
4530
+ prompt="$(jq -r '.prompt // ""' <<<"$payload" 2>/dev/null)" || pass_through
4531
+
4532
+ # Only a directive at the very start of the prompt is ours. Prose that merely
4533
+ # mentions `$router-off` in a sentence is the user's text, not a command.
4534
+ case "$prompt" in
4535
+ '$'*) ;;
4536
+ *) pass_through ;;
4537
+ esac
4538
+
4539
+ verb="${prompt#$}"
4540
+ # These four take no arguments. A prompt with a tail is not one of ours --
4541
+ # pass it through so the skill can explain itself rather than the hook eating
4542
+ # a message it cannot honour.
4543
+ case "$verb" in
4544
+ *[[:space:]]*) pass_through ;;
4545
+ esac
4546
+
4547
+ # ---------- directive table ----------
4548
+ #
4549
+ # Local-config toggles only. router-on/off/status flip this install's
4550
+ # config.toml; disable-routing is `off` plus the reversal hint below.
4551
+ case "$verb" in
4552
+ router-on) toggle="on" ;;
4553
+ router-off) toggle="off" ;;
4554
+ router-status) toggle="status" ;;
4555
+ disable-routing) toggle="off" ;;
4556
+ *) pass_through ;;
4557
+ esac
4558
+
4559
+ command -v npx >/dev/null 2>&1 || pass_through
4560
+
4561
+ # ---------- run ----------
4562
+
4563
+ # WEAVE_TOGGLE_TIMED_OUT is set by run_bounded instead of encoding the timeout
4564
+ # in the exit status. 124 is a status the child can legitimately return, and
4565
+ # reading that as "we timed out" would swallow the toggle's own error output.
4566
+ WEAVE_TOGGLE_TIMED_OUT=0
4567
+
4568
+ # run_bounded runs a command with a wall-clock cap. GNU `timeout` is not on
4569
+ # macOS, so this polls the child rather than depending on coreutils.
4570
+ #
4571
+ # The child runs in its own process group (`set -m` + `kill -- -PID`) because
4572
+ # npx execs node: signalling only the direct child leaves that node process
4573
+ # running after the hook has already passed the prompt through.
4574
+ run_bounded() {
4575
+ local seconds="$1" out="$2"; shift 2
4576
+ WEAVE_TOGGLE_TIMED_OUT=0
4577
+
4578
+ local had_monitor=0
4579
+ case "$-" in *m*) had_monitor=1 ;; esac
4580
+ set -m
4581
+ "$@" >"$out" 2>&1 &
4582
+ local pid=$!
4583
+ [ "$had_monitor" -eq 1 ] || set +m
4584
+
4585
+ local waited=0
4586
+ while kill -0 "$pid" 2>/dev/null; do
4587
+ if [ "$waited" -ge "$seconds" ]; then
4588
+ WEAVE_TOGGLE_TIMED_OUT=1
4589
+ # Negative pid = the whole group. Fall back to the bare pid if the
4590
+ # group is already gone, so a raced exit still gets reaped.
4591
+ kill -TERM -- "-$pid" 2>/dev/null || kill -TERM "$pid" 2>/dev/null
4592
+ sleep 1
4593
+ kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null
4594
+ wait "$pid" 2>/dev/null
4595
+ return 0
4596
+ fi
4597
+ sleep 1
4598
+ waited=$((waited + 1))
4599
+ done
4600
+ wait "$pid"
4601
+ }
4602
+
4603
+ out_file="$(mktemp -t weave-codex-toggle.XXXXXX)" || pass_through
4604
+ # shellcheck disable=SC2064 # expand out_file now; it never changes after this
4605
+ trap "rm -f '$out_file'" EXIT
4606
+
4607
+ # {{SCOPE}} is substituted at install time by the only code that knows whether
4608
+ # this install is user, project, or --dir scoped. It becomes literal argument
4609
+ # text (the installer printf %q-quotes any path), so there is nothing here to
4610
+ # word-split at runtime -- the braces are a template token, not an expansion.
4611
+ # shellcheck disable=SC1083
4612
+ run_bounded "$WEAVE_TOGGLE_TIMEOUT" "$out_file" \
4613
+ npx --package @weave-os/router -y -- weave-router "$toggle" --codex{{SCOPE}}
4614
+ status=$?
4615
+
4616
+ output="$(cat "$out_file" 2>/dev/null || true)"
4617
+ # Strip ANSI colour the installer emits when it thinks it has a terminal;
4618
+ # Codex renders `reason` as plain text.
4619
+ output="$(printf '%s' "$output" | sed -e 's/\x1b\[[0-9;]*m//g')"
4620
+
4621
+ # A failure is reported, not swallowed: passing through here would hand the
4622
+ # model a prompt the user meant as a command, and it would likely try the same
4623
+ # command again. Only a real timeout passes through -- the toggle never got to
4624
+ # finish, so the skill path is still the honest fallback.
4625
+ if [ "$WEAVE_TOGGLE_TIMED_OUT" -eq 1 ]; then
4626
+ pass_through
4627
+ fi
4628
+
4629
+ [ -n "$output" ] || output="weave-router $toggle --codex exited with status $status."
4630
+
4631
+ # Both trailers describe a change that actually happened, so they are gated on
4632
+ # a zero exit. A failed toggle rewrote no config; telling the user it takes
4633
+ # effect next launch would send them to restart Codex for nothing.
4634
+ if [ "$status" -eq 0 ] && [ "$verb" != "router-status" ]; then
4635
+ output="$output"$'\n\n'"Takes effect on your next \`codex\` launch: Codex reads its provider config at startup, so this session keeps routing as it already was."
4636
+ fi
4637
+ if [ "$status" -eq 0 ] && [ "$verb" = "disable-routing" ]; then
4638
+ output="$output"$'\n'"Reverse it with \$router-on."
4639
+ fi
4640
+
4641
+ block "$output"
4642
+ CODEX_TOGGLE_EOF
4643
+ directive_src="$embedded_src"
4644
+ fi
4645
+ if ! grep -Fq '<!-- weave-router managed codex directive -->' "$directive_src"; then
4646
+ warn "Codex directive hook has no ownership marker; skipping it. The \$router-on/off/status toggles still work as skills."
4647
+ [ -n "$embedded_src" ] && rm -f "$embedded_src"
4648
+ return 0
4649
+ fi
4650
+ # A symlink at this path is never ours, whatever it points at and whether or
4651
+ # not the target carries our marker. Writing through one would let a
4652
+ # reinstall overwrite an arbitrary file outside the Codex directory, and a
4653
+ # DANGLING link is invisible to -e, so this test must be -L and must come
4654
+ # first. It skips rather than exits: refuse_if_symlink would abort the whole
4655
+ # installer, and this hook is optional -- the toggle skills still work.
4656
+ if [ -L "$codex_directive_file" ]; then
4657
+ warn "A symlink sits at $codex_directive_file; leaving it untouched and skipping the local-toggle hook. The \$router-on/off/status toggles still work as skills."
4658
+ [ -n "$embedded_src" ] && rm -f "$embedded_src"
4659
+ return 0
4660
+ fi
4661
+ if [ "$scope" = "user" ] && [ -z "$install_dir" ]; then
4662
+ mkdir -p "$(dirname "$codex_directive_file")"
4663
+ fi
4664
+ if [ -e "$codex_directive_file" ] && { [ ! -f "$codex_directive_file" ] || ! grep -Fq '<!-- weave-router managed codex directive -->' "$codex_directive_file"; }; then
4665
+ warn "A user-owned Codex directive helper already exists at $codex_directive_file; leaving it untouched. The \$router-on/off/status toggles still work as skills."
4666
+ [ -n "$embedded_src" ] && rm -f "$embedded_src"
4667
+ return 0
4668
+ fi
4669
+
4670
+ local scope_args=""
4671
+ if [ -n "$install_dir" ]; then
4672
+ scope_args=" --dir $(printf '%q' "$install_dir")"
4673
+ elif [ "$scope" = "project" ]; then
4674
+ scope_args=" --scope project"
4675
+ fi
4676
+ local body
4677
+ body="$(cat "$directive_src")" || { [ -n "$embedded_src" ] && rm -f "$embedded_src"; return 0; }
4678
+ [ -n "$embedded_src" ] && rm -f "$embedded_src"
4679
+ printf '%s\n' "${body//\{\{SCOPE\}\}/$scope_args}" >"$codex_directive_file" || return 0
4680
+ chmod 700 "$codex_directive_file"
4681
+ ok "Codex local-toggle hook installed at $codex_directive_file"
4682
+ }
4683
+
4167
4684
 
4168
4685
  if [ "$target" = "codex" ]; then
4169
4686
  if ! install_codex_status_script; then
4170
4687
  err "Cannot install the Codex status helper safely; refusing to write hooks that could execute unowned code."
4171
4688
  exit 1
4172
4689
  fi
4690
+ # Before write_codex_config, which registers whatever this leaves on disk:
4691
+ # a registration pointing at a script that is not there yet makes Codex run
4692
+ # a missing command on every prompt. It never fails the install -- the
4693
+ # toggles fall back to their skills -- so its outcome is read off the file,
4694
+ # not off an exit status.
4695
+ install_codex_directive_script
4173
4696
  write_codex_config "$codex_config_file" "$base_url" "$api_key" "$user_email" "$user_name"
4174
4697
  ok "Codex config written to $codex_config_file"
4175
- # Only once the registration is gone: a helper deleted while its registration
4176
- # survives makes Codex run a missing command on every prompt.
4177
- remove_codex_directive_helper
4178
4698
  remove_obsolete_codex_prompt_wrappers "$codex_dir/prompts"
4179
4699
  install_codex_prompt_skills
4180
- info "Codex router directives: begin the message with one space, e.g. ' /force-model gpt-5.6-terra'."
4181
4700
 
4182
4701
  # Project scope: ensure the per-teammate config (which holds the router key)
4183
4702
  # is gitignored. The base URL is the same for every teammate, so a
@@ -4226,7 +4745,9 @@ if [ "$target" = "opencode" ]; then
4226
4745
  refuse_if_symlink "$gitignore"
4227
4746
  for entry in \
4228
4747
  "opencode.json" \
4229
- ".weave/"
4748
+ ".weave/" \
4749
+ ".weave-parked.json" \
4750
+ ".opencode/commands/*.weave-router"
4230
4751
  do
4231
4752
  if [ ! -f "$gitignore" ] || ! grep -qxF "$entry" "$gitignore"; then
4232
4753
  printf '%s\n' "$entry" >>"$gitignore"
@@ -4243,11 +4764,9 @@ if [ "$target" = "opencode" ]; then
4243
4764
  #
4244
4765
  # Router on/off/status are not installed — they run npx shell commands
4245
4766
  # specific to the Claude Code settings model and don't apply to opencode.
4246
- if [ "$scope" = "project" ]; then
4767
+ if [ "$scope" = "project" ] || [ -n "$install_dir" ]; then
4247
4768
  opencode_commands_dir="$opencode_dir/.opencode/commands"
4248
4769
  else
4249
- # User scope and --dir installs: use the global commands path that opencode
4250
- # discovers regardless of working directory.
4251
4770
  opencode_commands_dir="${XDG_CONFIG_HOME:-$HOME/.config}/opencode/commands"
4252
4771
  fi
4253
4772
  install_slash_commands "$opencode_commands_dir"
@@ -4265,12 +4784,12 @@ if [ "$target" = "opencode" ]; then
4265
4784
  # can outlive a plugin-less re-install that stripped the provider, which would
4266
4785
  # make these instructions misleading.
4267
4786
  if jq -e '(.provider // {}) | has("weave-claude")' "$opencode_config_file" >/dev/null 2>&1; then
4268
- info "Optional: connect your AI plans so they pay for the matching turns. Run ${C_BOLD}opencode auth login${C_RESET} → ${C_BOLD}Weave Router${C_RESET} for ${C_BOLD}ChatGPT Pro/Plus${C_RESET} (GPT/Codex turns) and/or ${C_BOLD}Weave Router — Claude plan${C_RESET} for ${C_BOLD}Claude Pro/Max${C_RESET} (Claude turns). The router still routes every turn; your Weave key pays for the rest."
4787
+ info "Optional: connect your AI plans so they pay for the matching turns. Run ${C_BOLD}opencode auth login${C_RESET} → ${C_BOLD}Weave Router — Codex plan${C_RESET} for ${C_BOLD}ChatGPT Pro/Plus${C_RESET} (GPT/Codex turns) and/or ${C_BOLD}Weave Router — Claude plan${C_RESET} for ${C_BOLD}Claude Pro/Max${C_RESET} (Claude turns). The router still routes every turn; your Weave key pays for the rest."
4269
4788
  fi
4270
4789
  if [ -n "$install_dir" ]; then
4271
4790
  # --dir installs land outside opencode's discovery roots, so the caller
4272
4791
  # has to point opencode at the file explicitly.
4273
- info "Run opencode with OPENCODE_CONFIG=$opencode_config_file opencode."
4792
+ info "Run opencode with OPENCODE_CONFIG=$opencode_config_file OPENCODE_CONFIG_DIR=$opencode_dir/.opencode opencode."
4274
4793
  fi
4275
4794
  [ "$mode" = "update" ] || print_uninstall_hint
4276
4795
  exit 0
@@ -4333,6 +4852,7 @@ fi
4333
4852
 
4334
4853
  # ---------- write the statusline script ----------
4335
4854
 
4855
+ if [ "$statusline_install" = "true" ]; then
4336
4856
  cat > "$statusline_file" << 'STATUSLINE_EOF'
4337
4857
  #!/usr/bin/env bash
4338
4858
  #
@@ -4617,8 +5137,13 @@ weave_sync_commands() {
4617
5137
  installed_body="$(sed '/^<!-- weave-router managed command: .* -->$/d' "$installed" 2>/dev/null)" || installed_body=""
4618
5138
  if [ "$prev_body" = "$installed_body" ] && [ "$new_body" != "$installed_body" ]; then
4619
5139
  tmp="$installed.tmp.$$"
4620
- if printf '%s\n<!-- weave-router managed command: %s -->' "$new_body" "$name" >"$tmp" 2>/dev/null; then
5140
+ if printf '%s\n' "$new_body" >"$tmp" 2>/dev/null; then
4621
5141
  mv "$tmp" "$installed" 2>/dev/null || rm -f "$tmp"
5142
+ ownership_file="$installed.weave-router"
5143
+ if [ ! -L "$ownership_file" ]; then
5144
+ printf 'weave-router managed command: %s\n%s\n' "$name" "$new_body" \
5145
+ >"$ownership_file" 2>/dev/null || true
5146
+ fi
4622
5147
  else
4623
5148
  rm -f "$tmp"
4624
5149
  fi
@@ -5294,7 +5819,10 @@ else
5294
5819
  fi
5295
5820
  STATUSLINE_EOF
5296
5821
  chmod +x "$statusline_file"
5822
+ printf '%s\n' "$CLAUDE_STATUSLINE_MARKER" >"$statusline_ownership_file"
5823
+ chmod 600 "$statusline_ownership_file"
5297
5824
  ok "Statusline installed at $statusline_file"
5825
+ fi
5298
5826
 
5299
5827
  # ---------- patch settings.json ----------
5300
5828
 
@@ -5314,6 +5842,7 @@ trap '_spin_cleanup; rm -f "$tmp_patch"' EXIT INT TERM HUP
5314
5842
  # replacement key without re-running the whole install.
5315
5843
  write_claude_settings() {
5316
5844
  local block_key="$1"
5845
+ prepare_claude_context_window
5317
5846
 
5318
5847
  # Claude Code splits ANTHROPIC_CUSTOM_HEADERS on newlines, so multiple headers
5319
5848
  # ride in the same env var separated by \n. Append identity headers alongside
@@ -5333,26 +5862,26 @@ write_claude_settings() {
5333
5862
  # Force tool-search deferral to match first-party Claude Code; "auto" can inline
5334
5863
  # every tool schema when the custom endpoint advertises a 200K context window.
5335
5864
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
5336
- jq -n --arg url "$base_url" --arg sl "$statusline_path_for_settings" '{
5865
+ jq -n --arg url "$base_url" --arg sl "$statusline_path_for_settings" --arg statusline_install "$statusline_install" '{
5337
5866
  env: { ANTHROPIC_BASE_URL: $url, ENABLE_TOOL_SEARCH: "true" },
5338
- statusLine: { type: "command", command: $sl },
5339
5867
  attribution: {
5340
5868
  commit: "Co-Authored-By: Weave Router <router@workweave.ai>",
5341
5869
  pr: "🤖 Generated with [Weave Router](https://router.workweave.ai)"
5342
5870
  }
5343
- }' >"$tmp_patch"
5871
+ } + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl }} else {} end)' >"$tmp_patch"
5344
5872
  else
5345
- jq -n --arg url "$base_url" --arg header "$custom_headers" --arg sl "$statusline_path_for_settings" '{
5873
+ jq -n --arg url "$base_url" --arg header "$custom_headers" --arg sl "$statusline_path_for_settings" --arg statusline_install "$statusline_install" '{
5346
5874
  env: { ANTHROPIC_BASE_URL: $url, ANTHROPIC_CUSTOM_HEADERS: $header, ENABLE_TOOL_SEARCH: "true" },
5347
- statusLine: { type: "command", command: $sl },
5348
5875
  attribution: {
5349
5876
  commit: "Co-Authored-By: Weave Router <router@workweave.ai>",
5350
5877
  pr: "🤖 Generated with [Weave Router](https://router.workweave.ai)"
5351
5878
  }
5352
- }' >"$tmp_patch"
5879
+ } + (if $statusline_install == "true" then {statusLine: { type: "command", command: $sl }} else {} end)' >"$tmp_patch"
5353
5880
  fi
5354
5881
 
5355
- # Merge with existing settings. Deep-merge env and replace statusLine.
5882
+ # Merge with existing settings. Deep-merge env and replace statusLine only
5883
+ # when this install owns the statusline slot; otherwise the patch omits it so
5884
+ # the user's existing statusline survives unchanged.
5356
5885
  # We strip router-owned auth from the existing settings BEFORE merging —
5357
5886
  # otherwise switching auth mode (key→dev-mode) would leave stale credentials
5358
5887
  # behind. ANTHROPIC_AUTH_TOKEN/apiKeyHelper are also removed to migrate older
@@ -5396,6 +5925,7 @@ write_claude_settings() {
5396
5925
  chmod 600 "$local_settings_file"
5397
5926
  ok "Router key header written to $local_settings_file"
5398
5927
  fi
5928
+ apply_claude_context_window install "$context_settings_file"
5399
5929
  }
5400
5930
 
5401
5931
  # write_claude_settings rewrites the full router config live, so a parked
@@ -5421,13 +5951,17 @@ if [ "$scope" = "project" ] && [ -z "$install_dir" ] && [ -n "${git_root:-}" ];
5421
5951
  # Same symlink containment as the .claude/ paths above: a hostile repo could
5422
5952
  # commit .gitignore as a symlink so the >> below writes outside the repo.
5423
5953
  refuse_if_symlink "$gitignore"
5424
- # Keep the statusline script and per-teammate local settings out of git. The
5425
- # local settings carry the router key header; each teammate gets their own.
5954
+ # Keep the router statusline script (when installed) and per-teammate local
5955
+ # settings out of git. The local settings carry the router key header; each
5956
+ # teammate gets their own.
5426
5957
  for entry in \
5427
5958
  ".claude/settings.local.json" \
5428
5959
  ".claude/.credentials.json" \
5429
- ".claude/cc-statusline.sh"
5960
+ ".claude/cc-statusline.sh" \
5961
+ ".claude/cc-statusline.sh.weave-router" \
5962
+ ".claude/commands/*.weave-router"
5430
5963
  do
5964
+ [[ "$entry" == .claude/cc-statusline.sh* ]] && [ "$statusline_install" != "true" ] && continue
5431
5965
  if [ ! -f "$gitignore" ] || ! grep -qxF "$entry" "$gitignore"; then
5432
5966
  printf '%s\n' "$entry" >>"$gitignore"
5433
5967
  fi