@weave-os/router 0.2.14

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.
Files changed (69) hide show
  1. package/LICENSE +90 -0
  2. package/README.md +172 -0
  3. package/bin.js +68 -0
  4. package/cc-statusline.sh +951 -0
  5. package/codex-skills/disable-routing/SKILL.md +22 -0
  6. package/codex-skills/fm/SKILL.md +15 -0
  7. package/codex-skills/fm/scripts/emit.sh +8 -0
  8. package/codex-skills/force-model/SKILL.md +15 -0
  9. package/codex-skills/force-model/scripts/emit.sh +9 -0
  10. package/codex-skills/rf/SKILL.md +15 -0
  11. package/codex-skills/rf/scripts/emit.sh +7 -0
  12. package/codex-skills/router-feedback/SKILL.md +15 -0
  13. package/codex-skills/router-feedback/scripts/emit.sh +9 -0
  14. package/codex-skills/router-models/SKILL.md +51 -0
  15. package/codex-skills/router-off/SKILL.md +22 -0
  16. package/codex-skills/router-on/SKILL.md +22 -0
  17. package/codex-skills/router-status/SKILL.md +19 -0
  18. package/codex-skills/ufm/SKILL.md +14 -0
  19. package/codex-skills/ufm/scripts/emit.sh +3 -0
  20. package/codex-skills/unforce-model/SKILL.md +14 -0
  21. package/codex-skills/unforce-model/scripts/emit.sh +4 -0
  22. package/codex-status.sh +378 -0
  23. package/commands/beta.md +5 -0
  24. package/commands/fm.md +6 -0
  25. package/commands/force-model.md +6 -0
  26. package/commands/models.md +46 -0
  27. package/commands/rf.md +6 -0
  28. package/commands/router-feedback.md +6 -0
  29. package/commands/router-models.md +46 -0
  30. package/commands/router-off.md +10 -0
  31. package/commands/router-on.md +10 -0
  32. package/commands/router-session.md +15 -0
  33. package/commands/router-status.md +10 -0
  34. package/commands/ufm.md +5 -0
  35. package/commands/unforce-model.md +5 -0
  36. package/directives.tsv +13 -0
  37. package/install.sh +5092 -0
  38. package/opencode-weave/README.md +78 -0
  39. package/opencode-weave/package.json +18 -0
  40. package/opencode-weave/src/index.ts +655 -0
  41. package/package.json +79 -0
  42. package/pi-router/README.md +123 -0
  43. package/pi-router/package.json +25 -0
  44. package/pi-router/skills/install-lsps/SKILL.md +75 -0
  45. package/pi-router/skills/lsp-guide/SKILL.md +63 -0
  46. package/pi-router/src/beta.ts +21 -0
  47. package/pi-router/src/compaction.ts +188 -0
  48. package/pi-router/src/config.ts +293 -0
  49. package/pi-router/src/context-window.ts +12 -0
  50. package/pi-router/src/dispatch.ts +377 -0
  51. package/pi-router/src/force-model.ts +126 -0
  52. package/pi-router/src/index.ts +62 -0
  53. package/pi-router/src/lsp-broker.ts +255 -0
  54. package/pi-router/src/lsp-client.ts +435 -0
  55. package/pi-router/src/lsp-format.ts +230 -0
  56. package/pi-router/src/lsp-install.ts +215 -0
  57. package/pi-router/src/lsp-protocol.ts +128 -0
  58. package/pi-router/src/lsp-servers.ts +361 -0
  59. package/pi-router/src/lsp.ts +529 -0
  60. package/pi-router/src/metadata.ts +32 -0
  61. package/pi-router/src/pricing.generated.ts +91 -0
  62. package/pi-router/src/provider.ts +64 -0
  63. package/pi-router/src/routed-model.ts +182 -0
  64. package/pi-router/src/safety.ts +66 -0
  65. package/pi-router/src/savings.ts +191 -0
  66. package/pi-router/src/ui.ts +91 -0
  67. package/pi-router/src/wooly.ts +408 -0
  68. package/registry.sh +102 -0
  69. package/uninstall.sh +788 -0
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: disable-routing
3
+ description: "Switch Codex back to its normal provider for future sessions."
4
+ ---
5
+
6
+ <!-- weave-router managed disable-routing skill -->
7
+
8
+ # Disable Weave routing
9
+
10
+ When the user invokes `$disable-routing`, switch the current Codex installation
11
+ off the Weave Router without logging out or deleting its router configuration.
12
+
13
+ 1. Explain that the change takes effect on the next `codex` launch and that it
14
+ can later be reversed with `npx --package @weave-os/router -y -- weave-router on --codex{{SCOPE}}`.
15
+ 2. Run exactly:
16
+
17
+ ```bash
18
+ npx --package @weave-os/router -y -- weave-router off --codex{{SCOPE}}
19
+ ```
20
+
21
+ 3. Report the command result. Do not uninstall the router or alter any other
22
+ Codex settings.
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: fm
3
+ description: "Alias for force-model — pin this Codex session to a specific model through the Weave Router."
4
+ ---
5
+
6
+ <!-- weave-router managed fm skill -->
7
+
8
+ When the user invokes `$fm <model-id>`, run this skill's `scripts/emit.sh` using the
9
+ absolute path shown in this skill's `<path>` (its directory + `/scripts/emit.sh`).
10
+ Pass the model id as arguments, quoted as a single argument list.
11
+ Do not send a user message and do not type a Codex slash command.
12
+
13
+ The script prints a leading-space `/force-model` line. The Weave Router reads that
14
+ exec output, pins the session, and continues this turn — so run the script once and
15
+ do not repeat its output as your answer. Then report the router's response.
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ # Alias of force-model/scripts/emit.sh
3
+ set -euo pipefail
4
+ if [ "$#" -eq 0 ] || [ -z "${1:-}" ]; then
5
+ echo "usage: emit.sh <model-id>" >&2
6
+ exit 1
7
+ fi
8
+ printf ' /force-model %s\n' "$*"
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: force-model
3
+ description: "Pin this Codex session to a specific model through the Weave Router."
4
+ ---
5
+
6
+ <!-- weave-router managed force-model skill -->
7
+
8
+ When the user invokes `$force-model <model-id>` (or `$fm`), run this skill's `scripts/emit.sh` using the
9
+ absolute path shown in this skill's `<path>` (its directory + `/scripts/emit.sh`).
10
+ Pass the model id as arguments, quoted as a single argument list.
11
+ Do not send a user message and do not type a Codex slash command.
12
+
13
+ The script prints a leading-space `/force-model` line. The Weave Router reads that
14
+ exec output, pins the session, and continues this turn — so run the script once and
15
+ do not repeat its output as your answer. Then report the router's response.
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bash
2
+ # Print a leading-space /force-model directive. Codex runs this via exec;
3
+ # the Weave Router intercepts the tool output and pins the session.
4
+ set -euo pipefail
5
+ if [ "$#" -eq 0 ] || [ -z "${1:-}" ]; then
6
+ echo "usage: emit.sh <model-id>" >&2
7
+ exit 1
8
+ fi
9
+ printf ' /force-model %s\n' "$*"
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: rf
3
+ description: "Alias for router-feedback — submit feedback about a Weave Router decision or model performance."
4
+ ---
5
+
6
+ <!-- weave-router managed rf skill -->
7
+
8
+ When the user invokes `$rf <feedback>`, run this skill's `scripts/emit.sh` using the
9
+ absolute path shown in this skill's `<path>` (its directory + `/scripts/emit.sh`).
10
+ Pass the feedback text as arguments, quoted as a single argument list.
11
+ Do not send a user message and do not type a Codex slash command.
12
+
13
+ The script prints a leading-space `/router-feedback` line. The Weave Router reads that
14
+ exec output, records the feedback, and continues this turn — so run the script once and
15
+ do not repeat its output as your answer. Then report the router's response.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ if [ "$#" -eq 0 ] || [ -z "${1:-}" ]; then
4
+ echo "usage: emit.sh <feedback>" >&2
5
+ exit 1
6
+ fi
7
+ printf ' /router-feedback %s\n' "$*"
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: router-feedback
3
+ description: "Submit feedback about a Weave Router decision or model performance."
4
+ ---
5
+
6
+ <!-- weave-router managed router-feedback skill -->
7
+
8
+ When the user invokes `$router-feedback <feedback>` (or `$rf`), run this skill's `scripts/emit.sh` using the
9
+ absolute path shown in this skill's `<path>` (its directory + `/scripts/emit.sh`).
10
+ Pass the feedback text as arguments, quoted as a single argument list.
11
+ Do not send a user message and do not type a Codex slash command.
12
+
13
+ The script prints a leading-space `/router-feedback` line. The Weave Router reads that
14
+ exec output, records the feedback, and continues this turn — so run the script once and
15
+ do not repeat its output as your answer. Then report the router's response.
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bash
2
+ # Print a leading-space /router-feedback directive. Codex runs this via exec;
3
+ # the Weave Router intercepts the tool output and records the feedback.
4
+ set -euo pipefail
5
+ if [ "$#" -eq 0 ] || [ -z "${1:-}" ]; then
6
+ echo "usage: emit.sh <feedback>" >&2
7
+ exit 1
8
+ fi
9
+ printf ' /router-feedback %s\n' "$*"
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: router-models
3
+ description: "List the models the Weave Router may route to, and turn them on or off."
4
+ ---
5
+
6
+ <!-- weave-router managed router-models skill -->
7
+
8
+ # Weave Router model selection
9
+
10
+ When the user invokes `$router-models`, show which models this
11
+ installation lets the router pick from, and change that selection when asked.
12
+ This is the same list — and the same stored setting — as the checkboxes on the
13
+ router dashboard's settings page.
14
+
15
+ Start by running:
16
+
17
+ ```bash
18
+ npx --package @weave-os/router -y -- weave-router models --codex{{SCOPE}}
19
+ ```
20
+
21
+ That prints every deployed model grouped by provider, with `[x]` for models the
22
+ router may pick and `[ ]` for models it may not. Present it back as a compact
23
+ checklist in that same `[x]` / `[ ]` form, keeping the provider grouping and the
24
+ exact model ids — the user selects models by id.
25
+
26
+ Then:
27
+
28
+ - If the user named models or providers, work out whether they want them on or
29
+ off from how they phrased it, and apply it with
30
+ `weave-router models enable <id>... --codex{{SCOPE}}` or
31
+ `weave-router models disable <id>... --codex{{SCOPE}}` (add `providers` before
32
+ `enable`/`disable` to switch a whole provider). Several ids can go in one
33
+ call. Then re-run the list and show the result.
34
+ - If they named nothing, stop after the list and ask which ones to change.
35
+ Never change anything they did not ask for.
36
+
37
+ Other things they might ask for:
38
+
39
+ - Rank models by preference:
40
+ `weave-router models prefer <id> <id>... --codex{{SCOPE}}` (order matters), or
41
+ `weave-router models prefer clear --codex{{SCOPE}}` to drop the ranking.
42
+ - Providers only: `weave-router models providers --codex{{SCOPE}}`.
43
+
44
+ If the command reports that this router doesn't expose model selection, that's a
45
+ Weave-hosted router: model selection belongs to the whole organization there, so
46
+ tell the user to change it at https://router.workweave.ai/dashboard/settings —
47
+ don't try to work around it. Its listing carries no on/off state, so present it
48
+ as a plain list; don't infer which models are enabled.
49
+
50
+ Disabling a model takes effect on the router's next routing decision; no restart
51
+ is needed.
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: router-off
3
+ description: "Route Codex to its default provider again (turn the Weave Router off)."
4
+ ---
5
+
6
+ <!-- weave-router managed router-off skill -->
7
+
8
+ # Turn Weave routing off
9
+
10
+ When the user invokes `$router-off`, switch this Codex installation off the
11
+ Weave Router without logging out or deleting its router configuration.
12
+
13
+ Run exactly:
14
+
15
+ ```bash
16
+ npx --package @weave-os/router -y -- weave-router off --codex{{SCOPE}}
17
+ ```
18
+
19
+ Then report the result and tell the user the change takes effect on their next
20
+ `codex` launch — Codex reads its provider config at startup, so the current
21
+ session keeps routing as it already was. It can be reversed with
22
+ `$router-on`. Do not uninstall the router or alter any other Codex settings.
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: router-on
3
+ description: "Route Codex through the Weave Router again (turn it back on)."
4
+ ---
5
+
6
+ <!-- weave-router managed router-on skill -->
7
+
8
+ # Turn Weave routing on
9
+
10
+ When the user invokes `$router-on`, switch this Codex installation back onto
11
+ the Weave Router using the managed configuration already on disk.
12
+
13
+ Run exactly:
14
+
15
+ ```bash
16
+ npx --package @weave-os/router -y -- weave-router on --codex{{SCOPE}}
17
+ ```
18
+
19
+ Then report the result and tell the user the change takes effect on their next
20
+ `codex` launch — Codex reads its provider config at startup, so the current
21
+ session keeps routing as it already was. Do not re-run the installer or alter
22
+ any other Codex settings.
@@ -0,0 +1,19 @@
1
+ ---
2
+ name: router-status
3
+ description: "Show whether Codex is routing through the Weave Router or using its default provider."
4
+ ---
5
+
6
+ <!-- weave-router managed router-status skill -->
7
+
8
+ # Weave Router status
9
+
10
+ When the user invokes `$router-status`, report whether this Codex installation
11
+ routes through the Weave Router.
12
+
13
+ Run exactly:
14
+
15
+ ```bash
16
+ npx --package @weave-os/router -y -- weave-router status --codex{{SCOPE}}
17
+ ```
18
+
19
+ Then summarize the result in one line. Do not change any configuration.
@@ -0,0 +1,14 @@
1
+ ---
2
+ name: ufm
3
+ description: "Alias for unforce-model — clear the active Weave Router model pin."
4
+ ---
5
+
6
+ <!-- weave-router managed ufm skill -->
7
+
8
+ When the user invokes `$ufm`, run this skill's `scripts/emit.sh` using the
9
+ absolute path shown in this skill's `<path>` (its directory + `/scripts/emit.sh`).
10
+ Do not send a user message and do not type a Codex slash command.
11
+
12
+ The script prints a leading-space `/unforce-model` line. The Weave Router reads that
13
+ exec output, clears the pin, and continues this turn — so run the script once and
14
+ do not repeat its output as your answer. Then report the router's response.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ printf ' /unforce-model\n'
@@ -0,0 +1,14 @@
1
+ ---
2
+ name: unforce-model
3
+ description: "Clear the active Weave Router model pin for this Codex session."
4
+ ---
5
+
6
+ <!-- weave-router managed unforce-model skill -->
7
+
8
+ When the user invokes `$unforce-model` (or `$ufm`), run this skill's `scripts/emit.sh` using the
9
+ absolute path shown in this skill's `<path>` (its directory + `/scripts/emit.sh`).
10
+ Do not send a user message and do not type a Codex slash command.
11
+
12
+ The script prints a leading-space `/unforce-model` line. The Weave Router reads that
13
+ exec output, clears the pin, and continues this turn — so run the script once and
14
+ do not repeat its output as your answer. Then report the router's response.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bash
2
+ # Print a leading-space /unforce-model directive for the Weave Router.
3
+ set -euo pipefail
4
+ printf ' /unforce-model\n'
@@ -0,0 +1,378 @@
1
+ #!/usr/bin/env bash
2
+ # <!-- weave-router managed codex status -->
3
+ #
4
+ # Codex lifecycle hook for the Weave Router. Codex passes a JSON object on
5
+ # stdin; the Stop hook includes the last assistant message, which carries the
6
+ # router's routed-model marker when the selected model changes. The helper
7
+ # keeps the last known routed model per session and reflects it in the terminal
8
+ # title, so the active router remains visible between turns without injecting
9
+ # another message into the conversation.
10
+ #
11
+ # Savings come from the router, not from local arithmetic. Codex records its
12
+ # own requested model on every turn and never the served one, so the per-turn
13
+ # pricing the Claude Code statusline does cannot be reproduced here — it would
14
+ # price both sides of the comparison at the same model and report zero. The
15
+ # router already sums the real thing per session, so the hook fetches
16
+ # GET <base>/v1/sessions/<id>/cost and renders what it returns. The fetch runs
17
+ # in a detached subshell writing a cache the NEXT turn reads, so no turn ever
18
+ # blocks on the network, and every failure path leaves the title model-only.
19
+
20
+ set -euo pipefail
21
+
22
+ # ---------- background self-refresh ----------
23
+ #
24
+ # Codex runs this helper on SessionStart and after every turn. Once per
25
+ # interval, use that lifecycle as the update check so installed helpers pick
26
+ # up router fixes without requiring the user to rerun the installer. The
27
+ # download is detached and swapped atomically; the current hook always
28
+ # finishes against the copy it started with.
29
+ #
30
+ # Set WEAVE_CODEX_STATUS_UPDATE=0 to disable it. Self-hosters can point
31
+ # WEAVE_CODEX_STATUS_URL at their own helper source. The common
32
+ # WEAVE_STATUSLINE_UPDATE and WEAVE_STATUSLINE_UPDATE_INTERVAL_DAYS variables
33
+ # remain accepted as aliases for users who configure both clients together.
34
+ weave_self_refresh() {
35
+ [ "${WEAVE_CODEX_STATUS_UPDATE:-${WEAVE_STATUSLINE_UPDATE:-1}}" = "0" ] && return 0
36
+ command -v curl >/dev/null 2>&1 || return 0
37
+
38
+ local self="${BASH_SOURCE[0]:-$0}"
39
+ [ -f "$self" ] && [ -w "$self" ] || return 0
40
+
41
+ local interval_days="${WEAVE_CODEX_STATUS_UPDATE_INTERVAL_DAYS:-${WEAVE_STATUSLINE_UPDATE_INTERVAL_DAYS:-7}}"
42
+ case "$interval_days" in
43
+ ''|*[!0-9]*) return 0 ;;
44
+ esac
45
+ local interval_seconds=$(( interval_days * 86400 ))
46
+
47
+ local cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router"
48
+ mkdir -p "$cache_dir" 2>/dev/null || return 0
49
+ local script_slug path_digest
50
+ script_slug="$(printf '%s' "$self" | tr -c 'A-Za-z0-9._-' '_')"
51
+ path_digest="$(printf '%s' "$self" | cksum | awk '{print $1}')"
52
+ local stamp="$cache_dir/checked-at${script_slug}-${path_digest}-codex"
53
+
54
+ local now stamp_mtime
55
+ now="$(date +%s 2>/dev/null)" || return 0
56
+ if [ -f "$stamp" ]; then
57
+ stamp_mtime="$(stat -c %Y "$stamp" 2>/dev/null || stat -f %m "$stamp" 2>/dev/null)" || stamp_mtime=0
58
+ else
59
+ stamp_mtime=0
60
+ fi
61
+ if [ -n "${stamp_mtime:-}" ] && [ "$stamp_mtime" -gt 0 ] \
62
+ && [ $(( now - stamp_mtime )) -lt "$interval_seconds" ]; then
63
+ return 0
64
+ fi
65
+
66
+ # Stamp before forking so concurrent SessionStart/Stop hooks share one
67
+ # download. A failed download consumes the interval; the next hook retries.
68
+ : >"$stamp" 2>/dev/null || return 0
69
+
70
+ local url="${WEAVE_CODEX_STATUS_URL:-https://raw.githubusercontent.com/weave-os/router/main/install/codex-status.sh}"
71
+ local tmp="${self}.tmp.$$"
72
+ (
73
+ exec </dev/null
74
+ if curl -fsSL --max-time 15 "$url" -o "$tmp" 2>/dev/null \
75
+ && [ -s "$tmp" ] \
76
+ && head -n 1 "$tmp" | grep -q '^#!.*bash' \
77
+ && [ "$(wc -c <"$tmp")" -ge 1024 ]; then
78
+ if cmp -s "$tmp" "$self"; then
79
+ rm -f "$tmp"
80
+ else
81
+ chmod 700 "$tmp" 2>/dev/null || true
82
+ mv "$tmp" "$self" 2>/dev/null || rm -f "$tmp"
83
+ fi
84
+ else
85
+ rm -f "$tmp"
86
+ fi
87
+ ) >/dev/null 2>&1 &
88
+ disown 2>/dev/null || true
89
+ return 0
90
+ }
91
+
92
+ state_root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/codex"
93
+ helper_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
94
+ disabled_marker="$helper_dir/.weave-router-disabled"
95
+ router_badge_sentinel=$'⁣⁠⁣⁠'
96
+ # Must stay verbatim in sync with install.sh / uninstall.sh: the endpoint read
97
+ # below is scoped to this block so a key-shaped string elsewhere in the user's
98
+ # config.toml is never adopted.
99
+ codex_begin_marker="# >>> weave-router managed (do not edit between markers) >>>"
100
+ codex_end_marker="# <<< weave-router managed <<<"
101
+
102
+ emit_title() {
103
+ local title="$1"
104
+ if [ -n "${WEAVE_CODEX_STATUS_TITLE_FILE:-}" ]; then
105
+ printf '%s\n' "$title" >"$WEAVE_CODEX_STATUS_TITLE_FILE"
106
+ elif [ -w /dev/tty ]; then
107
+ printf '\033]0;%s\007' "$title" >/dev/tty
108
+ fi
109
+ }
110
+
111
+ safe_session_id() {
112
+ local id="$1"
113
+ case "$id" in
114
+ ''|*[!A-Za-z0-9._-]*) return 1 ;;
115
+ esac
116
+ [ "${#id}" -le 128 ] || return 1
117
+ printf '%s' "$id"
118
+ }
119
+
120
+ safe_display_value() {
121
+ printf '%s' "$1" | sed 's/[^A-Za-z0-9._:\/-]//g' | cut -c1-128
122
+ }
123
+
124
+ state_file_for() {
125
+ local id
126
+ id="$(safe_session_id "$1")" || return 1
127
+ printf '%s/%s.state' "$state_root" "$id"
128
+ }
129
+
130
+ read_state() {
131
+ local file="$1" key value
132
+ [ -f "$file" ] || return 0
133
+ while IFS='=' read -r key value; do
134
+ case "$key" in
135
+ routed_model) routed_model="$value" ;;
136
+ esac
137
+ done <"$file"
138
+ }
139
+
140
+ write_state() {
141
+ local file="$1" tmp
142
+ mkdir -p "$state_root"
143
+ chmod 700 "$state_root"
144
+ tmp="$(mktemp "$state_root/.state.XXXXXX")"
145
+ printf 'requested_model=%s\nrouted_model=%s\n' "$requested_model" "$routed_model" >"$tmp"
146
+ chmod 600 "$tmp"
147
+ mv "$tmp" "$file"
148
+ }
149
+
150
+ cost_file_for() {
151
+ local id
152
+ id="$(safe_session_id "$1")" || return 1
153
+ printf '%s/%s.cost' "$state_root" "$id"
154
+ }
155
+
156
+ # Reads the router base URL and key out of the Codex config this install owns.
157
+ # Resolved from the helper's own location first so a project-scope install never
158
+ # reads (or leaks) the user-scope key: the project helper lives in the same
159
+ # .codex directory as its config, while the user-scope helper sits in ~/.weave
160
+ # and reads ~/.codex. Values are scoped to the managed block so a key-shaped
161
+ # string the user wrote elsewhere in the file is never adopted. awk, not a TOML
162
+ # parser, because the Codex target deliberately does not require jq for config
163
+ # reads.
164
+ read_codex_endpoint() {
165
+ local config=""
166
+ # Project/custom installs name the helper weave-status.sh and keep it next
167
+ # to their config.toml. Falling through to ~/.codex would fetch another
168
+ # installation's session cost with that key. The user-scope helper
169
+ # (codex-status.sh in ~/.weave) has no adjacent config and owns HOME.
170
+ if [ -f "$helper_dir/config.toml" ]; then
171
+ config="$helper_dir/config.toml"
172
+ elif [ "$(basename "$0")" != "weave-status.sh" ] && [ -f "$HOME/.codex/config.toml" ]; then
173
+ config="$HOME/.codex/config.toml"
174
+ fi
175
+ [ -n "$config" ] || return 0
176
+ awk -v begin="$codex_begin_marker" -v end="$codex_end_marker" '
177
+ $0 == begin { inblk = 1; next }
178
+ $0 == end { inblk = 0; next }
179
+ !inblk { next }
180
+ match($0, /base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
181
+ v = substr($0, RSTART, RLENGTH)
182
+ sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
183
+ url = v
184
+ }
185
+ match($0, /"X-Weave-Router-Key"[[:space:]]*=[[:space:]]*"[^"]*"/) {
186
+ v = substr($0, RSTART, RLENGTH)
187
+ sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
188
+ key = v
189
+ }
190
+ END { if (url != "" && key != "") printf "%s\n%s\n", url, key }
191
+ ' "$config" 2>/dev/null || true
192
+ }
193
+
194
+ # Kicks off a detached fetch of this session's committed cost. The result lands
195
+ # in a cache the next turn reads; this turn renders whatever is already there.
196
+ # Fire-and-forget on purpose — a slow or unreachable router must never stall a
197
+ # Codex turn, and every failure simply leaves the previous cache in place.
198
+ refresh_session_cost() {
199
+ local id="$1" file="$2"
200
+ [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && return 0
201
+ command -v curl >/dev/null 2>&1 || return 0
202
+
203
+ local endpoint base_url key
204
+ endpoint="$(read_codex_endpoint)" || return 0
205
+ base_url="$(printf '%s' "$endpoint" | sed -n 1p)"
206
+ key="$(printf '%s' "$endpoint" | sed -n 2p)"
207
+ [ -n "$base_url" ] && [ -n "$key" ] || return 0
208
+
209
+ mkdir -p "$state_root" 2>/dev/null || return 0
210
+ chmod 700 "$state_root" 2>/dev/null || true
211
+
212
+ (
213
+ exec </dev/null
214
+ # mkdir is the portable atomic test-and-set. A crashed holder would block
215
+ # refreshes forever, so a lock older than the fetch timeout is reclaimed.
216
+ lock="$file.lock"
217
+ if ! mkdir "$lock" 2>/dev/null; then
218
+ lock_mtime="$(stat -c %Y "$lock" 2>/dev/null || stat -f %m "$lock" 2>/dev/null)" || lock_mtime=0
219
+ lock_now="$(date +%s 2>/dev/null)" || lock_now=0
220
+ if [ "${lock_mtime:-0}" -le 0 ] || [ $(( lock_now - lock_mtime )) -le 30 ]; then
221
+ exit 0
222
+ fi
223
+ rm -rf "$lock" 2>/dev/null
224
+ mkdir "$lock" 2>/dev/null || exit 0
225
+ fi
226
+ trap 'rmdir "$lock" 2>/dev/null' EXIT
227
+
228
+ # A file:// base is the offline/test seam: curl reads it as the response
229
+ # body directly, so the endpoint path is meaningless for it.
230
+ url="${base_url%/}"
231
+ case "$url" in
232
+ file://*) ;;
233
+ *) url="${url%/v1}/v1/sessions/$id/cost" ;;
234
+ esac
235
+ body="$(curl -fsS --max-time 5 -H "X-Weave-Router-Key: $key" "$url" 2>/dev/null)" || exit 0
236
+ # savings_usd is the router's own (requested - actual). A body without it
237
+ # (404, error envelope, older router) writes nothing and leaves the cache.
238
+ savings="$(printf '%s' "$body" | jq -r '.savings_usd // empty' 2>/dev/null)" || exit 0
239
+ case "$savings" in
240
+ ''|*[!0-9.eE+-]*) exit 0 ;;
241
+ esac
242
+ tmp="$file.tmp.$$"
243
+ mkdir -p "$(dirname "$file")" 2>/dev/null
244
+ if printf '%s' "$savings" >"$tmp" 2>/dev/null; then
245
+ chmod 600 "$tmp" 2>/dev/null
246
+ mv "$tmp" "$file" 2>/dev/null
247
+ fi
248
+ rm -f "$tmp" 2>/dev/null
249
+ ) >/dev/null 2>&1 &
250
+ disown 2>/dev/null || true
251
+ }
252
+
253
+ # Renders the cached savings as a display clause, or nothing. Values below a
254
+ # cent read as "<$0.01" rather than "$0.00", which would be indistinguishable
255
+ # from "the router ran and did not beat your selection". Negative totals are
256
+ # omitted entirely: the router picked a pricier model for quality on this
257
+ # session and "saved -$0.02" is a worse answer than staying quiet.
258
+ savings_clause() {
259
+ local file="$1" raw
260
+ [ "${WEAVE_CODEX_STATUS_SAVINGS:-1}" = "0" ] && return 0
261
+ [ -f "$file" ] || return 0
262
+ raw="$(cat "$file" 2>/dev/null)" || return 0
263
+ case "$raw" in
264
+ ''|*[!0-9.eE+-]*) return 0 ;;
265
+ esac
266
+ awk -v v="$raw" 'BEGIN{
267
+ v = v + 0
268
+ if (v < 0.005) { exit }
269
+ if (v < 0.01) { printf " · saved <$0.01"; exit }
270
+ printf " · saved $%.2f", v
271
+ }' 2>/dev/null || true
272
+ }
273
+
274
+ set -e
275
+
276
+ case "${1:-hook}" in
277
+ --direct)
278
+ emit_title "Codex · direct"
279
+ exit 0
280
+ ;;
281
+ --on)
282
+ rm -f "$disabled_marker"
283
+ emit_title "Weave Router · active"
284
+ exit 0
285
+ ;;
286
+ --off)
287
+ [ ! -L "$disabled_marker" ] || exit 0
288
+ : >"$disabled_marker"
289
+ chmod 600 "$disabled_marker"
290
+ emit_title "Codex · direct"
291
+ exit 0
292
+ ;;
293
+ esac
294
+
295
+ payload="$(cat)"
296
+ [ -n "$payload" ] || exit 0
297
+ weave_self_refresh 2>/dev/null || true
298
+ command -v jq >/dev/null 2>&1 || exit 0
299
+ jq -e . >/dev/null 2>&1 <<<"$payload" || exit 0
300
+
301
+ hook_event_name="$(jq -r '.hook_event_name // ""' <<<"$payload")"
302
+ if [ "$hook_event_name" = "SessionStart" ]; then
303
+ if [ -f "$disabled_marker" ]; then
304
+ emit_title "Codex · direct"
305
+ else
306
+ emit_title "Weave Router · active"
307
+ fi
308
+ exit 0
309
+ fi
310
+
311
+ if [ -f "$disabled_marker" ]; then
312
+ exit 0
313
+ fi
314
+
315
+ requested_model="$(safe_display_value "$(jq -r '.model // ""' <<<"$payload")")"
316
+ routed_model=""
317
+ session_id="$(jq -r '.session_id // ""' <<<"$payload")"
318
+ last_assistant_message="$(jq -r '.last_assistant_message // ""' <<<"$payload")"
319
+
320
+ file=""
321
+ if file="$(state_file_for "$session_id" 2>/dev/null)"; then
322
+ read_state "$file"
323
+ fi
324
+
325
+ # The marker is intentionally matched only at the beginning of the assistant
326
+ # message. Do not treat ordinary prose that mentions the heading as metadata.
327
+ first_line="${last_assistant_message%%$'\n'*}"
328
+ marker_model=""
329
+ force_model=""
330
+ case "$first_line" in
331
+ "${router_badge_sentinel}✦ **Weave Router** → "*)
332
+ marker_model="${first_line#"${router_badge_sentinel}✦ **Weave Router** → "}"
333
+ marker_model="${marker_model%% ·*}"
334
+ ;;
335
+ "✦ **Weave Router** → "*)
336
+ marker_model="${first_line#"✦ **Weave Router** → "}"
337
+ marker_model="${marker_model%% ·*}"
338
+ ;;
339
+ esac
340
+ case "$first_line" in
341
+ "Weave Router: force-model applied: "*" ("*)
342
+ force_model="${first_line#"Weave Router: force-model applied: "}"
343
+ force_model="${force_model%% (*}"
344
+ ;;
345
+ esac
346
+ if [ -n "$marker_model" ]; then
347
+ routed_model="$(safe_display_value "$marker_model")"
348
+ elif [ -n "$force_model" ]; then
349
+ routed_model="$(safe_display_value "$force_model")"
350
+ else
351
+ routed_model="$(safe_display_value "$routed_model")"
352
+ fi
353
+
354
+ if [ -n "$file" ]; then
355
+ write_state "$file"
356
+ fi
357
+
358
+ # The cache holds the previous turn's fetch; the refresh below serves the next
359
+ # one. Router telemetry is written asynchronously anyway, so a just-finished
360
+ # turn would not be included even in a blocking read — reading first and
361
+ # refreshing after costs a turn of freshness and buys never blocking Codex.
362
+ savings=""
363
+ cost_file=""
364
+ if cost_file="$(cost_file_for "$session_id" 2>/dev/null)"; then
365
+ savings="$(savings_clause "$cost_file")"
366
+ refresh_session_cost "$(safe_session_id "$session_id")" "$cost_file"
367
+ fi
368
+
369
+ if [ -n "$routed_model" ] && [ -n "$requested_model" ] && [ "$routed_model" != "$requested_model" ]; then
370
+ title="Weave Router · $routed_model ← $requested_model$savings"
371
+ elif [ -n "$routed_model" ]; then
372
+ title="Weave Router · $routed_model$savings"
373
+ elif [ -n "$requested_model" ]; then
374
+ title="Weave Router · active ← $requested_model$savings"
375
+ else
376
+ title="Weave Router · active$savings"
377
+ fi
378
+ emit_title "$title"