@weave-os/router 0.2.15 → 0.2.17

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
@@ -12,7 +12,7 @@
12
12
  # opencode.json — since the file is JSON, install/uninstall are structural
13
13
  # (jq) rather than marker-delimited. For pi it merges a `weave` provider into
14
14
  # ~/.pi/agent/models.json, sets it as the default in settings.json, and adds
15
- # the @workweave/router extension (which also adds a parallel subagent
15
+ # the @weave-os/router extension (which also adds a parallel subagent
16
16
  # `dispatch` tool) — all structural (jq) merges.
17
17
  #
18
18
  # Two scopes (apply to all targets):
@@ -32,42 +32,42 @@
32
32
  # <dir>/.pi/ (run: PI_CODING_AGENT_DIR=<dir>/.pi pi) (with --pi)
33
33
  #
34
34
  # Usage:
35
- # npx @workweave/router # interactive picker (Claude Code, Codex, opencode)
36
- # npx @workweave/router --claude # skip the picker, target Claude Code
37
- # npx @workweave/router --codex # skip the picker, target Codex
38
- # npx @workweave/router setup --claude --codex # configure both native clients
39
- # npx @workweave/router login claude # enroll Claude Pro/Max
40
- # npx @workweave/router login codex # enroll ChatGPT Pro/Plus
41
- # npx @workweave/router accounts list # inspect enrolled accounts
42
- # npx @workweave/router status # router + native client status
43
- # npx @workweave/router --opencode # skip the picker, target opencode
44
- # npx @workweave/router --pi # skip the picker, target pi
45
- # npx @workweave/router --pi --lsp go,typescript # also install language servers for pi's lsp tool
35
+ # npx @weave-os/router # interactive picker (Claude Code, Codex, opencode)
36
+ # npx @weave-os/router --claude # skip the picker, target Claude Code
37
+ # npx @weave-os/router --codex # skip the picker, target Codex
38
+ # npx @weave-os/router setup --claude --codex # configure both native clients
39
+ # npx @weave-os/router login claude # enroll Claude Pro/Max
40
+ # npx @weave-os/router login codex # enroll ChatGPT Pro/Plus
41
+ # npx @weave-os/router accounts list # inspect enrolled accounts
42
+ # npx @weave-os/router status # router + native client status
43
+ # npx @weave-os/router --opencode # skip the picker, target opencode
44
+ # npx @weave-os/router --pi # skip the picker, target pi
45
+ # npx @weave-os/router --pi --lsp go,typescript # also install language servers for pi's lsp tool
46
46
  # (go/typescript/python/rust; needs that language's toolchain)
47
- # npx @workweave/router --scope project # commit-with-team install
48
- # npx @workweave/router --dir /tmp/my-sandbox # isolated throwaway install
49
- # npx @workweave/router --local # local router on localhost:8080
50
- # npx @workweave/router --base-url http://localhost:8080 # self-hosted, custom port
51
- # npx @workweave/router --non-interactive # require WEAVE_ROUTER_KEY env var (defaults target to claude)
52
- # npx @workweave/router --quiet # suppress banner, ping check, and trailing tips
53
- # npx @workweave/router --rotate-key # ignore the installed key and prompt for a new one
54
- # npx @workweave/router --uninstall # remove a previous install (delegates to uninstall.sh)
47
+ # npx @weave-os/router --scope project # commit-with-team install
48
+ # npx @weave-os/router --dir /tmp/my-sandbox # isolated throwaway install
49
+ # npx @weave-os/router --local # local router on localhost:8080
50
+ # npx @weave-os/router --base-url http://localhost:8080 # self-hosted, custom port
51
+ # npx @weave-os/router --non-interactive # require WEAVE_ROUTER_KEY env var (defaults target to claude)
52
+ # npx @weave-os/router --quiet # suppress banner, ping check, and trailing tips
53
+ # npx @weave-os/router --rotate-key # ignore the installed key and prompt for a new one
54
+ # npx @weave-os/router --uninstall # remove a previous install (delegates to uninstall.sh)
55
55
  #
56
56
  # Re-running the installer reuses the key already on disk, so you only paste it
57
57
  # once — for every client, not just Claude Code. `update` is the scriptable form
58
58
  # of that: it never prompts, refreshes the managed config + assets in place, and
59
59
  # errors (rather than asking) when no key can be found:
60
- # npx @workweave/router update --claude # refresh the Claude Code install in place
61
- # npx @workweave/router update --codex # same for Codex / opencode / pi
60
+ # npx @weave-os/router update --claude # refresh the Claude Code install in place
61
+ # npx @weave-os/router update --codex # same for Codex / opencode / pi
62
62
  #
63
63
  # Toggle an existing install on/off without losing the router config (so
64
64
  # switching back is instant). These never prompt for a key and require an
65
65
  # explicit client (--claude / --codex / --opencode); they only flip config
66
66
  # that install.sh already wrote:
67
- # npx @workweave/router off --claude # route directly to Anthropic again (Claude Code)
68
- # npx @workweave/router on --codex # route through the Weave Router again (Codex)
69
- # npx @workweave/router status --opencode # report whether opencode is on the router or direct
70
- # npx @workweave/router disable-routing # Codex shortcut: use Codex's normal provider again
67
+ # npx @weave-os/router off --claude # route directly to Anthropic again (Claude Code)
68
+ # npx @weave-os/router on --codex # route through the Weave Router again (Codex)
69
+ # npx @weave-os/router status --opencode # report whether opencode is on the router or direct
70
+ # npx @weave-os/router disable-routing # Codex shortcut: use Codex's normal provider again
71
71
  # Claude Code reads env at launch, so an off/on takes effect on the next
72
72
  # `claude` start; Codex and opencode re-read config every invocation.
73
73
  # Cursor's base URL lives in its own settings UI (no file we own), so there's
@@ -83,13 +83,13 @@
83
83
  # the same lists the router dashboard's settings page renders. The endpoint and
84
84
  # router key both come from the install already on disk, so nothing is prompted
85
85
  # and no key is ever passed on the command line:
86
- # npx @workweave/router models --claude # every model, with its on/off state
87
- # npx @workweave/router models disable gpt-5.6 --claude # take a model out of rotation
88
- # npx @workweave/router models enable gpt-5.6 --claude # put it back
89
- # npx @workweave/router models providers --claude # same, one row per provider
90
- # npx @workweave/router models providers disable openai --claude # drop a whole provider
91
- # npx @workweave/router models prefer claude-opus-5 --claude # set the preferred-model ranking
92
- # npx @workweave/router models list --json --claude # machine-readable, for scripts
86
+ # npx @weave-os/router models --claude # every model, with its on/off state
87
+ # npx @weave-os/router models disable gpt-5.6 --claude # take a model out of rotation
88
+ # npx @weave-os/router models enable gpt-5.6 --claude # put it back
89
+ # npx @weave-os/router models providers --claude # same, one row per provider
90
+ # npx @weave-os/router models providers disable openai --claude # drop a whole provider
91
+ # npx @weave-os/router models prefer claude-opus-5 --claude # set the preferred-model ranking
92
+ # npx @weave-os/router models list --json --claude # machine-readable, for scripts
93
93
  # Editing needs a router that mounts the model-selection API (self-hosted and
94
94
  # local routers do). The Weave-hosted router keeps model selection with the
95
95
  # organization, in the Weave dashboard — there `models` lists and points you at
@@ -103,8 +103,9 @@ set -euo pipefail
103
103
  HOSTED_BASE_URL="https://router.workweave.ai"
104
104
  DEFAULT_BASE_URL="${WEAVE_ROUTER_URL:-$HOSTED_BASE_URL}"
105
105
  # npm package name is supplied by the Node wrapper; direct shell installs keep
106
- # the legacy name for compatibility.
107
- npm_package_name="${WEAVE_ROUTER_NPM_PACKAGE:-@workweave/router}"
106
+ # the current package name; WEAVE_ROUTER_NPM_PACKAGE remains an escape hatch for
107
+ # compatibility with wrappers that explicitly select another package.
108
+ npm_package_name="${WEAVE_ROUTER_NPM_PACKAGE:-@weave-os/router}"
108
109
 
109
110
 
110
111
  scope="user"
@@ -195,7 +196,7 @@ skip() { printf "%s⊙%s %s%s%s\n" "$C_DIM" "$C_RESET" "$C_DIM" "$*" "$C_RESET";
195
196
  # uninstall.sh's flag surface.
196
197
  uninstall_cmd() {
197
198
  # --package + `--` is load-bearing: npm <= 6's bundled npx treats an
198
- # undeclared `-y` as consuming the NEXT token, so `npx -y @workweave/router`
199
+ # undeclared `-y` as consuming the NEXT token, so `npx -y @weave-os/router`
199
200
  # loses the package name and resolves whatever follows as the command.
200
201
  local cmd="npx --package $npm_package_name -y -- weave-router --uninstall"
201
202
  case "$target" in
@@ -264,7 +265,9 @@ _spin_cleanup() {
264
265
  if [ "$tty_out" = "true" ]; then
265
266
  printf '\033[?25h' # show cursor
266
267
  fi
267
- [ -n "$spin_log" ] && rm -f "$spin_log" 2>/dev/null || true
268
+ if [ -n "$spin_log" ]; then
269
+ rm -f "$spin_log" 2>/dev/null || true
270
+ fi
268
271
  # Also restore stty echo in case we died mid-keypaste prompt. macOS
269
272
  # `[ -r /dev/tty ]` returns true even when the underlying device errors
270
273
  # on open (ENXIO "Device not configured") under `curl | sh` and CI, so
@@ -512,12 +515,13 @@ write_codex_config() {
512
515
  printf '%s' "${s//\"/\\\"}"
513
516
  }
514
517
 
515
- local esc_key esc_email esc_name esc_url esc_status
518
+ local esc_key esc_email esc_name esc_url esc_status esc_directive
516
519
  esc_key="$(toml_escape "$block_key")"
517
520
  esc_email="$(toml_escape "$block_email")"
518
521
  esc_name="$(toml_escape "$block_name")"
519
522
  esc_url="$(toml_escape "$block_url")"
520
523
  esc_status="$(toml_escape "$codex_status_file")"
524
+ esc_directive="$(toml_escape "$codex_directive_file")"
521
525
 
522
526
  # Plant whichever identity values we have alongside the router key so the
523
527
  # router can attribute Codex traffic to a person on shared keys. Build the
@@ -570,6 +574,19 @@ type = "command"
570
574
  command = "${esc_status}"
571
575
  TOML
572
576
  )"
577
+ # Only wire the directive hook when its helper actually installed. An empty
578
+ # command would be invalid TOML config, and a Codex that refuses to start is
579
+ # a far worse outcome than directives falling back to their skills.
580
+ if [ -n "$codex_directive_file" ]; then
581
+ hook_block="${hook_block}$(cat <<TOML
582
+
583
+ [[hooks.UserPromptSubmit]]
584
+ [[hooks.UserPromptSubmit.hooks]]
585
+ type = "command"
586
+ command = "${esc_directive}"
587
+ TOML
588
+ )"
589
+ fi
573
590
  fi
574
591
  local block
575
592
  block="$(cat <<TOML
@@ -593,15 +610,34 @@ TOML
593
610
 
594
611
  if [ -f "$config_file" ]; then
595
612
  local tmp; tmp="$(mktemp -t weave-codex.XXXXXX)"
596
- # Strip the managed block (between markers) plus any top-level
597
- # `model_provider =` outside it. We define "top-level" as everything
598
- # before the first `[section]` header. The awk handles both passes in
599
- # one sweep so we never emit a duplicate.
613
+ # Strip the managed block (between markers), any top-level
614
+ # `model_provider =` outside it, and any `[model_providers.weave]` table
615
+ # (with its subtables) outside it. "Top-level" means everything before the
616
+ # first `[section]` header. The awk handles every pass in one sweep so we
617
+ # never emit a duplicate.
618
+ #
619
+ # Dropping the out-of-marker provider table is what keeps a re-install
620
+ # idempotent once Codex has rewritten config.toml itself. Codex round-trips
621
+ # the whole file through a TOML serializer when it persists its own state
622
+ # (hook trust hashes, project trust levels), and comments do not survive
623
+ # that: the markers vanish while `[model_providers.weave]` remains. Keying
624
+ # the strip on the markers alone then left the stale table in place and
625
+ # appended a second one -- TOML rejects a table declared twice, so Codex
626
+ # refused to start with "duplicate key" while the installer reported
627
+ # success.
600
628
  awk -v begin="$WEAVE_CODEX_BEGIN_MARKER" -v end="$WEAVE_CODEX_END_MARKER" '
601
629
  $0 == begin { skip = 1; next }
602
630
  $0 == end { skip = 0; next }
603
631
  skip { next }
604
- /^[[:space:]]*\[/ { in_section = 1 }
632
+ /^[[:space:]]*\[/ {
633
+ in_section = 1
634
+ if ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/) {
635
+ in_weave_provider = 1
636
+ next
637
+ }
638
+ in_weave_provider = 0
639
+ }
640
+ in_weave_provider { next }
605
641
  !in_section && /^[[:space:]]*model_provider[[:space:]]*=/ { next }
606
642
  { print }
607
643
  ' "$config_file" >"$tmp"
@@ -842,7 +878,7 @@ write_opencode_config() {
842
878
  # write_pi_models_config merges a managed `weave` provider into pi's
843
879
  # models.json (anthropic-compatible — the router speaks Anthropic Messages
844
880
  # natively). The header set carries identity plus the main-loop routing knobs
845
- # (quality bias); the @workweave/router extension re-registers the provider
881
+ # (quality bias); the @weave-os/router extension re-registers the provider
846
882
  # per process to flip those knobs for subagents/compaction. apiKey is the
847
883
  # router key as well as a header — pi treats apiKey as required to consider auth
848
884
  # configured, but the router authenticates off X-Weave-Router-Key
@@ -879,7 +915,7 @@ write_pi_models_config() {
879
915
 
880
916
  # Headline models surfaced in pi's /model picker. The router re-routes every
881
917
  # request regardless, so this list is UX; keep it Anthropic-shaped and in
882
- # sync with @workweave/router's WEAVE_MODELS constant.
918
+ # sync with @weave-os/router's WEAVE_MODELS constant.
883
919
  #
884
920
  # baseUrl is the router ROOT (no /v1): pi's anthropic-messages provider uses
885
921
  # @anthropic-ai/sdk, which appends /v1/messages itself. Unlike the codex block
@@ -903,6 +939,7 @@ write_pi_models_config() {
903
939
  { id: "claude-opus-4-7", name: "Claude Opus 4.7 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 64000 },
904
940
  { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1000000, maxTokens: 64000 },
905
941
  { id: "claude-haiku-4-5", name: "Claude Haiku 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 200000, maxTokens: 32000 },
942
+ { id: "gpt-6-astra", name: "GPT-6 Astra (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
906
943
  { id: "gpt-5.6-sol", name: "GPT-5.6 Sol (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 1050000, maxTokens: 128000 },
907
944
  { id: "grok-4.5", name: "Grok 4.5 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 },
908
945
  { id: "grok-4.6", name: "Grok 4.6 (via Weave Router)", reasoning: true, input: ["text","image"], contextWindow: 500000, maxTokens: 131072 }
@@ -1049,7 +1086,7 @@ resolve_user_name() {
1049
1086
  # canonical uninstall logic lives in a sibling file, and we want both
1050
1087
  # direct invocations (`./install.sh --uninstall`) and curl-piped ones
1051
1088
  # (`curl ... | sh -s -- --uninstall`) to behave the same as
1052
- # `npx @workweave/router --uninstall` (which bin.js routes to uninstall.sh on
1089
+ # `npx @weave-os/router --uninstall` (which bin.js routes to uninstall.sh on
1053
1090
  # its own).
1054
1091
  #
1055
1092
  # Scan every arg, not just $1, so flag order doesn't matter; build a clean
@@ -1355,6 +1392,8 @@ if [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interacti
1355
1392
  # Per-target paths so the prompt text matches what actually gets written.
1356
1393
  case "$target" in
1357
1394
  codex)
1395
+ # This path is display text, not an expansion target.
1396
+ # shellcheck disable=SC2088
1358
1397
  scope_user_path="~/.codex/"
1359
1398
  scope_project_path="<repo>/.codex/"
1360
1399
  scope_cli_label="codex"
@@ -1367,17 +1406,23 @@ if [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interacti
1367
1406
  if [ -n "${XDG_CONFIG_HOME:-}" ]; then
1368
1407
  scope_user_path="$XDG_CONFIG_HOME/opencode/"
1369
1408
  else
1409
+ # This path is display text, not an expansion target.
1410
+ # shellcheck disable=SC2088
1370
1411
  scope_user_path="~/.config/opencode/"
1371
1412
  fi
1372
1413
  scope_project_path="<repo>/opencode.json"
1373
1414
  scope_cli_label="opencode"
1374
1415
  ;;
1375
1416
  pi)
1417
+ # This path is display text, not an expansion target.
1418
+ # shellcheck disable=SC2088
1376
1419
  scope_user_path="~/.pi/agent/"
1377
1420
  scope_project_path="<repo>/.pi/"
1378
1421
  scope_cli_label="pi"
1379
1422
  ;;
1380
1423
  *)
1424
+ # This path is display text, not an expansion target.
1425
+ # shellcheck disable=SC2088
1381
1426
  scope_user_path="~/.claude/"
1382
1427
  scope_project_path="<repo>/.claude/"
1383
1428
  scope_cli_label="claude"
@@ -1403,6 +1448,8 @@ if [ -z "$install_dir" ] && [ "$scope_explicit" = "false" ] && [ "$non_interacti
1403
1448
  read -r project_dir_choice </dev/tty || project_dir_choice=""
1404
1449
  project_dir="${project_dir_choice:-$default_project_dir}"
1405
1450
  # Expand a leading ~ since `read` doesn't.
1451
+ # The pattern intentionally matches a literal tilde.
1452
+ # shellcheck disable=SC2088
1406
1453
  case "$project_dir" in
1407
1454
  "~") project_dir="$HOME" ;;
1408
1455
  "~/"*) project_dir="$HOME/${project_dir#~/}" ;;
@@ -1475,7 +1522,9 @@ case "$target" in
1475
1522
  esac
1476
1523
  fi
1477
1524
 
1478
- script_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
1525
+ if ! script_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd)"; then
1526
+ script_dir=""
1527
+ fi
1479
1528
 
1480
1529
  # ---------- directive registry (embedded) ----------
1481
1530
  #
@@ -1493,7 +1542,7 @@ router-feedback|rf|prompt|yes|yes|yes|no|manual|command,skill
1493
1542
  router-off||local-toggle|yes|yes|no|no|manual|command,skill
1494
1543
  router-on||local-toggle|yes|yes|no|no|manual|command,skill
1495
1544
  router-status||local-toggle|yes|yes|no|no|manual|command,skill
1496
- router-session||prompt|yes|no|no|no|manual|command
1545
+ router-session||prompt|yes|yes|no|no|manual|command,skill
1497
1546
  router-models|models|local-toggle|yes|yes|no|no|manual|command,skill
1498
1547
  disable-routing||local-toggle|no|yes|no|no|manual|skill
1499
1548
  beta||prompt|yes|no|no|yes|manual|command
@@ -1605,7 +1654,9 @@ else
1605
1654
  # preserved for --scope project passed on the command line).
1606
1655
  if [ -n "${project_dir:-}" ]; then
1607
1656
  settings_base="$project_dir"
1608
- git_root="$(cd "$project_dir" && git rev-parse --show-toplevel 2>/dev/null || true)"
1657
+ if ! git_root="$(cd "$project_dir" && git rev-parse --show-toplevel 2>/dev/null)"; then
1658
+ git_root=""
1659
+ fi
1609
1660
  else
1610
1661
  if ! git_root="$(git rev-parse --show-toplevel 2>/dev/null)"; then
1611
1662
  err "--scope project must be run inside a git repo, or pass --dir <path>. cd into your project first, or use --dir."
@@ -1664,8 +1715,10 @@ elif [ "$target" = "codex" ]; then
1664
1715
  codex_config_file="$codex_dir/config.toml"
1665
1716
  if [ "$scope" = "user" ] && [ -z "$install_dir" ]; then
1666
1717
  codex_status_file="$settings_base/.weave/codex-status.sh"
1718
+ codex_directive_file="$settings_base/.weave/codex-directive.sh"
1667
1719
  else
1668
1720
  codex_status_file="$codex_dir/weave-status.sh"
1721
+ codex_directive_file="$codex_dir/weave-directive.sh"
1669
1722
  fi
1670
1723
  codex_status_disabled_marker="$(dirname "$codex_status_file")/.weave-router-disabled"
1671
1724
 
@@ -1767,6 +1820,17 @@ json_get() {
1767
1820
  jq -r "${2} // empty" "$1" 2>/dev/null || true
1768
1821
  }
1769
1822
 
1823
+ # strip_trailing_slashes removes every trailing slash from a URL while keeping
1824
+ # comparisons between config files stable when a value was written with more
1825
+ # than one separator.
1826
+ strip_trailing_slashes() {
1827
+ local value="$1"
1828
+ while [ "${value%/}" != "$value" ]; do
1829
+ value="${value%/}"
1830
+ done
1831
+ printf '%s' "$value"
1832
+ }
1833
+
1770
1834
  # read_claude_key prints the router key already installed in the given settings
1771
1835
  # file, or nothing when the file is absent / carries no key header. Claude Code
1772
1836
  # packs several headers into one newline-delimited ANTHROPIC_CUSTOM_HEADERS
@@ -1819,10 +1883,19 @@ key_source_is_own() {
1819
1883
  read_codex_key() {
1820
1884
  local f="$1"
1821
1885
  key_source_is_own "$f" || return 0
1822
- awk -v begin="$WEAVE_CODEX_BEGIN_MARKER" -v end="$WEAVE_CODEX_END_MARKER" '
1823
- $0 == begin { inblk = 1; next }
1824
- $0 == end { inblk = 0; next }
1825
- inblk && match($0, /"X-Weave-Router-Key"[[:space:]]*=[[:space:]]*"[^"]*"/) {
1886
+ # Scan the [model_providers.weave] table and its subtables rather than the
1887
+ # managed markers, and accept the header name quoted or bare. Our own writer
1888
+ # emits one inline `http_headers = { "X-Weave-Router-Key" = "..." }`; Codex's
1889
+ # serializer re-emits the same value as a bare key in a
1890
+ # [model_providers.weave.http_headers] subtable. Matching only the quoted
1891
+ # in-marker spelling missed the key on any config Codex had rewritten, and a
1892
+ # re-install then minted a second router key instead of reusing this one.
1893
+ awk '
1894
+ /^[[:space:]]*\[/ {
1895
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/)
1896
+ next
1897
+ }
1898
+ in_provider && match($0, /"?X-Weave-Router-Key"?[[:space:]]*=[[:space:]]*"[^"]*"/) {
1826
1899
  hdr = substr($0, RSTART, RLENGTH)
1827
1900
  sub(/^.*=[[:space:]]*"/, "", hdr)
1828
1901
  sub(/"$/, "", hdr)
@@ -1842,7 +1915,7 @@ read_opencode_key() {
1842
1915
  }
1843
1916
 
1844
1917
  # read_pi_key prints the router key this pi install already has. The dedicated
1845
- # key file comes first — it is what the @workweave/router extension itself reads
1918
+ # key file comes first — it is what the @weave-os/router extension itself reads
1846
1919
  # at runtime — and models.json is the fallback for an install whose key file was
1847
1920
  # removed by hand.
1848
1921
  read_pi_key() {
@@ -1937,6 +2010,41 @@ resolve_installed_base_url() {
1937
2010
  printf ''
1938
2011
  }
1939
2012
 
2013
+ # resolve_installed_base_source prints the file that supplied the expected
2014
+ # Claude Code endpoint, or nothing when no file matches. Keeping the source
2015
+ # alongside the endpoint lets update apply the same provenance check as models
2016
+ # before it sends the installed key to that endpoint.
2017
+ resolve_installed_base_source() {
2018
+ local expected="$1" normalized_expected candidate found normalized_found
2019
+ normalized_expected="$(strip_trailing_slashes "$expected")"
2020
+ while IFS= read -r candidate; do
2021
+ [ -n "$candidate" ] || continue
2022
+ found="$(json_get "$candidate" '.env.ANTHROPIC_BASE_URL')"
2023
+ normalized_found="$(strip_trailing_slashes "$found")"
2024
+ if [ "$normalized_found" = "$normalized_expected" ]; then
2025
+ printf '%s' "$candidate"
2026
+ return 0
2027
+ fi
2028
+ done <<<"$(models_base_file_order)"
2029
+ printf ''
2030
+ }
2031
+
2032
+ # resolve_installed_key_source prints the file that supplied the installed
2033
+ # Claude Code key, or nothing when the key came from the environment or is
2034
+ # absent. The update trust gate uses this to distinguish the normal project
2035
+ # split from a repo-planted endpoint.
2036
+ resolve_installed_key_source() {
2037
+ local candidate
2038
+ while IFS= read -r candidate; do
2039
+ [ -n "$candidate" ] || continue
2040
+ if [ -n "$(read_claude_key "$candidate")" ]; then
2041
+ printf '%s' "$candidate"
2042
+ return 0
2043
+ fi
2044
+ done <<<"$(models_key_file_order)"
2045
+ printf ''
2046
+ }
2047
+
1940
2048
  # resolve_installed_endpoint prints the router endpoint this install already
1941
2049
  # points at, for whichever client is being installed, or nothing. `update` uses
1942
2050
  # it so a refresh never silently retargets a self-hosted install at the hosted
@@ -1955,11 +2063,19 @@ resolve_installed_endpoint() {
1955
2063
  return 0
1956
2064
  ;;
1957
2065
  codex)
2066
+ # Read base_url from the [model_providers.weave] table wherever it sits,
2067
+ # not only from between the managed markers. Codex drops our comment
2068
+ # markers when it rewrites config.toml (see write_codex_config) while
2069
+ # keeping the table, and a marker-scoped read then reported a live
2070
+ # install as absent -- `login codex` and `status` claimed Codex was not
2071
+ # configured until the user re-installed to restore the markers.
1958
2072
  if key_source_is_own "$codex_config_file"; then
1959
- found="$(awk -v begin="$WEAVE_CODEX_BEGIN_MARKER" -v end="$WEAVE_CODEX_END_MARKER" '
1960
- $0 == begin { inblk = 1; next }
1961
- $0 == end { inblk = 0; next }
1962
- inblk && match($0, /^[[:space:]]*base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
2073
+ found="$(awk '
2074
+ /^[[:space:]]*\[/ {
2075
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*\][[:space:]]*(#.*)?$/)
2076
+ next
2077
+ }
2078
+ in_provider && match($0, /^[[:space:]]*base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
1963
2079
  line = substr($0, RSTART, RLENGTH)
1964
2080
  sub(/^.*=[[:space:]]*"/, "", line)
1965
2081
  sub(/"$/, "", line)
@@ -1998,20 +2114,25 @@ resolve_installed_endpoint() {
1998
2114
  # hosted default, or an explicit --base-url — rather than whatever the checkout
1999
2115
  # happened to contain.
2000
2116
  models_endpoint_is_trusted() {
2001
- local url="$1" base_src="$2" key_src="$3"
2117
+ local url="$1" base_src="$2" key_src="$3" normalized_url normalized_marked_url
2118
+ normalized_url="$(strip_trailing_slashes "$url")"
2002
2119
  [ "$base_url_explicit" = "true" ] && return 0
2003
- [ "$url" = "$HOSTED_BASE_URL" ] && return 0
2120
+ [ "$normalized_url" = "$(strip_trailing_slashes "$HOSTED_BASE_URL")" ] && return 0
2004
2121
  [ -n "$base_src" ] && [ "$base_src" = "$key_src" ] && return 0
2005
2122
  # Project-scoped self-hosted installs intentionally split the endpoint and
2006
2123
  # key. The installer writes a gitignored marker beside the key; require that
2007
2124
  # marker to match before trusting the split. A tracked/symlinked local file is
2008
2125
  # not a teammate's private configuration and cannot vouch for an endpoint.
2009
- if [ "$key_src" = "$local_settings_file" ] && [ ! -L "$key_src" ]; then
2126
+ # The marker vouches for the endpoint independently of whether this run uses
2127
+ # the key from disk or a replacement supplied through WEAVE_ROUTER_KEY.
2128
+ if [ "$target" = "claude" ] && [ -n "$local_settings_file" ] \
2129
+ && [ ! -L "$local_settings_file" ]; then
2010
2130
  local marked_url
2011
- marked_url="$(json_get "$key_src" '.env.WEAVE_ROUTER_BASE_URL')"
2012
- if [ "${marked_url%/}" = "${url%/}" ]; then
2131
+ marked_url="$(json_get "$local_settings_file" '.env.WEAVE_ROUTER_BASE_URL')"
2132
+ normalized_marked_url="$(strip_trailing_slashes "$marked_url")"
2133
+ if [ "$normalized_marked_url" = "$normalized_url" ]; then
2013
2134
  command -v git >/dev/null 2>&1 || return 1
2014
- git -C "$(dirname "$key_src")" ls-files --error-unmatch -- "$key_src" >/dev/null 2>&1 && return 1
2135
+ git -C "$(dirname "$local_settings_file")" ls-files --error-unmatch -- "$local_settings_file" >/dev/null 2>&1 && return 1
2015
2136
  return 0
2016
2137
  fi
2017
2138
  fi
@@ -2751,7 +2872,10 @@ run_login_claude() {
2751
2872
  authorize_endpoint="${WEAVE_ANTHROPIC_OAUTH_AUTHORIZE:-https://claude.ai/oauth/authorize}"
2752
2873
  authorize_url="$authorize_endpoint?code=true&client_id=9d1c250a-e61b-44d9-88ed-5944d1962f5e&response_type=code&redirect_uri=$(jq -nr '"https://console.anthropic.com/oauth/code/callback"|@uri')&scope=$(jq -nr '"org:create_api_key user:profile user:inference"|@uri')&code_challenge=$challenge&code_challenge_method=S256&state=$expected_state"
2753
2874
  open_oauth_url "$authorize_url"
2754
- [ "$non_interactive" != "true" ] && [ -r /dev/tty ] || { err "Claude login requires an interactive terminal to paste the authorization code."; exit 1; }
2875
+ if [ "$non_interactive" = "true" ] || [ ! -r /dev/tty ]; then
2876
+ err "Claude login requires an interactive terminal to paste the authorization code."
2877
+ exit 1
2878
+ fi
2755
2879
  printf 'Paste the Claude authorization code: ' >/dev/tty
2756
2880
  read -r pasted_code </dev/tty
2757
2881
  auth_code="${pasted_code%%#*}"
@@ -2780,7 +2904,10 @@ run_login_codex() {
2780
2904
  case "$interval" in *[!0-9]*|"") interval=5 ;; esac
2781
2905
  [ "$interval" -ge 1 ] || interval=1
2782
2906
  [ "$interval" -le 30 ] || interval=5
2783
- [ -n "$device_auth_id" ] && [ -n "$user_code" ] || { err "Codex device authorization returned an invalid response."; exit 1; }
2907
+ if [ -z "$device_auth_id" ] || [ -z "$user_code" ]; then
2908
+ err "Codex device authorization returned an invalid response."
2909
+ exit 1
2910
+ fi
2784
2911
  open_oauth_url "$issuer/codex/device"
2785
2912
  printf '%s\n' "Enter code: $user_code"
2786
2913
  attempts=0
@@ -2792,13 +2919,19 @@ run_login_codex() {
2792
2919
  done
2793
2920
  authorization_code="$(printf '%s' "$authorization_response" | jq -r '.authorization_code // empty')"
2794
2921
  verifier="$(printf '%s' "$authorization_response" | jq -r '.code_verifier // empty')"
2795
- [ -n "$authorization_code" ] && [ -n "$verifier" ] || { err "Codex authorization returned an invalid response."; exit 1; }
2922
+ if [ -z "$authorization_code" ] || [ -z "$verifier" ]; then
2923
+ err "Codex authorization returned an invalid response."
2924
+ exit 1
2925
+ fi
2796
2926
  token_form="grant_type=authorization_code&code=$(jq -nr --arg value "$authorization_code" '$value|@uri')&redirect_uri=$(jq -nr --arg value "$issuer/deviceauth/callback" '$value|@uri')&client_id=app_EMoamEEZ73f0CkXaXp7hrann&code_verifier=$(jq -nr --arg value "$verifier" '$value|@uri')"
2797
2927
  token_response="$(oauth_post_form "$issuer/oauth/token" "$token_form")" \
2798
2928
  || { err "Codex token exchange failed."; exit 1; }
2799
2929
  refresh_token="$(printf '%s' "$token_response" | jq -r '.refresh_token // empty')"
2800
2930
  account_id="$(jwt_account_id "$(printf '%s' "$token_response" | jq -r '.id_token // .access_token // empty')")"
2801
- [ -n "$refresh_token" ] && [ -n "$account_id" ] || { err "Codex token exchange omitted account identity or refresh credentials."; exit 1; }
2931
+ if [ -z "$refresh_token" ] || [ -z "$account_id" ]; then
2932
+ err "Codex token exchange omitted account identity or refresh credentials."
2933
+ exit 1
2934
+ fi
2802
2935
  body="$(jq -nc --arg provider codex --arg account "$account_id" --arg token "$refresh_token" '{provider:$provider,external_account_id:$account,refresh_token:$token}')"
2803
2936
  models_api POST "/v1/subscriptions/accounts" "$body" || models_fail "enrolling Codex subscription"
2804
2937
  ok "Codex subscription enrolled."
@@ -2866,6 +2999,12 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
2866
2999
  # branches below so `set -u` holds on every path.
2867
3000
  models_base_source=""
2868
3001
  models_key_source=""
3002
+ # The codex fallback below and run_router_status both resolve a Codex install
3003
+ # even on a run whose target is Claude, and the per-target setup only defines
3004
+ # codex_config_file when the target IS codex. Default it here or `set -u`
3005
+ # aborts the whole command: `status` with a Codex-only install died on
3006
+ # "codex_config_file: unbound variable" instead of reporting the install.
3007
+ codex_config_file="${codex_config_file:-$settings_base/.codex/config.toml}"
2869
3008
  # Editing model selection needs the endpoint and key of one specific install,
2870
3009
  # never the hosted defaults: a self-hosted user pointing at their own router
2871
3010
  # would otherwise silently edit the hosted one's installation.
@@ -2880,21 +3019,13 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
2880
3019
  exit 1
2881
3020
  fi
2882
3021
  base_url="$models_base"
2883
- # resolve_installed_endpoint ran in a command substitution, so any global it
2884
- # set died with that subshell. Recover the source by walking the same
2885
- # precedence to find which file holds the endpoint we just adopted. Only
2886
- # Claude Code spreads its endpoint across several files; every other client
2887
- # keeps endpoint and key in one managed config, which is self-consistent by
2888
- # construction (see models_endpoint_is_trusted's same-file rule).
3022
+ # resolve_installed_endpoint ran in a command substitution, so recover the
3023
+ # source by walking the same precedence to find which file holds the
3024
+ # endpoint we just adopted. Only Claude Code spreads its endpoint across
3025
+ # several files; every other client keeps endpoint and key in one managed
3026
+ # config, which is self-consistent by construction.
2889
3027
  if [ "$target" = "claude" ]; then
2890
- while IFS= read -r models_src_candidate; do
2891
- [ -n "$models_src_candidate" ] || continue
2892
- models_src_url="$(json_get "$models_src_candidate" '.env.ANTHROPIC_BASE_URL')"
2893
- if [ "${models_src_url%/}" = "$models_base" ]; then
2894
- models_base_source="$models_src_candidate"
2895
- break
2896
- fi
2897
- done <<<"$(models_base_file_order)"
3028
+ models_base_source="$(resolve_installed_base_source "$models_base")"
2898
3029
  else
2899
3030
  models_base_source="$(models_config_file_for_target)"
2900
3031
  fi
@@ -2909,13 +3040,7 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
2909
3040
  # came from by re-reading them in read_installed_key's own precedence.
2910
3041
  models_key_source=""
2911
3042
  if [ "$target" = "claude" ]; then
2912
- while IFS= read -r models_src_candidate; do
2913
- [ -n "$models_src_candidate" ] || continue
2914
- if [ -n "$(read_claude_key "$models_src_candidate")" ]; then
2915
- models_key_source="$models_src_candidate"
2916
- break
2917
- fi
2918
- done <<<"$(models_key_file_order)"
3043
+ models_key_source="$(resolve_installed_key_source)"
2919
3044
  else
2920
3045
  models_key_source="$(models_config_file_for_target)"
2921
3046
  fi
@@ -2927,9 +3052,9 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
2927
3052
  # Never send a key to an endpoint the checkout supplied. See
2928
3053
  # models_endpoint_is_trusted: a hostile repo can commit a settings.json naming
2929
3054
  # its own router, and pairing that with the teammate key from the gitignored
2930
- # settings.local.json would hand the key to whoever wrote the repo.
2931
- if [ "$models_key_source" != "env:WEAVE_ROUTER_KEY" ] \
2932
- && ! models_endpoint_is_trusted "$base_url" "$models_base_source" "$models_key_source"; then
3055
+ # settings.local.json or WEAVE_ROUTER_KEY would hand the key to whoever wrote
3056
+ # the repo.
3057
+ if ! models_endpoint_is_trusted "$base_url" "$models_base_source" "$models_key_source"; then
2933
3058
  err "Refusing to send this installation's router key to $base_url."
2934
3059
  printf " %sThat endpoint comes from %s, which git tracks — a checked-out repo can set it —%s\n" \
2935
3060
  "$C_DIM" "${models_base_source##*/}" "$C_RESET" >&2
@@ -2971,10 +3096,15 @@ fi
2971
3096
  # `off` parks the router URL and points Claude Code at Anthropic, so the parked
2972
3097
  # sidecar is the authority while toggled off — reading the live file there would
2973
3098
  # pin the install to api.anthropic.com.
3099
+ installed_base=""
3100
+ installed_base_source=""
2974
3101
  if [ "$mode" = "update" ] && [ "$base_url_explicit" != "true" ]; then
2975
3102
  installed_base="$(resolve_installed_endpoint)"
2976
3103
  if [ -n "$installed_base" ]; then
2977
3104
  base_url="${installed_base%/}"
3105
+ if [ "$target" = "claude" ]; then
3106
+ installed_base_source="$(resolve_installed_base_source "$base_url")"
3107
+ fi
2978
3108
  fi
2979
3109
  fi
2980
3110
 
@@ -3044,6 +3174,31 @@ else
3044
3174
  prompt_for_key
3045
3175
  fi
3046
3176
 
3177
+ # A project-scoped Claude install intentionally reads its endpoint from the
3178
+ # tracked settings.json and its key from the ignored settings.local.json. An
3179
+ # update must not carry a newly changed tracked endpoint into the validation or
3180
+ # config write unless the user has independently vouched for it. The same gate
3181
+ # also protects cron/CI runs that provide WEAVE_ROUTER_KEY instead of reading
3182
+ # the installed key from disk.
3183
+ update_key_source=""
3184
+ if [ "$mode" = "update" ] && [ "$target" = "claude" ]; then
3185
+ if [ -n "${WEAVE_ROUTER_KEY:-}" ]; then
3186
+ update_key_source="env:WEAVE_ROUTER_KEY"
3187
+ else
3188
+ update_key_source="$(resolve_installed_key_source)"
3189
+ fi
3190
+ fi
3191
+ if [ "$mode" = "update" ] && [ "$target" = "claude" ] \
3192
+ && [ "$base_url_explicit" != "true" ] && [ -n "$installed_base" ] \
3193
+ && ! models_endpoint_is_trusted "$base_url" "$installed_base_source" "$update_key_source"; then
3194
+ err "Refusing to use the installed router endpoint $base_url."
3195
+ printf " %sThat endpoint comes from a git-tracked project file and has not been independently approved.%s\n" \
3196
+ "$C_DIM" "$C_RESET" >&2
3197
+ printf " %sPass --base-url <url> to confirm it, or re-run the installer against the endpoint you want.%s\n" \
3198
+ "$C_DIM" "$C_RESET" >&2
3199
+ exit 1
3200
+ fi
3201
+
3047
3202
  # ---------- identity (user email + name) ----------
3048
3203
  #
3049
3204
  # The router parses X-Weave-User-Email and X-Weave-User-Name on every protocol
@@ -3232,7 +3387,9 @@ remove_obsolete_codex_prompt_wrappers() {
3232
3387
  while IFS= read -r cmd; do
3233
3388
  src="$commands_src_dir/$cmd.md"
3234
3389
  dst="$dst_dir/$cmd.md"
3235
- [ -f "$src" ] && [ -f "$dst" ] || continue
3390
+ if [ ! -f "$src" ] || [ ! -f "$dst" ]; then
3391
+ continue
3392
+ fi
3236
3393
  [ -L "$dst" ] && continue
3237
3394
  if [ "$scope" = "project" ] || [ -n "$install_dir" ]; then
3238
3395
  refuse_if_symlink "$dst"
@@ -3531,11 +3688,6 @@ state_root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/codex"
3531
3688
  helper_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
3532
3689
  disabled_marker="$helper_dir/.weave-router-disabled"
3533
3690
  router_badge_sentinel=$'⁣⁠⁣⁠'
3534
- # Must stay verbatim in sync with install.sh / uninstall.sh: the endpoint read
3535
- # below is scoped to this block so a key-shaped string elsewhere in the user's
3536
- # config.toml is never adopted.
3537
- codex_begin_marker="# >>> weave-router managed (do not edit between markers) >>>"
3538
- codex_end_marker="# <<< weave-router managed <<<"
3539
3691
 
3540
3692
  emit_title() {
3541
3693
  local title="$1"
@@ -3595,10 +3747,18 @@ cost_file_for() {
3595
3747
  # Resolved from the helper's own location first so a project-scope install never
3596
3748
  # reads (or leaks) the user-scope key: the project helper lives in the same
3597
3749
  # .codex directory as its config, while the user-scope helper sits in ~/.weave
3598
- # and reads ~/.codex. Values are scoped to the managed block so a key-shaped
3599
- # string the user wrote elsewhere in the file is never adopted. awk, not a TOML
3600
- # parser, because the Codex target deliberately does not require jq for config
3601
- # reads.
3750
+ # and reads ~/.codex. Values are scoped to the [model_providers.weave] table so
3751
+ # a key-shaped string the user wrote elsewhere in the file is never adopted. awk,
3752
+ # not a TOML parser, because the Codex target deliberately does not require jq
3753
+ # for config reads.
3754
+ #
3755
+ # Scoped to the table rather than the managed comment markers, and matching the
3756
+ # header name quoted or bare, because Codex rewrites config.toml through a TOML
3757
+ # serializer whenever it persists its own state: comments do not survive, so the
3758
+ # markers vanish while the table remains, and the inline http_headers come back
3759
+ # as a subtable with the header name unquoted. A marker-scoped, quoted-only read
3760
+ # resolved nothing on any config Codex had touched, which silently dropped the
3761
+ # savings figure from the title with no error anywhere.
3602
3762
  read_codex_endpoint() {
3603
3763
  local config=""
3604
3764
  # Project/custom installs name the helper weave-status.sh and keep it next
@@ -3611,19 +3771,45 @@ read_codex_endpoint() {
3611
3771
  config="$HOME/.codex/config.toml"
3612
3772
  fi
3613
3773
  [ -n "$config" ] || return 0
3614
- awk -v begin="$codex_begin_marker" -v end="$codex_end_marker" '
3615
- $0 == begin { inblk = 1; next }
3616
- $0 == end { inblk = 0; next }
3617
- !inblk { next }
3774
+ awk '
3775
+ # Cut a TOML comment, honouring quoted strings so a # inside a value stays.
3776
+ # A full-line comment reduces to empty and matches nothing below, so this
3777
+ # replaces a separate skip rule -- and unlike one, it also catches a comment
3778
+ # trailing another assignment, which the unanchored matches would otherwise
3779
+ # read as live config on any line preceding the real value.
3780
+ function weave_strip_comment(line, i, c, out, indq, insq, esc) {
3781
+ out = ""
3782
+ indq = 0
3783
+ insq = 0
3784
+ esc = 0
3785
+ for (i = 1; i <= length(line); i++) {
3786
+ c = substr(line, i, 1)
3787
+ if (esc) { out = out c; esc = 0; continue }
3788
+ # Only basic strings have escapes; a backslash in a literal string is
3789
+ # data, so consuming the next character there would mis-track the quote.
3790
+ if (indq && c == "\\") { out = out c; esc = 1; continue }
3791
+ if (!insq && c == "\"") { indq = !indq; out = out c; continue }
3792
+ if (!indq && c == "'"'"'") { insq = !insq; out = out c; continue }
3793
+ if (c == "#" && !indq && !insq) break
3794
+ out = out c
3795
+ }
3796
+ return out
3797
+ }
3798
+ { $0 = weave_strip_comment($0) }
3799
+ /^[[:space:]]*\[/ {
3800
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/)
3801
+ next
3802
+ }
3803
+ !in_provider { next }
3618
3804
  match($0, /base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
3619
3805
  v = substr($0, RSTART, RLENGTH)
3620
3806
  sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
3621
- url = v
3807
+ if (url == "") url = v
3622
3808
  }
3623
- match($0, /"X-Weave-Router-Key"[[:space:]]*=[[:space:]]*"[^"]*"/) {
3809
+ match($0, /"?X-Weave-Router-Key"?[[:space:]]*=[[:space:]]*"[^"]*"/) {
3624
3810
  v = substr($0, RSTART, RLENGTH)
3625
3811
  sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
3626
- key = v
3812
+ if (key == "") key = v
3627
3813
  }
3628
3814
  END { if (url != "" && key != "") printf "%s\n%s\n", url, key }
3629
3815
  ' "$config" 2>/dev/null || true
@@ -3821,11 +4007,294 @@ CODEX_STATUS_EOF
3821
4007
  ok "Codex status integration installed at $codex_status_file"
3822
4008
  }
3823
4009
 
4010
+ # install_codex_directive_script installs the UserPromptSubmit hook that answers
4011
+ # Weave directives before any inference. Same ownership rules as the status
4012
+ # helper: a file we do not own is never overwritten, and refusing to install is
4013
+ # preferable to wiring a hook at a path holding someone else's code.
4014
+ #
4015
+ # The heredoc fallback exists because install.sh is also served standalone
4016
+ # (`curl | sh`, and the npm bin runs it directly), where no sibling asset is
4017
+ # available to copy. install/tests/codex-status_test.sh asserts the two copies
4018
+ # never drift.
4019
+ install_codex_directive_script() {
4020
+ local candidate directive_src=""
4021
+ for candidate in \
4022
+ "$script_dir/codex-directive.sh" \
4023
+ "$script_dir/../codex-directive.sh"
4024
+ do
4025
+ if [ -f "$candidate" ]; then
4026
+ directive_src="$candidate"
4027
+ break
4028
+ fi
4029
+ done
4030
+ if [ "$scope" = "user" ] && [ -z "$install_dir" ]; then
4031
+ mkdir -p "$(dirname "$codex_directive_file")"
4032
+ else
4033
+ refuse_if_symlink "$codex_directive_file"
4034
+ fi
4035
+ if [ -e "$codex_directive_file" ] && { [ ! -f "$codex_directive_file" ] || ! grep -Fq '<!-- weave-router managed codex directive -->' "$codex_directive_file"; }; then
4036
+ warn "A user-owned Codex directive helper already exists at $codex_directive_file; leaving it untouched."
4037
+ return 1
4038
+ fi
4039
+ if [ -n "$directive_src" ]; then
4040
+ grep -Fq '<!-- weave-router managed codex directive -->' "$directive_src" || {
4041
+ warn "Codex directive helper has no ownership marker; leaving it unchanged."
4042
+ return 1
4043
+ }
4044
+ cp "$directive_src" "$codex_directive_file"
4045
+ else
4046
+ cat >"$codex_directive_file" <<'CODEX_DIRECTIVE_EOF'
4047
+ #!/usr/bin/env bash
4048
+ # <!-- weave-router managed codex directive -->
4049
+ #
4050
+ # Codex UserPromptSubmit hook for the Weave Router. Codex passes a JSON object
4051
+ # on stdin carrying the RAW prompt text, before `$skill` expansion and before
4052
+ # any inference. That is what makes this hook the deterministic equivalent of
4053
+ # Claude Code's slash commands.
4054
+ #
4055
+ # Why this exists. A Codex skill is prompt text: the model reads it, decides to
4056
+ # exec a script, and invents the arguments. Pinning a model that way costs two
4057
+ # inference turns (one to decide to run the script, one because the script's
4058
+ # output arrives as a tool result) and loses argument fidelity — a `$rf - note`
4059
+ # verdict is routinely paraphrased away by the model before it reaches the
4060
+ # router. Claude Code pays neither cost, because `/fm x` is expanded textually
4061
+ # by the client and the router short-circuits a user-typed directive into a
4062
+ # synthetic response with no upstream call at all.
4063
+ #
4064
+ # This hook closes that gap. It parses the directive itself, sends it to the
4065
+ # router as a user-typed message, and blocks the Codex turn — so the directive
4066
+ # costs zero inference and the arguments arrive byte-for-byte.
4067
+ #
4068
+ # The pin lands on the caller's real session because the force-model pin key
4069
+ # omits the first-message discriminator (see deriveForceModelSessionKeyForRequest):
4070
+ # it is derived from the API key and the client session id alone, and this hook
4071
+ # sends the same Session-Id that Codex sends on its own turns.
4072
+ #
4073
+ # FAIL OPEN. Every unexpected condition — no jq, no curl, no credentials, an
4074
+ # unreachable router, a malformed payload — must let the prompt through
4075
+ # untouched. A directive that silently swallows the user's prompt is far worse
4076
+ # than one that does not fire.
4077
+
4078
+ set -uo pipefail
4079
+
4080
+ # ---------- responses ----------
4081
+
4082
+ # pass_through hands the prompt to Codex unchanged. Every failure path ends here.
4083
+ pass_through() {
4084
+ printf '{"continue":true}\n'
4085
+ exit 0
4086
+ }
4087
+
4088
+ # block stops the turn before any inference and shows the text to the user.
4089
+ # Codex renders `reason`; nothing reaches the model.
4090
+ block() {
4091
+ local reason="$1" payload
4092
+ payload="$(jq -cn --arg r "$reason" '{decision:"block", reason:$r, continue:false}' 2>/dev/null)" \
4093
+ || pass_through
4094
+ printf '%s\n' "$payload"
4095
+ exit 0
4096
+ }
4097
+
4098
+ command -v jq >/dev/null 2>&1 || pass_through
4099
+
4100
+ payload="$(cat)" || pass_through
4101
+ [ -n "$payload" ] || pass_through
4102
+
4103
+ prompt="$(jq -r '.prompt // ""' <<<"$payload" 2>/dev/null)" || pass_through
4104
+ session_id="$(jq -r '.session_id // ""' <<<"$payload" 2>/dev/null)" || pass_through
4105
+ requested_model="$(jq -r '.model // ""' <<<"$payload" 2>/dev/null)" || pass_through
4106
+
4107
+ # Only a directive at the very start of the prompt is ours. Prose that merely
4108
+ # mentions `$fm` somewhere in a sentence is the user's text, not a command.
4109
+ case "$prompt" in
4110
+ '$'*) ;;
4111
+ *) pass_through ;;
4112
+ esac
4113
+
4114
+ verb="${prompt#$}"
4115
+ args=""
4116
+ case "$verb" in
4117
+ *' '*)
4118
+ args="${verb#* }"
4119
+ verb="${verb%% *}"
4120
+ ;;
4121
+ esac
4122
+ # Trim surrounding whitespace from the argument tail without touching its
4123
+ # interior: a leading `-`/`+` is a router-feedback verdict and must survive.
4124
+ args="${args#"${args%%[![:space:]]*}"}"
4125
+ args="${args%"${args##*[![:space:]]}"}"
4126
+
4127
+ # ---------- directive table ----------
4128
+ #
4129
+ # Only prompt-capability directives are handled here. The local-toggle skills
4130
+ # (router-on/off/status/models, disable-routing) mutate local config rather than
4131
+ # router state, so a skill remains the right adapter for them.
4132
+ directive=""
4133
+ case "$verb" in
4134
+ fm|force-model) directive="/force-model" ;;
4135
+ ufm|unforce-model) directive="/unforce-model" ;;
4136
+ rf|router-feedback) directive="/router-feedback" ;;
4137
+ router-session)
4138
+ # Purely local: the session id is already in the hook payload, so this
4139
+ # answers without a network call and without a model turn.
4140
+ [ -n "$session_id" ] || pass_through
4141
+ block "✦ Weave Router · session id: $session_id"
4142
+ ;;
4143
+ *) pass_through ;;
4144
+ esac
4145
+
4146
+ # A directive that needs an argument and has none is more useful as a prompt:
4147
+ # the skill can still explain itself rather than the hook eating the message.
4148
+ case "$directive" in
4149
+ /force-model|/router-feedback)
4150
+ [ -n "$args" ] || pass_through
4151
+ ;;
4152
+ esac
4153
+
4154
+ # Without a client session id the router would derive a different pin key than
4155
+ # Codex's own turns, so the pin would apply to a session the user is not in.
4156
+ # Passing through is the honest failure: the skill path still works.
4157
+ [ -n "$session_id" ] || pass_through
4158
+ command -v curl >/dev/null 2>&1 || pass_through
4159
+
4160
+ # ---------- credentials ----------
4161
+ #
4162
+ # Read base_url and the router key from the [model_providers.weave] table.
4163
+ # Deliberately NOT scoped to the managed comment markers: Codex rewrites
4164
+ # config.toml through a TOML serializer when it persists its own state, which
4165
+ # drops comments while keeping the table, and re-emits the inline http_headers
4166
+ # as a subtable with the header name unquoted. A marker-scoped or quoted-only
4167
+ # reader misses both on any config Codex has touched.
4168
+ resolve_router_endpoint() {
4169
+ local config=""
4170
+ local helper_dir
4171
+ helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)" || helper_dir=""
4172
+ if [ -n "$helper_dir" ] && [ -f "$helper_dir/config.toml" ]; then
4173
+ config="$helper_dir/config.toml"
4174
+ elif [ -f "${CODEX_HOME:-$HOME/.codex}/config.toml" ]; then
4175
+ config="${CODEX_HOME:-$HOME/.codex}/config.toml"
4176
+ fi
4177
+ [ -n "$config" ] || return 1
4178
+ awk '
4179
+ # Cut a TOML comment, honouring quoted strings so a # inside a value stays.
4180
+ # A full-line comment reduces to empty and matches nothing below, so this
4181
+ # replaces a separate skip rule -- and unlike one, it also catches a comment
4182
+ # trailing another assignment, which the unanchored matches would otherwise
4183
+ # read as live config on any line preceding the real value.
4184
+ function weave_strip_comment(line, i, c, out, indq, insq, esc) {
4185
+ out = ""
4186
+ indq = 0
4187
+ insq = 0
4188
+ esc = 0
4189
+ for (i = 1; i <= length(line); i++) {
4190
+ c = substr(line, i, 1)
4191
+ if (esc) { out = out c; esc = 0; continue }
4192
+ # Only basic strings have escapes; a backslash in a literal string is
4193
+ # data, so consuming the next character there would mis-track the quote.
4194
+ if (indq && c == "\\") { out = out c; esc = 1; continue }
4195
+ if (!insq && c == "\"") { indq = !indq; out = out c; continue }
4196
+ if (!indq && c == "'"'"'") { insq = !insq; out = out c; continue }
4197
+ if (c == "#" && !indq && !insq) break
4198
+ out = out c
4199
+ }
4200
+ return out
4201
+ }
4202
+ { $0 = weave_strip_comment($0) }
4203
+ # TOML basic string -> raw value: drop the `<header> = "` prefix and the
4204
+ # closing quote, then undo the escaping write_codex_config applied.
4205
+ function weave_unescape(s) {
4206
+ sub(/^"?[A-Za-z][A-Za-z0-9-]*"?[[:space:]]*=[[:space:]]*"/, "", s)
4207
+ sub(/"$/, "", s)
4208
+ gsub(/\\"/, "\"", s)
4209
+ gsub(/\\\\/, "\\", s)
4210
+ return s
4211
+ }
4212
+ /^[[:space:]]*\[/ {
4213
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/)
4214
+ next
4215
+ }
4216
+ !in_provider { next }
4217
+ match($0, /base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
4218
+ v = substr($0, RSTART, RLENGTH)
4219
+ sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
4220
+ if (url == "") url = v
4221
+ }
4222
+ match($0, /"?X-Weave-Router-Key"?[[:space:]]*=[[:space:]]*"([^"\\]|\\.)*"/) {
4223
+ if (key == "") key = weave_unescape(substr($0, RSTART, RLENGTH))
4224
+ }
4225
+ match($0, /"?X-Weave-User-Email"?[[:space:]]*=[[:space:]]*"([^"\\]|\\.)*"/) {
4226
+ if (email == "") email = weave_unescape(substr($0, RSTART, RLENGTH))
4227
+ }
4228
+ match($0, /"?X-Weave-User-Name"?[[:space:]]*=[[:space:]]*"([^"\\]|\\.)*"/) {
4229
+ if (name == "") name = weave_unescape(substr($0, RSTART, RLENGTH))
4230
+ }
4231
+ END { if (url != "" && key != "") printf "%s\n%s\n%s\n%s\n", url, key, email, name }
4232
+ ' "$config" 2>/dev/null
4233
+ }
4234
+
4235
+ endpoint="$(resolve_router_endpoint)" || pass_through
4236
+ base_url="$(printf '%s' "$endpoint" | sed -n 1p)"
4237
+ router_key="$(printf '%s' "$endpoint" | sed -n 2p)"
4238
+ user_email="$(printf '%s' "$endpoint" | sed -n 3p)"
4239
+ user_name="$(printf '%s' "$endpoint" | sed -n 4p)"
4240
+ if [ -z "$base_url" ] || [ -z "$router_key" ]; then
4241
+ pass_through
4242
+ fi
4243
+
4244
+ url="${base_url%/}"
4245
+ url="${url%/v1}/v1/chat/completions"
4246
+
4247
+ # ---------- send ----------
4248
+ #
4249
+ # The leading space is what stops Codex's own slash-command handling from
4250
+ # claiming the line; the router strips it. Sent as a user message (not a tool
4251
+ # result) so the router takes its synthetic short-circuit and never calls a
4252
+ # model — the same path Claude Code's slash commands already take.
4253
+ line=" $directive"
4254
+ [ -n "$args" ] && line="$line $args"
4255
+
4256
+ body="$(jq -cn --arg m "${requested_model:-gpt-5.6-sol}" --arg c "$line" \
4257
+ '{model:$m, messages:[{role:"user", content:$c}]}' 2>/dev/null)" || pass_through
4258
+
4259
+ # Identity headers only when the install has them: the router must never see a
4260
+ # header with an empty value, and omitting them is what an unattributed install
4261
+ # already does on every ordinary turn.
4262
+ identity_args=()
4263
+ [ -n "$user_email" ] && identity_args+=(-H "X-Weave-User-Email: $user_email")
4264
+ [ -n "$user_name" ] && identity_args+=(-H "X-Weave-User-Name: $user_name")
4265
+
4266
+ response="$(curl -fsS --max-time 10 \
4267
+ -H "Content-Type: application/json" \
4268
+ -H "X-Weave-Router-Key: $router_key" \
4269
+ -H "Session-Id: $session_id" \
4270
+ -H "X-App: codex" \
4271
+ ${identity_args[@]+"${identity_args[@]}"} \
4272
+ -d "$body" \
4273
+ "$url" 2>/dev/null)" || pass_through
4274
+ [ -n "$response" ] || pass_through
4275
+
4276
+ # `strings` filters to the string type: jq -r would otherwise render an object
4277
+ # or array as JSON, which is non-empty and would block the turn with garbage.
4278
+ marker="$(jq -r '[.choices[0].message.content | strings] | first // ""' <<<"$response" 2>/dev/null)" || pass_through
4279
+ marker="$(printf '%s' "$marker" | sed -e 's/\*\*//g' -e '/^[[:space:]]*$/d')"
4280
+ [ -n "$marker" ] || pass_through
4281
+
4282
+ block "$marker"
4283
+ CODEX_DIRECTIVE_EOF
4284
+ fi
4285
+ chmod 700 "$codex_directive_file"
4286
+ ok "Codex directive hook installed at $codex_directive_file"
4287
+ }
4288
+
3824
4289
  if [ "$target" = "codex" ]; then
3825
4290
  if ! install_codex_status_script; then
3826
4291
  err "Cannot install the Codex status helper safely; refusing to write hooks that could execute unowned code."
3827
4292
  exit 1
3828
4293
  fi
4294
+ if ! install_codex_directive_script; then
4295
+ warn "Skipping the Codex directive hook; \$fm, \$rf and \$router-session will fall back to their skills."
4296
+ codex_directive_file=""
4297
+ fi
3829
4298
  write_codex_config "$codex_config_file" "$base_url" "$api_key" "$user_email" "$user_name"
3830
4299
  ok "Codex config written to $codex_config_file"
3831
4300
  remove_obsolete_codex_prompt_wrappers "$codex_dir/prompts"
@@ -3842,6 +4311,7 @@ if [ "$target" = "codex" ]; then
3842
4311
  for entry in \
3843
4312
  ".codex/config.toml" \
3844
4313
  ".codex/weave-status.sh" \
4314
+ ".codex/weave-directive.sh" \
3845
4315
  ".codex/.weave-router-disabled"
3846
4316
  do
3847
4317
  if [ ! -f "$gitignore" ] || ! grep -qxF "$entry" "$gitignore"; then
@@ -4222,8 +4692,12 @@ weave_sync_commands() {
4222
4692
  # be recovered those three are skipped rather than rewritten to point at the
4223
4693
  # user-scope install.
4224
4694
  local scope_args="" scope_known="false" off="$cmd_dir/router-off.md"
4695
+ # Backticks are literal Markdown delimiters.
4696
+ # shellcheck disable=SC2016
4225
4697
  if [ -f "$off" ] && grep -Eq '^`npx @(workweave/router|weave-os/router) off --claude.*`$' "$off" 2>/dev/null; then
4226
4698
  scope_known="true"
4699
+ # Backticks are literal Markdown delimiters.
4700
+ # shellcheck disable=SC2016
4227
4701
  scope_args="$(sed -En 's#^`npx @(workweave/router|weave-os/router) off --claude(.*)`$#\2#p' "$off" | head -n 1)"
4228
4702
  fi
4229
4703
 
@@ -4262,7 +4736,7 @@ weave_sync_commands() {
4262
4736
  if [ -f "$prev" ]; then
4263
4737
  new_body="$(weave_render_command "$raw" "$scope_args")"
4264
4738
  prev_body="$(weave_render_command "$prev" "$scope_args")"
4265
- installed_body="$(cat "$installed" 2>/dev/null | sed '/^<!-- weave-router managed command: .* -->$/d')" || installed_body=""
4739
+ installed_body="$(sed '/^<!-- weave-router managed command: .* -->$/d' "$installed" 2>/dev/null)" || installed_body=""
4266
4740
  if [ "$prev_body" = "$installed_body" ] && [ "$new_body" != "$installed_body" ]; then
4267
4741
  tmp="$installed.tmp.$$"
4268
4742
  if printf '%s\n<!-- weave-router managed command: %s -->' "$new_body" "$name" >"$tmp" 2>/dev/null; then
@@ -4493,11 +4967,12 @@ prices='{
4493
4967
  "gpt-5.5-mini": 0.0005,
4494
4968
  "gpt-5.5-nano": 0.00015,
4495
4969
  "gpt-5.5-pro": 0.03,
4496
- "gpt-5.6-luna": 0.001,
4497
- "gpt-5.6-luna-pro": 0.001,
4498
- "gpt-5.6-sol": 0.005,
4499
- "gpt-5.6-sol-pro": 0.005,
4500
- "gpt-5.6-terra": 0.0025,
4970
+ "gpt-5.6-luna": 0.0002,
4971
+ "gpt-5.6-luna-pro": 0.0002,
4972
+ "gpt-5.6-sol": 0.004,
4973
+ "gpt-5.6-sol-pro": 0.004,
4974
+ "gpt-5.6-terra": 0.002,
4975
+ "gpt-6-astra": 0.01,
4501
4976
  "grok-4.5": 0.002,
4502
4977
  "grok-4.6": 0.002,
4503
4978
  "minimax/minimax-m2.7": 0.0003,
@@ -4573,11 +5048,12 @@ prices='{
4573
5048
  "gpt-5.5-mini": 0.0025,
4574
5049
  "gpt-5.5-nano": 0.0006,
4575
5050
  "gpt-5.5-pro": 0.18,
4576
- "gpt-5.6-luna": 0.006,
4577
- "gpt-5.6-luna-pro": 0.006,
4578
- "gpt-5.6-sol": 0.03,
4579
- "gpt-5.6-sol-pro": 0.03,
4580
- "gpt-5.6-terra": 0.015,
5051
+ "gpt-5.6-luna": 0.0012,
5052
+ "gpt-5.6-luna-pro": 0.0012,
5053
+ "gpt-5.6-sol": 0.02,
5054
+ "gpt-5.6-sol-pro": 0.02,
5055
+ "gpt-5.6-terra": 0.012,
5056
+ "gpt-6-astra": 0.05,
4581
5057
  "grok-4.5": 0.006,
4582
5058
  "grok-4.6": 0.006,
4583
5059
  "minimax/minimax-m2.7": 0.0012,
@@ -4658,6 +5134,7 @@ prices='{
4658
5134
  "gpt-5.6-sol": 0.1,
4659
5135
  "gpt-5.6-sol-pro": 0.1,
4660
5136
  "gpt-5.6-terra": 0.1,
5137
+ "gpt-6-astra": 0.1,
4661
5138
  "grok-4.5": 0.25,
4662
5139
  "grok-4.6": 0.25,
4663
5140
  "minimax/minimax-m2.7": 0.2,
@@ -4974,14 +5451,12 @@ write_claude_settings() {
4974
5451
  fi
4975
5452
  custom_headers="$custom_headers"$'\n'"X-App: claude-code"
4976
5453
 
4977
- # Setting ANTHROPIC_BASE_URL makes Claude Code treat us as non-first-party and
4978
- # disable MCP tool-search deferral, inlining every tool schema into every request
4979
- # — a large uncompactable prefix that can push a session into an autocompact
4980
- # thrash loop. ENABLE_TOOL_SEARCH=auto restores on-demand loading (Claude Code's
4981
- # own first-party default).
5454
+ # Setting ANTHROPIC_BASE_URL makes Claude Code treat us as non-first-party.
5455
+ # Force tool-search deferral to match first-party Claude Code; "auto" can inline
5456
+ # every tool schema when the custom endpoint advertises a 200K context window.
4982
5457
  if [ "$scope" = "project" ] && [ -z "$install_dir" ]; then
4983
5458
  jq -n --arg url "$base_url" --arg sl "$statusline_path_for_settings" '{
4984
- env: { ANTHROPIC_BASE_URL: $url, ENABLE_TOOL_SEARCH: "auto" },
5459
+ env: { ANTHROPIC_BASE_URL: $url, ENABLE_TOOL_SEARCH: "true" },
4985
5460
  statusLine: { type: "command", command: $sl },
4986
5461
  attribution: {
4987
5462
  commit: "Co-Authored-By: Weave Router <router@workweave.ai>",
@@ -4990,7 +5465,7 @@ write_claude_settings() {
4990
5465
  }' >"$tmp_patch"
4991
5466
  else
4992
5467
  jq -n --arg url "$base_url" --arg header "$custom_headers" --arg sl "$statusline_path_for_settings" '{
4993
- env: { ANTHROPIC_BASE_URL: $url, ANTHROPIC_CUSTOM_HEADERS: $header, ENABLE_TOOL_SEARCH: "auto" },
5468
+ env: { ANTHROPIC_BASE_URL: $url, ANTHROPIC_CUSTOM_HEADERS: $header, ENABLE_TOOL_SEARCH: "true" },
4994
5469
  statusLine: { type: "command", command: $sl },
4995
5470
  attribution: {
4996
5471
  commit: "Co-Authored-By: Weave Router <router@workweave.ai>",