@weave-os/router 0.2.28 → 0.2.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cc-statusline.sh CHANGED
@@ -1,26 +1,65 @@
1
1
  #!/usr/bin/env bash
2
2
  #
3
3
  # Claude Code statusline for the Weave Router. CC pipes a JSON blob on stdin
4
- # whose `transcript_path` points at the JSONL log of the current session and
5
- # whose `model.display_name` is the user's CC-side model selection. The
6
- # router rewrites each request's `model` field before forwarding, so
7
- # Anthropic/OpenAI/Google return `message.model = <routed>` in the SSE
8
- # stream and CC stores that in the transcript verbatim. Per-turn savings
9
- # come from comparing each turn's routed cost against what the user's
10
- # selection would have cost on the same tokens. Works identically for
11
- # local docker and the managed cloud router — no sidecar, no DB, no auth.
4
+ # whose `transcript_path` points at the current session's JSONL log. Model
5
+ # names and price comparisons come from that local transcript; neither
6
+ # establishes the request's destination, including when the transcript
7
+ # contains an old router pin acknowledgement.
12
8
  #
13
9
  # Wire up by adding to ~/.claude/settings.json:
14
10
  # { "statusLine": { "type": "command", "command": "/abs/path/to/cc-statusline.sh" } }
15
11
  #
16
12
  # Renders:
17
- # WEAVE ROUTER — claude-sonnet-4-5 ← claude-opus-4-7 · saved $1.23 · 12.4k in / 3.1k out / 45.2k cached
13
+ # WEAVE ROUTER · you picked opus-4-7 → served sonnet-4-5 · saved ~$1.23 this session
18
14
  #
19
15
  # Pricing source of truth: internal/router/catalog. Input/output prices and
20
16
  # cache-read multipliers are generated by cmd/genprices. Cache creation remains
21
17
  # at 1.25× input pending TTL-aware pricing.
22
18
 
23
19
  set -euo pipefail
20
+ export PATH="$PATH:$HOME/.weave/bin"
21
+
22
+ # ---------- /router-status prompt hook ----------
23
+ #
24
+ # Registered as a UserPromptSubmit hook with --prompt-hook. Every other prompt
25
+ # passes through untouched; /router-status is answered from local state and
26
+ # stopped before it reaches a model, so checking the router never spends a
27
+ # turn. The settings env (router URL and key header) is inherited by hooks, and
28
+ # the session's last statusline render is cached by the statusline below.
29
+ weave_router_status_hook() {
30
+ command -v jq >/dev/null 2>&1 || return 0
31
+ local payload prompt session line="" root report scope_suffix=""
32
+ [ "$#" -eq 0 ] || scope_suffix="$(printf ' %q' "$@")"
33
+ payload="$(cat)"
34
+ prompt="$(jq -r '.prompt // empty' <<<"$payload" 2>/dev/null)" || return 0
35
+ [[ "$prompt" =~ ^[[:space:]]*/router-status[[:space:]]*$ ]] || return 0
36
+ if [[ "${ANTHROPIC_BASE_URL:-}" == https://api.anthropic.com* ]]; then
37
+ report="Weave Router is off: Claude Code talks to Anthropic directly. Turn it back on with /router-on."
38
+ elif [[ -n "${ANTHROPIC_BASE_URL:-}" && "${ANTHROPIC_CUSTOM_HEADERS:-}" == *"X-Weave-Router-Key:"* ]]; then
39
+ report="Weave Router is on: Claude Code sends requests to ${ANTHROPIC_BASE_URL}."
40
+ elif [[ -n "${ANTHROPIC_BASE_URL:-}" ]]; then
41
+ report="Claude Code sends requests to ${ANTHROPIC_BASE_URL}, but no Weave Router key is set. Repair it with: npx @weave-os/router update --claude${scope_suffix}"
42
+ else
43
+ report="Weave Router is off: Claude Code talks to Anthropic directly. Turn it back on with /router-on."
44
+ fi
45
+ session="$(jq -r '.session_id // empty' <<<"$payload" 2>/dev/null)" || session=""
46
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-status"
47
+ if [[ "$session" =~ ^[A-Za-z0-9._-]{1,128}$ && -f "$root/$session.line" ]]; then
48
+ line="$(head -c 512 "$root/$session.line" | head -n 1)"
49
+ fi
50
+ if [[ -n "$line" ]]; then
51
+ report="$report"$'\n'"This session: $line"
52
+ else
53
+ report="$report"$'\n'"No routed turn yet in this session."
54
+ fi
55
+ report="$report"$'\n'"Full check (key, login, endpoint): npx @weave-os/router status --claude${scope_suffix}"
56
+ jq -n --arg reason "$report" '{continue: false, stopReason: $reason, suppressOutput: true}'
57
+ }
58
+ if [ "${1:-}" = "--prompt-hook" ]; then
59
+ shift
60
+ weave_router_status_hook "$@" || true
61
+ exit 0
62
+ fi
24
63
 
25
64
  # ---------- background self-refresh ----------
26
65
  #
@@ -422,7 +461,14 @@ weave_hidden_gate() {
422
461
  file://*) ;;
423
462
  *) url="$url/v1/display-settings" ;;
424
463
  esac
425
- body="$(curl -fsS --max-time 5 -H "X-Weave-Router-Key: $key" "$url" 2>/dev/null)" || exit 0
464
+ header_file="$(mktemp "$cache_dir/.headers.XXXXXX")" || exit 0
465
+ chmod 600 "$header_file"
466
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
467
+ if ! body="$(curl -fsS --max-time 5 -K "$header_file" "$url" 2>/dev/null)"; then
468
+ rm -f "$header_file"
469
+ exit 0
470
+ fi
471
+ rm -f "$header_file"
426
472
  hidden="$(printf '%s' "$body" | jq -r '.hide_terminal_surfaces // false' 2>/dev/null)"
427
473
  tmp="$cache.tmp.$$"
428
474
  if [ "$hidden" = "true" ]; then
@@ -441,21 +487,32 @@ if weave_hidden_gate </dev/null; then
441
487
  fi
442
488
 
443
489
  input="$(cat)"
490
+ jq -e 'type == "object"' >/dev/null 2>&1 <<<"$input" || exit 0
444
491
  transcript_path="$(printf '%s' "$input" | jq -r '.transcript_path // empty')"
445
- # Prefer model.id over display_name: pricing keys + the routed model id in
492
+ # Prefer model.id over display_name: pricing keys + the response model id in
446
493
  # the transcript are canonical ids (e.g. claude-opus-4-7), while display_name
447
494
  # is a human label ("Opus 4.7 (1M context)") that won't hit the pricing table,
448
- # zeroing out savings. id passes through normalize_model cleanly.
495
+ # preventing a price comparison. id passes through normalize_model cleanly.
449
496
  selected_display="$(printf '%s' "$input" | jq -r '.model.id // .model.display_name // "?"')"
450
497
 
498
+ # Claude owns this percentage and its window; session totals never establish it.
499
+ context_clause="$(jq -r '
500
+ .context_window as $c |
501
+ if ($c.context_window_size | type) == "number" and $c.context_window_size > 0 and $c.context_window_size <= 2147483647
502
+ and ($c.context_window_size | floor) == $c.context_window_size
503
+ and ($c.used_percentage | type) == "number" and $c.used_percentage >= 0 and $c.used_percentage <= 100
504
+ then " · Context " + ($c.used_percentage | floor | tostring) + "%" +
505
+ (if $c.used_percentage >= 90 then " !" else "" end)
506
+ else "" end
507
+ ' <<<"$input" 2>/dev/null)" || context_clause=""
508
+
509
+ [ "${WEAVE_STATUSLINE_CONTEXT:-1}" != "0" ] || context_clause=""
510
+
451
511
  # Normalize a model id to a pricing-table key. CC + the decisions log carry
452
512
  # two flavors of annotation we don't want in the lookup:
453
513
  # * date suffix: claude-opus-4-7-20260101 → claude-opus-4-7
454
514
  # * variant tag: claude-opus-4-7[1m] → claude-opus-4-7
455
- # The 1M-context variant prices ~2× base for prompts >200k tokens, but for
456
- # the "saved $X vs your selection" UX the base rate is the right comparison
457
- # — we're measuring the model swap, not the context tier. Used below on the
458
- # routed and requested model ids from the decisions log / transcript.
515
+ # This estimate compares base model prices, not context-tier surcharges.
459
516
  normalize_model() {
460
517
  printf '%s' "$1" | sed -E 's/\[[^]]*\]$//; s/-[0-9]{8}$//'
461
518
  }
@@ -469,6 +526,7 @@ prices='{
469
526
  "claude-fable-5": 0.01,
470
527
  "claude-fable-5-1": 0.01,
471
528
  "claude-haiku-4-5": 0.001,
529
+ "claude-haiku-5-5": 0.0001,
472
530
  "claude-opus-4-0": 0.015,
473
531
  "claude-opus-4-1": 0.015,
474
532
  "claude-opus-4-5": 0.005,
@@ -479,12 +537,12 @@ prices='{
479
537
  "claude-opus-5-5": 0.004,
480
538
  "claude-sonnet-4-5": 0.003,
481
539
  "claude-sonnet-4-6": 0.003,
482
- "claude-sonnet-5": 0.003,
540
+ "claude-sonnet-5": 0.002,
483
541
  "claude-sonnet-5-5": 0.002,
484
- "deepseek/deepseek-v4-flash": 0.0001134,
542
+ "deepseek/deepseek-v4-flash": 0.00014,
485
543
  "deepseek/deepseek-v4-pro": 0.00174,
486
544
  "deepseek/deepseek-v4-pro-0813": 0.00174,
487
- "deepseek/deepseek-v4.1-flash": 0.00022,
545
+ "deepseek/deepseek-v4.1-flash": 0.0002,
488
546
  "gemini-2.0-flash": 0.0001,
489
547
  "gemini-2.0-flash-lite": 0.000075,
490
548
  "gemini-2.5-flash": 0.0003,
@@ -499,6 +557,7 @@ prices='{
499
557
  "gemini-3.6-flash": 0.0015,
500
558
  "gemini-3.7-flash": 0.0015,
501
559
  "gemini-3.8-flash": 0.0015,
560
+ "gemini-4-argon": 0.002,
502
561
  "google/gemma-4-26b-a4b-it": 0.00015,
503
562
  "gpt-4.1": 0.002,
504
563
  "gpt-4.1-mini": 0.0004,
@@ -525,17 +584,21 @@ prices='{
525
584
  "gpt-6-astra": 0.01,
526
585
  "gpt-6-luna": 0.0001,
527
586
  "gpt-6-sol": 0.002,
587
+ "gpt-6.1-sol": 0.002,
588
+ "gpt-6.1-terra": 0.001,
528
589
  "grok-4.5": 0.002,
529
590
  "grok-4.6": 0.002,
530
591
  "grok-4.7": 0.002,
531
592
  "inclusionai/ling-3.0-flash": 0.00006,
532
593
  "minimax/minimax-m2.7": 0.0003,
533
594
  "minimax/minimax-m3": 0.0003,
595
+ "minimax/minimax-m3.1-flash": 0.00015,
534
596
  "mistralai/mistral-small-2603": 0.0002,
535
597
  "moonshotai/kimi-k2.5": 0.0006,
536
598
  "moonshotai/kimi-k2.6": 0.00095,
537
599
  "moonshotai/kimi-k2.7": 0.00095,
538
600
  "moonshotai/kimi-k3": 0.003,
601
+ "moonshotai/kimi-k3.1": 0.002,
539
602
  "muse-spark-1.3": 0.00125,
540
603
  "qwen/qwen3-235b-a22b-2507": 0.0002266,
541
604
  "qwen/qwen3-30b-a3b-instruct-2507": 0.00015,
@@ -547,7 +610,7 @@ prices='{
547
610
  "qwen/qwen3.7-plus": 0.0004,
548
611
  "qwen/qwen3.8-max": 0.002,
549
612
  "xiaomi/mimo-v2.5-pro": 0.001,
550
- "xiaomi/mimo-v2.6-flash": 0.00014,
613
+ "xiaomi/mimo-v2.6-flash": 0.00013,
551
614
  "xiaomi/mimo-v2.6-pro": 0.000435,
552
615
  "z-ai/glm-5": 0.001,
553
616
  "z-ai/glm-5.1": 0.0014,
@@ -559,6 +622,7 @@ prices='{
559
622
  "claude-fable-5": 0.05,
560
623
  "claude-fable-5-1": 0.05,
561
624
  "claude-haiku-4-5": 0.005,
625
+ "claude-haiku-5-5": 0.0005,
562
626
  "claude-opus-4-0": 0.075,
563
627
  "claude-opus-4-1": 0.075,
564
628
  "claude-opus-4-5": 0.025,
@@ -569,12 +633,12 @@ prices='{
569
633
  "claude-opus-5-5": 0.02,
570
634
  "claude-sonnet-4-5": 0.015,
571
635
  "claude-sonnet-4-6": 0.015,
572
- "claude-sonnet-5": 0.015,
636
+ "claude-sonnet-5": 0.01,
573
637
  "claude-sonnet-5-5": 0.01,
574
- "deepseek/deepseek-v4-flash": 0.0002791,
638
+ "deepseek/deepseek-v4-flash": 0.00028,
575
639
  "deepseek/deepseek-v4-pro": 0.00348,
576
640
  "deepseek/deepseek-v4-pro-0813": 0.00348,
577
- "deepseek/deepseek-v4.1-flash": 0.00066,
641
+ "deepseek/deepseek-v4.1-flash": 0.00099,
578
642
  "gemini-2.0-flash": 0.0004,
579
643
  "gemini-2.0-flash-lite": 0.0003,
580
644
  "gemini-2.5-flash": 0.0012,
@@ -589,6 +653,7 @@ prices='{
589
653
  "gemini-3.6-flash": 0.0075,
590
654
  "gemini-3.7-flash": 0.0075,
591
655
  "gemini-3.8-flash": 0.0075,
656
+ "gemini-4-argon": 0.01,
592
657
  "google/gemma-4-26b-a4b-it": 0.0006,
593
658
  "gpt-4.1": 0.008,
594
659
  "gpt-4.1-mini": 0.0016,
@@ -615,17 +680,21 @@ prices='{
615
680
  "gpt-6-astra": 0.05,
616
681
  "gpt-6-luna": 0.0005,
617
682
  "gpt-6-sol": 0.01,
683
+ "gpt-6.1-sol": 0.01,
684
+ "gpt-6.1-terra": 0.005,
618
685
  "grok-4.5": 0.006,
619
686
  "grok-4.6": 0.006,
620
687
  "grok-4.7": 0.006,
621
688
  "inclusionai/ling-3.0-flash": 0.00018,
622
689
  "minimax/minimax-m2.7": 0.0012,
623
690
  "minimax/minimax-m3": 0.0012,
691
+ "minimax/minimax-m3.1-flash": 0.0006,
624
692
  "mistralai/mistral-small-2603": 0.0006,
625
693
  "moonshotai/kimi-k2.5": 0.003,
626
694
  "moonshotai/kimi-k2.6": 0.004,
627
695
  "moonshotai/kimi-k2.7": 0.004,
628
696
  "moonshotai/kimi-k3": 0.015,
697
+ "moonshotai/kimi-k3.1": 0.01,
629
698
  "muse-spark-1.3": 0.00425,
630
699
  "qwen/qwen3-235b-a22b-2507": 0.0009064,
631
700
  "qwen/qwen3-30b-a3b-instruct-2507": 0.0006,
@@ -649,6 +718,7 @@ prices='{
649
718
  "claude-fable-5": 0.1,
650
719
  "claude-fable-5-1": 0.025,
651
720
  "claude-haiku-4-5": 0.1,
721
+ "claude-haiku-5-5": 0.1,
652
722
  "claude-opus-4-0": 0.1,
653
723
  "claude-opus-4-1": 0.1,
654
724
  "claude-opus-4-5": 0.1,
@@ -661,10 +731,10 @@ prices='{
661
731
  "claude-sonnet-4-6": 0.1,
662
732
  "claude-sonnet-5": 0.1,
663
733
  "claude-sonnet-5-5": 0.1,
664
- "deepseek/deepseek-v4-flash": 0.2,
734
+ "deepseek/deepseek-v4-flash": 0.1,
665
735
  "deepseek/deepseek-v4-pro": 0.0862,
666
736
  "deepseek/deepseek-v4-pro-0813": 0.0862,
667
- "deepseek/deepseek-v4.1-flash": 0.031818181818181815,
737
+ "deepseek/deepseek-v4.1-flash": 0.03,
668
738
  "gemini-2.0-flash": 0.25,
669
739
  "gemini-2.0-flash-lite": 0.25,
670
740
  "gemini-2.5-flash": 0.1,
@@ -679,6 +749,7 @@ prices='{
679
749
  "gemini-3.6-flash": 0.1,
680
750
  "gemini-3.7-flash": 0.1,
681
751
  "gemini-3.8-flash": 0.1,
752
+ "gemini-4-argon": 0.1,
682
753
  "google/gemma-4-26b-a4b-it": 0.1,
683
754
  "gpt-4.1": 0.25,
684
755
  "gpt-4.1-mini": 0.25,
@@ -705,17 +776,21 @@ prices='{
705
776
  "gpt-6-astra": 0.1,
706
777
  "gpt-6-luna": 0.1,
707
778
  "gpt-6-sol": 0.1,
779
+ "gpt-6.1-sol": 0.05,
780
+ "gpt-6.1-terra": 0.05,
708
781
  "grok-4.5": 0.25,
709
782
  "grok-4.6": 0.25,
710
783
  "grok-4.7": 0.25,
711
784
  "inclusionai/ling-3.0-flash": 0.2,
712
785
  "minimax/minimax-m2.7": 0.2,
713
786
  "minimax/minimax-m3": 0.2,
787
+ "minimax/minimax-m3.1-flash": 0.1,
714
788
  "mistralai/mistral-small-2603": 0.1,
715
789
  "moonshotai/kimi-k2.5": 0.5,
716
790
  "moonshotai/kimi-k2.6": 0.1684,
717
791
  "moonshotai/kimi-k2.7": 0.2,
718
792
  "moonshotai/kimi-k3": 0.1,
793
+ "moonshotai/kimi-k3.1": 0.1,
719
794
  "muse-spark-1.3": 0.12,
720
795
  "qwen/qwen3-235b-a22b-2507": 0.5,
721
796
  "qwen/qwen3-30b-a3b-instruct-2507": 0.1684,
@@ -727,7 +802,7 @@ prices='{
727
802
  "qwen/qwen3.7-plus": 0.2,
728
803
  "qwen/qwen3.8-max": 0.125,
729
804
  "xiaomi/mimo-v2.5-pro": 0.1,
730
- "xiaomi/mimo-v2.6-flash": 0.02,
805
+ "xiaomi/mimo-v2.6-flash": 0.015384615384615385,
731
806
  "xiaomi/mimo-v2.6-pro": 0.00827586,
732
807
  "z-ai/glm-5": 0.2,
733
808
  "z-ai/glm-5.1": 0.18571428571428572,
@@ -738,24 +813,14 @@ prices='{
738
813
  }'
739
814
  # END_GENERATED_PRICES
740
815
 
741
- routed=""
742
- forced="false"
743
- forced_model=""
744
- session_savings=""
745
- tot_in=0
746
- tot_out=0
747
- tot_cache_read=0
748
- tot_cache_write=0
749
-
750
- # Per-turn savings compare each turn's routed cost (priced from
751
- # message.model in the transcript) against what the CC-side model selection
752
- # (selected_display) would have cost on the same tokens. The selection
753
- # isn't strictly the per-turn "requested" model — CC tags some background
754
- # side-calls (compaction probes, title-gen) with a different model id —
755
- # but for those the planner short-circuits to a hard pin and the savings
756
- # math zeroes out anyway. Turns where routed == selection or where either
757
- # model isn't in the pricing table emit 0 savings; the tokens clause
758
- # always renders.
816
+ transcript_model=""
817
+ has_pin_record="false"
818
+ last_pin_model=""
819
+ session_cost_difference=""
820
+
821
+ # This is a hypothetical comparison against the CURRENT selection, not
822
+ # realized router savings: the transcript does not record each turn's
823
+ # requested model or prove that any turn went through the router.
759
824
 
760
825
  # Normalize the CC-side selection once for use in the jq math below.
761
826
  requested_norm="$(normalize_model "$selected_display")"
@@ -769,62 +834,52 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
769
834
  # locally (errored requests, cancellations, tool-only stubs) instead of a
770
835
  # real model id. Show that as "failure" rather than leaking the internal
771
836
  # sentinel into the statusline.
772
- routed="$("${reverse[@]}" "$transcript_path" 2>/dev/null \
837
+ transcript_model="$("${reverse[@]}" "$transcript_path" 2>/dev/null \
773
838
  | jq -r 'select(.type=="assistant") | .message.model // empty' \
774
839
  | head -n 1 || true)"
775
- if [[ "$routed" == "<synthetic>" ]]; then
776
- routed="failure"
840
+ if [[ "$transcript_model" == "<synthetic>" ]]; then
841
+ transcript_model="failure"
777
842
  else
778
- routed="$(normalize_model "$routed")"
843
+ transcript_model="$(normalize_model "$transcript_model")"
779
844
  fi
780
845
 
781
- # Detect an active /force-model pin from the router's synthetic ack turns —
782
- # the only turns stamped message.model == "weave-router". The router emits
783
- # one whenever a pin changes state:
784
- # * /force-model → "force-model applied: <model> (<provider>) …"
785
- # * /unforce-model → "force-model cleared …"
786
- # * loop / no-progress break → "… clearing the session pin …" (expires the
787
- # pin, including a user-forced one)
788
- # * unrecognized model → "… isn't a recognized model · keeping
789
- # automatic routing" — a NO-OP: the prior
790
- # pin, if any, is left untouched
791
- # * listing (historical) → "… pick a model by id …" / "no models are
792
- # available to pin …" — also NO-OPs. The
793
- # router no longer emits these, but a
794
- # transcript written while it did still
795
- # carries them, and they must not read as
796
- # a clear or a live pin loses its [forced]
797
- # These persist on disk (the ingress stripper only scrubs them from upstream
798
- # requests). Classify each weave-router turn newest-first, skip the no-op
799
- # "rejected" acks, and let the latest real state change decide: an "applied"
800
- # marker means the session is pinned (and names the model); anything else
801
- # (cleared / loop-break / no-progress) means automatic routing has resumed.
802
- # Restricting to weave-router turns keeps a normal reply that merely quotes
803
- # these phrases from flipping the tag. (A silent server-side TTL expiry emits
804
- # no turn and so can't be reflected here — the pin TTL outlives a session.)
805
- force_state="$("${reverse[@]}" "$transcript_path" 2>/dev/null \
806
- | jq -r 'select(.type=="assistant" and .message.model=="weave-router")
807
- | ([.message.content[]? | select(.type? == "text") | .text] | join(" ") | gsub("[\n\r]"; " ")) as $t
808
- | if ($t | test("force-model applied:")) then "APPLIED " + ($t | capture("force-model applied: (?<m>[^ ]+)").m)
809
- elif ($t | test("isn.t a recognized model")) then "REJECTED"
810
- elif ($t | test("pick a model by id|no models are available to pin")) then "REJECTED"
811
- else "CLEARED" end' 2>/dev/null \
812
- | grep -m1 -v '^REJECTED$' || true)"
846
+ # Fold acknowledged transitions in transcript order. Content-block copies and
847
+ # replayed outcome IDs are the same event, not a newer state change.
848
+ force_state="$(jq -nRr '
849
+ def model: type == "string" and test("^[A-Za-z0-9._:/-]{1,128}$");
850
+ def valid_command_outcome:
851
+ try (.version == 1 and (.id | type == "string" and test("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"))
852
+ and (.command | IN("force_model", "router_session", "router_models", "router_feedback", "loop_stop"))
853
+ and (.disposition | IN("accepted", "rejected"))
854
+ and (.pin.transition | IN("unchanged", "applied", "cleared"))
855
+ and (if .pin.transition == "unchanged" then true else
856
+ .command == "force_model" and .disposition == "accepted" end)
857
+ and (if .pin.transition == "applied" then (.pin.model | model)
858
+ and (.pin.provider | model)
859
+ and ((.pin.effort // "") | type == "string" and test("^[A-Za-z0-9_-]{0,32}$")) else true end)) catch false;
860
+ reduce (inputs | fromjson? | objects) as $entry ({seen:{}, pin:null};
861
+ if $entry.type != "assistant" or $entry.message.model != "weave-router" then .
862
+ elif ($entry.message | has("router_command")) then
863
+ $entry.message.router_command as $o |
864
+ if ($o | valid_command_outcome) and (.seen[$o.id] != true) then
865
+ .seen[$o.id] = true |
866
+ if $o.pin.transition == "applied" then
867
+ .pin = ($o.pin.model + (if ($o.pin.effort // "") == "" then "" else ":" + $o.pin.effort end))
868
+ elif $o.pin.transition == "cleared" then .pin = null else . end
869
+ else . end
870
+ else
871
+ ([$entry.message.content[]? | select(.type? == "text") | .text] | join(" ") | sub("^(?:✦ \\*\\*Weave Router\\*\\* →|Weave Router:)[[:space:]]*"; "")) as $t |
872
+ if ($t | test("^force-(model|parent) applied: [A-Za-z0-9._:/-]+")) then
873
+ .pin = ($t | capture("force-(?:model|parent) applied: (?<m>[A-Za-z0-9._:/-]+)").m)
874
+ elif ($t | test("^force-model cleared\\b")) then .pin = null else . end
875
+ end) | if .pin then "APPLIED " + .pin else "CLEARED" end
876
+ ' "$transcript_path" 2>/dev/null || true)"
813
877
  if [[ "$force_state" == APPLIED\ * ]]; then
814
- forced="true"
815
- forced_model="${force_state#APPLIED }"
878
+ has_pin_record="true"
879
+ last_pin_model="${force_state#APPLIED }"
816
880
  fi
817
881
 
818
- # Compute a session running total: savings across every assistant turn
819
- # whose marker reports a requested ≠ routed swap, plus cumulative token
820
- # counts across every assistant turn (rerouted or not — total work the
821
- # session has done). cache_creation is priced at 1.25× input; cache_read
822
- # uses each model's generated catalog multiplier. Both are no-ops when the
823
- # provider does not return those fields.
824
- #
825
- # The marker regex tolerates the optional "(<provider>)" segment and a
826
- # `[1m]` / `-YYYYMMDD` suffix on either model name so transcripts written
827
- # against context-tiered or dated model ids still parse cleanly.
882
+ # Missing prices leave the comparison unknown without hiding the model.
828
883
  #
829
884
  # Dedup note: CC writes one JSONL entry per *content block* in an
830
885
  # assistant turn (text, text, tool_use → 3 entries), and every entry
@@ -838,9 +893,9 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
838
893
  # grows), so the composite key keeps turns distinct. Two turns with
839
894
  # byte-identical id AND usage would still collapse, but that's a
840
895
  # genuine retry/duplicate we want to drop.
841
- read -r session_savings tot_in tot_out tot_cache_read tot_cache_write < <(
896
+ session_cost_difference="$(
842
897
  jq -rs --argjson p "$prices" --arg requested "$requested_norm" '
843
- [.[] | select(.type=="assistant")] |
898
+ [.[] | select(.type=="assistant" and .message.model!="<synthetic>" and .message.model!="weave-router")] |
844
899
  unique_by([.message.id, .message.usage]) |
845
900
  .[] |
846
901
  .message as $m |
@@ -851,13 +906,13 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
851
906
  cwrt: ($m.usage.cache_creation_input_tokens // 0),
852
907
  crd: ($m.usage.cache_read_input_tokens // 0)
853
908
  } as $t |
854
- (if $requested == "" or $requested == $rm then 0
909
+ (if ($t.in + $t.out + $t.cwrt + $t.crd) == 0 then 0
855
910
  else
856
911
  ($p.input[$rm] // null) as $rin | ($p.output[$rm] // null) as $rout |
857
912
  ($p.cache_read[$rm] // null) as $rcr |
858
913
  ($p.input[$requested] // null) as $sin | ($p.output[$requested] // null) as $sout |
859
914
  ($p.cache_read[$requested] // null) as $scr |
860
- if ($rin == null or $rout == null or $rcr == null or $sin == null or $sout == null or $scr == null) then 0
915
+ if ($rin == null or $rout == null or $rcr == null or $sin == null or $sout == null or $scr == null) then null
861
916
  else
862
917
  (($t.in + 1.25 * $t.cwrt + $rcr * $t.crd) / 1000) as $routed_input_units |
863
918
  (($t.in + 1.25 * $t.cwrt + $scr * $t.crd) / 1000) as $requested_input_units |
@@ -867,21 +922,20 @@ if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
867
922
  ($requested_cost - $routed_cost)
868
923
  end
869
924
  end) as $savings |
870
- "\($savings) \($t.in) \($t.out) \($t.crd) \($t.cwrt)"
925
+ if $savings == null then "unknown" else $savings end
871
926
  ' "$transcript_path" 2>/dev/null \
872
- | awk 'BEGIN{s=0; i=0; o=0; r=0; w=0}
873
- {s+=$1; i+=$2; o+=$3; r+=$4; w+=$5}
874
- END{printf "%.4f %d %d %d %d\n", s, i, o, r, w}'
875
- ) || true
927
+ | awk 'BEGIN{s=0}
928
+ {if ($1 == "unknown") comparison_unknown=1; else s+=$1}
929
+ END{
930
+ if (NR == 0 || comparison_unknown) printf "unknown"; else printf "%.4f", s;
931
+ }'
932
+ )" || true
876
933
  fi
877
934
 
878
935
  # ---------- refresh when a model isn't in the pricing table ----------
879
936
  #
880
- # A model that shipped after this copy of the script has no price entry, so the
881
- # jq guard above zeroes savings on every turn and the line reads "saved $0.00"
882
- # — indistinguishable from "the router ran and didn't beat your selection". The
883
- # periodic check heals that eventually, but a week late, and a model launch is
884
- # exactly when the number gets looked at. Refresh off-schedule instead.
937
+ # A model missing from this copy's price table cannot be compared. Refresh
938
+ # off-schedule instead of waiting up to a week for the periodic check.
885
939
  #
886
940
  # Keyed on its own stamp per unpriced id: a model we never price (self-hosted,
887
941
  # unrecognized) then costs one download per interval, not one per turn, and
@@ -909,82 +963,173 @@ weave_refresh_on_price_miss() {
909
963
  model_slug="$(printf '%s' "$missing" | tr -c 'A-Za-z0-9._-' '_')"
910
964
  weave_self_refresh ".miss.${model_slug}" 1
911
965
  }
912
- weave_refresh_on_price_miss "$requested_norm" "$routed" 2>/dev/null || true
966
+ weave_refresh_on_price_miss "$requested_norm" "$transcript_model" 2>/dev/null || true
967
+
968
+ router_context_fallback() {
969
+ [ -z "$context_clause" ] || return 0
970
+ [ "${WEAVE_STATUSLINE_CONTEXT:-1}" != "0" ] || return 0
971
+ local session helper_dir scope cache root now snapshot
972
+ session="$(jq -r '.session_id // empty' <<<"$input")"
973
+ case "$session" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
974
+ [ "${#session}" -le 128 ] || return 0
975
+ helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
976
+ scope="$(printf '%s' "$helper_dir" | cksum | awk '{print $1}')"
977
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-context"
978
+ cache="$root/$scope-$session.json"
979
+ mkdir -p "$root" 2>/dev/null || return 0
980
+ chmod 700 "$root"
981
+ local generation active_file
982
+ active_file="$cache.active"
983
+ now="$(date +%s)"
984
+ if [ -f "$cache" ] && [ "$(wc -c <"$cache")" -le 8192 ]; then
985
+ snapshot="$(jq -ce --arg session "$session" --argjson now "$now" '
986
+
987
+ def tokens: type == "number" and floor == . and . > 0 and . <= 2147483647;
988
+ def epoch: sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601;
989
+ .context_snapshot as $s |
990
+ select(.session_id == $session and $s.version == 1 and $s.estimate_kind == "approximate") |
991
+ select(($s.estimate_tokens | tokens) and ($s.context_window | tokens) and ($s.output_reserve_tokens | tokens)) |
992
+ select(($s.served_model | type) == "string" and ($s.served_model | test("^[A-Za-z0-9._:/-]{1,128}$"))) |
993
+ select(($s.request_id | type) == "string" and ($s.request_id | length) > 0 and ($s.request_id | length) <= 128) |
994
+ ($s.recorded_at | epoch) as $recorded | ($s.requested_at | epoch) as $requested |
995
+ select($requested > 0 and $requested <= $recorded and $recorded <= $now and $now - $recorded <= 300) |
996
+ $s
997
+ ' "$cache" 2>/dev/null)" || snapshot=""
998
+ if [ -n "$snapshot" ]; then
999
+ local served requested
1000
+ served="$(normalize_model "$(jq -r '.served_model' <<<"$snapshot")")"
1001
+ requested="$(normalize_model "$(jq -r '.requested_model // empty' <<<"$snapshot")")"
1002
+ if [ "$served" = "$transcript_model" ] && [ "$requested" = "$requested_norm" ]; then
1003
+ context_clause="$(awk -v e="$(jq -r '.estimate_tokens' <<<"$snapshot")" -v w="$(jq -r '.context_window' <<<"$snapshot")" 'BEGIN {
1004
+ printf " · last Router ctx est. ~%s/%s", (e < 1000 ? e : sprintf("%.0fk", e/1000)), (w < 1000 ? w : sprintf("%.0fk", w/1000))
1005
+ }')"
1006
+ fi
1007
+ fi
1008
+ fi
1009
+ command -v curl >/dev/null 2>&1 || return 0
1010
+ mkdir -p "$root" 2>/dev/null || return 0
1011
+ chmod 700 "$root"
1012
+ (
1013
+ exec </dev/null
1014
+ # Serialize refreshes; a timeout cannot delay the status-line process.
1015
+ if ! mkdir "$cache.lock" 2>/dev/null; then
1016
+ lock_mtime="$(stat -c %Y "$cache.lock" 2>/dev/null || stat -f %m "$cache.lock" 2>/dev/null)" || lock_mtime=0
1017
+ [ $(( $(date +%s) - lock_mtime )) -gt 30 ] || exit 0
1018
+ dead="$cache.lock.dead.$$"
1019
+ mv "$cache.lock" "$dead" 2>/dev/null || exit 0
1020
+ rm -rf "$dead"
1021
+ mkdir "$cache.lock" 2>/dev/null || exit 0
1022
+ fi
1023
+ trap 'rmdir "$cache.lock" 2>/dev/null' EXIT
1024
+ generation="$(mktemp "$root/.generation.XXXXXX")" || exit 0
1025
+ printf '%s' "$generation" >"$generation"
1026
+ chmod 600 "$generation"
1027
+ mv "$generation" "$active_file"
1028
+ settings_base="$HOME"
1029
+ case "$helper_dir" in */.claude) settings_base="${helper_dir%/.claude}" ;; esac
1030
+ settings="$settings_base/.claude/settings.json"
1031
+ local_settings="$settings_base/.claude/settings.local.json"
1032
+ base=""
1033
+ key=""
1034
+ for settings_file in "$settings" "$local_settings"; do
1035
+ [ -f "$settings_file" ] || continue
1036
+ if jq -e '.env | has("ANTHROPIC_BASE_URL")' "$settings_file" >/dev/null 2>&1; then
1037
+ base="$(jq -r '.env.ANTHROPIC_BASE_URL // empty' "$settings_file" 2>/dev/null)"
1038
+ fi
1039
+ if jq -e '.env | has("ANTHROPIC_CUSTOM_HEADERS")' "$settings_file" >/dev/null 2>&1; then
1040
+ key="$(jq -r '.env.ANTHROPIC_CUSTOM_HEADERS // "" | split("\n")[] | select(startswith("X-Weave-Router-Key:")) | sub("^X-Weave-Router-Key:[[:space:]]*"; "")' "$settings_file" 2>/dev/null | head -n1)"
1041
+ fi
1042
+ done
1043
+ base="${WEAVE_ROUTER_BASE_URL:-${ANTHROPIC_BASE_URL:-$base}}"
1044
+ key="${WEAVE_ROUTER_KEY:-$key}"
1045
+ [ -n "$base" ] && [ -n "$key" ] || exit 0
1046
+ url="${base%/}"
1047
+ case "$url" in file://*) ;; *) url="${url%/v1}/v1/sessions/$session/cost" ;; esac
1048
+ tmp="$(mktemp "$root/.snapshot.XXXXXX")" || exit 0
1049
+ header_file="$(mktemp "$root/.headers.XXXXXX")" || { rm -f "$tmp"; exit 0; }
1050
+ chmod 600 "$tmp"
1051
+ chmod 600 "$header_file"
1052
+ printf 'header = "X-Weave-Router-Key: %s"\n' "$key" >"$header_file"
1053
+ if curl -fsS --max-time 5 --max-filesize 8192 -K "$header_file" "$url" -o "$tmp" 2>/dev/null \
1054
+ && [ "$(wc -c <"$tmp")" -le 8192 ] \
1055
+ && [ "$(jq -r '.session_id // empty' "$tmp" 2>/dev/null)" = "$session" ]; then
1056
+ # Request observation order is independent of fetch completion order.
1057
+ # Fraction padding preserves RFC3339Nano order within the same second.
1058
+ previous="$cache"
1059
+ [ -f "$previous" ] || previous=/dev/null
1060
+ if [ "$(cat "$active_file" 2>/dev/null)" = "$generation" ] && jq -e -s '
1061
+ def timestamp_parts: split(".") as $p |
1062
+ [($p[0] | sub("Z$"; "")), ((($p[1] // "") | sub("Z$"; "")) + "000000000")[0:9]];
1063
+ def observation: [.context_snapshot.requested_at | timestamp_parts] + [.context_snapshot.recorded_at | timestamp_parts];
1064
+ (.[0] | observation) as $fresh |
1065
+ if length == 1 or .[1].context_snapshot == null then true else $fresh > (.[1] | observation) or ($fresh == (.[1] | observation) and .[0].context_snapshot.request_id == .[1].context_snapshot.request_id) end
1066
+ ' "$tmp" "$previous" 2>/dev/null; then
1067
+ mv "$tmp" "$cache"
1068
+ fi
1069
+ fi
1070
+ rm -f "$tmp" "$header_file"
1071
+ ) >/dev/null 2>&1 &
1072
+ disown 2>/dev/null || true
1073
+ }
1074
+ router_context_fallback 2>/dev/null || true
913
1075
 
914
1076
  # Brand color (#FF6C47) on terminals that grok 24-bit truecolor — that's
915
1077
  # every modern one (iTerm2, Apple Terminal, vscode, ghostty, alacritty,
916
1078
  # wezterm, kitty). Falls back gracefully on any escape-stripping terminal.
917
1079
  brand=$'\033[38;2;255;108;71mWEAVE ROUTER\033[0m'
918
1080
 
919
- # Format helpers.
920
- fmt_money() {
921
- awk -v v="$1" 'BEGIN{
922
- if (v == "" || v+0 == 0) { printf "$0.00"; exit }
923
- if (v+0 < 0.005 && v+0 > -0.005){ printf "<$0.01"; exit }
924
- if (v+0 < 0) { printf "-$%.2f", -v+0; exit }
925
- printf "$%.2f", v
926
- }'
927
- }
928
1081
 
929
- fmt_tok() {
930
- awk -v v="$1" 'BEGIN{
931
- v = v+0
932
- if (v >= 1000000) { printf "%.1fM", v/1000000; exit }
933
- if (v >= 1000) { printf "%.1fk", v/1000; exit }
934
- printf "%d", v
935
- }'
936
- }
937
-
938
- # cache_read tokens are the cached portion of every prompt that the
939
- # provider serves at 0.1× input price; cache_write tokens are the bytes
940
- # that get newly cached on this turn at 1.25× input price. They behave
941
- # completely differently both in cost and in what they tell the user
942
- # about session-level efficiency, so we surface them separately rather
943
- # than summing into a single "cached" number that conflates the two.
944
- # Each clause is shown only when nonzero, so quiet sessions stay quiet.
945
- tokens_clause=""
946
- if [[ "$tot_in" -gt 0 || "$tot_out" -gt 0 || "$tot_cache_read" -gt 0 || "$tot_cache_write" -gt 0 ]]; then
947
- tokens_clause=" · $(fmt_tok "$tot_in") in / $(fmt_tok "$tot_out") out"
948
- if [[ "$tot_cache_read" -gt 0 ]]; then
949
- tokens_clause+=" / $(fmt_tok "$tot_cache_read") cache read"
950
- fi
951
- if [[ "$tot_cache_write" -gt 0 ]]; then
952
- tokens_clause+=" / $(fmt_tok "$tot_cache_write") cache write"
953
- fi
1082
+ # "you picked" is Claude Code's selection; "served" is the latest response
1083
+ # model in the transcript. The cost clause is the whole session priced at the
1084
+ # served models versus the pick, so an upgrade reads as "more", not a negative
1085
+ # saving.
1086
+ short_model() { printf '%s' "${1#claude-}"; }
1087
+ picked=""
1088
+ if [[ -n "$selected_display" && "$selected_display" != "?" ]]; then
1089
+ picked="$(short_model "$requested_norm")"
954
1090
  fi
955
-
956
- if [[ "$forced" == "true" ]]; then
957
- # Session is pinned via /force-model. The "← selection · saved $X" clause
958
- # describes automatic routing and would be misleading on a manual pin, so
959
- # show the pinned model with a [forced] tag instead. forced_model comes from
960
- # the marker; fall back to the routed/selected id if parsing came up empty.
961
- forced_display="${forced_model:-${routed:-$selected_display}}"
962
- printf '%s — %s [forced]%s' "$brand" "$forced_display" "$tokens_clause"
963
- elif [[ "$routed" == "failure" ]]; then
964
- # Latest turn was a CC-synthesized error stub — don't claim a routing
965
- # swap or compute savings against a non-model.
966
- printf '%s — %s%s' "$brand" "$routed" "$tokens_clause"
967
- elif [[ -n "$routed" ]]; then
968
- # Always show the savings clause, flooring a non-positive total at $0.00.
969
- # session_savings is "0.0000" on fresh sessions or sessions where every
970
- # turn routed back to the selected model, and can go negative when routing
971
- # upgrades a turn to a pricier model (e.g. a sticky/hard-pinned side-call,
972
- # or a hard turn escalated to opus). "saved -$X" would mislead, so clamp
973
- # the display to $0.00 rather than dropping the clause — a $0.00 readout
974
- # tells the user the router ran and simply didn't beat their selection.
975
- # When the CC selection is unknown ("?" or empty) there's nothing to
976
- # compare against, so drop the "← selection" arrow and just show routed.
977
- display_savings="$session_savings"
978
- if [[ -z "$display_savings" ]] \
979
- || awk -v v="$display_savings" 'BEGIN{exit !(v+0 < 0)}'; then
980
- display_savings="0"
981
- fi
982
- if [[ -n "$selected_display" && "$selected_display" != "?" ]]; then
983
- printf '%s — %s ← %s · saved %s%s' \
984
- "$brand" "$routed" "$selected_display" "$(fmt_money "$display_savings")" "$tokens_clause"
1091
+ status_text=""
1092
+ if [[ "$transcript_model" == "failure" ]]; then
1093
+ status_text=" · last response failed"
1094
+ elif [[ "$transcript_model" == "weave-router" ]]; then
1095
+ status_text=" · control acknowledgement"
1096
+ elif [[ -n "$transcript_model" ]]; then
1097
+ if [[ -n "$picked" && "$transcript_model" != "$requested_norm" ]]; then
1098
+ status_text=" · you picked $picked → served $(short_model "$transcript_model")"
985
1099
  else
986
- printf '%s — %s%s' "$brand" "$routed" "$tokens_clause"
1100
+ status_text=" · served $(short_model "$transcript_model")"
987
1101
  fi
988
- else
989
- printf '%s — %s%s' "$brand" "$selected_display" "$tokens_clause"
1102
+ elif [[ -n "$picked" ]]; then
1103
+ status_text=" · you picked $picked"
990
1104
  fi
1105
+ if [[ -n "$session_cost_difference" && "$session_cost_difference" != "unknown" && "$transcript_model" != "failure" && "$transcript_model" != "weave-router" ]]; then
1106
+ status_text="$status_text$(awk -v v="$session_cost_difference" -v pick="$picked" 'BEGIN{
1107
+ v = v + 0
1108
+ if (v >= 0.005) printf " · saved ~$%.2f this session", v
1109
+ else if (v > 0) printf " · saved <$0.01 this session"
1110
+ else if (v == 0) printf " · no savings yet this session"
1111
+ else if (v > -0.005) printf " · cost <$0.01 more than %s this session", pick
1112
+ else printf " · cost ~$%.2f more than %s this session (upgraded hard turns)", -v, pick
1113
+ }')"
1114
+ fi
1115
+ if [[ "$has_pin_record" == "true" ]]; then
1116
+ status_text="$status_text · last pin: $last_pin_model"
1117
+ fi
1118
+
1119
+ # /router-status reads this back through the prompt hook, so it can answer
1120
+ # without a model turn.
1121
+ weave_cache_status_line() {
1122
+ local session root
1123
+ session="$(jq -r '.session_id // empty' <<<"$input")"
1124
+ case "$session" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esac
1125
+ [ "${#session}" -le 128 ] || return 0
1126
+ [ -n "$transcript_model" ] || return 0
1127
+ root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/claude-status"
1128
+ mkdir -p "$root" && chmod 700 "$root" || return 0
1129
+ printf '%s\n' "${status_text# · }" >"$root/$session.line.$$" \
1130
+ && mv -f "$root/$session.line.$$" "$root/$session.line"
1131
+ }
1132
+ weave_cache_status_line 2>/dev/null || true
1133
+
1134
+ printf '%s%s' "$brand" "$status_text"
1135
+ printf '%s' "$context_clause"