@weave-os/router 0.2.16 → 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.
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env bash
2
+ # <!-- weave-router managed codex directive -->
3
+ #
4
+ # Codex UserPromptSubmit hook for the Weave Router. Codex passes a JSON object
5
+ # on stdin carrying the RAW prompt text, before `$skill` expansion and before
6
+ # any inference. That is what makes this hook the deterministic equivalent of
7
+ # Claude Code's slash commands.
8
+ #
9
+ # Why this exists. A Codex skill is prompt text: the model reads it, decides to
10
+ # exec a script, and invents the arguments. Pinning a model that way costs two
11
+ # inference turns (one to decide to run the script, one because the script's
12
+ # output arrives as a tool result) and loses argument fidelity — a `$rf - note`
13
+ # verdict is routinely paraphrased away by the model before it reaches the
14
+ # router. Claude Code pays neither cost, because `/fm x` is expanded textually
15
+ # by the client and the router short-circuits a user-typed directive into a
16
+ # synthetic response with no upstream call at all.
17
+ #
18
+ # This hook closes that gap. It parses the directive itself, sends it to the
19
+ # router as a user-typed message, and blocks the Codex turn — so the directive
20
+ # costs zero inference and the arguments arrive byte-for-byte.
21
+ #
22
+ # The pin lands on the caller's real session because the force-model pin key
23
+ # omits the first-message discriminator (see deriveForceModelSessionKeyForRequest):
24
+ # it is derived from the API key and the client session id alone, and this hook
25
+ # sends the same Session-Id that Codex sends on its own turns.
26
+ #
27
+ # FAIL OPEN. Every unexpected condition — no jq, no curl, no credentials, an
28
+ # unreachable router, a malformed payload — must let the prompt through
29
+ # untouched. A directive that silently swallows the user's prompt is far worse
30
+ # than one that does not fire.
31
+
32
+ set -uo pipefail
33
+
34
+ # ---------- responses ----------
35
+
36
+ # pass_through hands the prompt to Codex unchanged. Every failure path ends here.
37
+ pass_through() {
38
+ printf '{"continue":true}\n'
39
+ exit 0
40
+ }
41
+
42
+ # block stops the turn before any inference and shows the text to the user.
43
+ # Codex renders `reason`; nothing reaches the model.
44
+ block() {
45
+ local reason="$1" payload
46
+ payload="$(jq -cn --arg r "$reason" '{decision:"block", reason:$r, continue:false}' 2>/dev/null)" \
47
+ || pass_through
48
+ printf '%s\n' "$payload"
49
+ exit 0
50
+ }
51
+
52
+ command -v jq >/dev/null 2>&1 || pass_through
53
+
54
+ payload="$(cat)" || pass_through
55
+ [ -n "$payload" ] || pass_through
56
+
57
+ prompt="$(jq -r '.prompt // ""' <<<"$payload" 2>/dev/null)" || pass_through
58
+ session_id="$(jq -r '.session_id // ""' <<<"$payload" 2>/dev/null)" || pass_through
59
+ requested_model="$(jq -r '.model // ""' <<<"$payload" 2>/dev/null)" || pass_through
60
+
61
+ # Only a directive at the very start of the prompt is ours. Prose that merely
62
+ # mentions `$fm` somewhere in a sentence is the user's text, not a command.
63
+ case "$prompt" in
64
+ '$'*) ;;
65
+ *) pass_through ;;
66
+ esac
67
+
68
+ verb="${prompt#$}"
69
+ args=""
70
+ case "$verb" in
71
+ *' '*)
72
+ args="${verb#* }"
73
+ verb="${verb%% *}"
74
+ ;;
75
+ esac
76
+ # Trim surrounding whitespace from the argument tail without touching its
77
+ # interior: a leading `-`/`+` is a router-feedback verdict and must survive.
78
+ args="${args#"${args%%[![:space:]]*}"}"
79
+ args="${args%"${args##*[![:space:]]}"}"
80
+
81
+ # ---------- directive table ----------
82
+ #
83
+ # Only prompt-capability directives are handled here. The local-toggle skills
84
+ # (router-on/off/status/models, disable-routing) mutate local config rather than
85
+ # router state, so a skill remains the right adapter for them.
86
+ directive=""
87
+ case "$verb" in
88
+ fm|force-model) directive="/force-model" ;;
89
+ ufm|unforce-model) directive="/unforce-model" ;;
90
+ rf|router-feedback) directive="/router-feedback" ;;
91
+ router-session)
92
+ # Purely local: the session id is already in the hook payload, so this
93
+ # answers without a network call and without a model turn.
94
+ [ -n "$session_id" ] || pass_through
95
+ block "✦ Weave Router · session id: $session_id"
96
+ ;;
97
+ *) pass_through ;;
98
+ esac
99
+
100
+ # A directive that needs an argument and has none is more useful as a prompt:
101
+ # the skill can still explain itself rather than the hook eating the message.
102
+ case "$directive" in
103
+ /force-model|/router-feedback)
104
+ [ -n "$args" ] || pass_through
105
+ ;;
106
+ esac
107
+
108
+ # Without a client session id the router would derive a different pin key than
109
+ # Codex's own turns, so the pin would apply to a session the user is not in.
110
+ # Passing through is the honest failure: the skill path still works.
111
+ [ -n "$session_id" ] || pass_through
112
+ command -v curl >/dev/null 2>&1 || pass_through
113
+
114
+ # ---------- credentials ----------
115
+ #
116
+ # Read base_url and the router key from the [model_providers.weave] table.
117
+ # Deliberately NOT scoped to the managed comment markers: Codex rewrites
118
+ # config.toml through a TOML serializer when it persists its own state, which
119
+ # drops comments while keeping the table, and re-emits the inline http_headers
120
+ # as a subtable with the header name unquoted. A marker-scoped or quoted-only
121
+ # reader misses both on any config Codex has touched.
122
+ resolve_router_endpoint() {
123
+ local config=""
124
+ local helper_dir
125
+ helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)" || helper_dir=""
126
+ if [ -n "$helper_dir" ] && [ -f "$helper_dir/config.toml" ]; then
127
+ config="$helper_dir/config.toml"
128
+ elif [ -f "${CODEX_HOME:-$HOME/.codex}/config.toml" ]; then
129
+ config="${CODEX_HOME:-$HOME/.codex}/config.toml"
130
+ fi
131
+ [ -n "$config" ] || return 1
132
+ awk '
133
+ # Cut a TOML comment, honouring quoted strings so a # inside a value stays.
134
+ # A full-line comment reduces to empty and matches nothing below, so this
135
+ # replaces a separate skip rule -- and unlike one, it also catches a comment
136
+ # trailing another assignment, which the unanchored matches would otherwise
137
+ # read as live config on any line preceding the real value.
138
+ function weave_strip_comment(line, i, c, out, indq, insq, esc) {
139
+ out = ""
140
+ indq = 0
141
+ insq = 0
142
+ esc = 0
143
+ for (i = 1; i <= length(line); i++) {
144
+ c = substr(line, i, 1)
145
+ if (esc) { out = out c; esc = 0; continue }
146
+ # Only basic strings have escapes; a backslash in a literal string is
147
+ # data, so consuming the next character there would mis-track the quote.
148
+ if (indq && c == "\\") { out = out c; esc = 1; continue }
149
+ if (!insq && c == "\"") { indq = !indq; out = out c; continue }
150
+ if (!indq && c == "'"'"'") { insq = !insq; out = out c; continue }
151
+ if (c == "#" && !indq && !insq) break
152
+ out = out c
153
+ }
154
+ return out
155
+ }
156
+ { $0 = weave_strip_comment($0) }
157
+ # TOML basic string -> raw value: drop the `<header> = "` prefix and the
158
+ # closing quote, then undo the escaping write_codex_config applied.
159
+ function weave_unescape(s) {
160
+ sub(/^"?[A-Za-z][A-Za-z0-9-]*"?[[:space:]]*=[[:space:]]*"/, "", s)
161
+ sub(/"$/, "", s)
162
+ gsub(/\\"/, "\"", s)
163
+ gsub(/\\\\/, "\\", s)
164
+ return s
165
+ }
166
+ /^[[:space:]]*\[/ {
167
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/)
168
+ next
169
+ }
170
+ !in_provider { next }
171
+ match($0, /base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
172
+ v = substr($0, RSTART, RLENGTH)
173
+ sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
174
+ if (url == "") url = v
175
+ }
176
+ match($0, /"?X-Weave-Router-Key"?[[:space:]]*=[[:space:]]*"([^"\\]|\\.)*"/) {
177
+ if (key == "") key = weave_unescape(substr($0, RSTART, RLENGTH))
178
+ }
179
+ match($0, /"?X-Weave-User-Email"?[[:space:]]*=[[:space:]]*"([^"\\]|\\.)*"/) {
180
+ if (email == "") email = weave_unescape(substr($0, RSTART, RLENGTH))
181
+ }
182
+ match($0, /"?X-Weave-User-Name"?[[:space:]]*=[[:space:]]*"([^"\\]|\\.)*"/) {
183
+ if (name == "") name = weave_unescape(substr($0, RSTART, RLENGTH))
184
+ }
185
+ END { if (url != "" && key != "") printf "%s\n%s\n%s\n%s\n", url, key, email, name }
186
+ ' "$config" 2>/dev/null
187
+ }
188
+
189
+ endpoint="$(resolve_router_endpoint)" || pass_through
190
+ base_url="$(printf '%s' "$endpoint" | sed -n 1p)"
191
+ router_key="$(printf '%s' "$endpoint" | sed -n 2p)"
192
+ user_email="$(printf '%s' "$endpoint" | sed -n 3p)"
193
+ user_name="$(printf '%s' "$endpoint" | sed -n 4p)"
194
+ if [ -z "$base_url" ] || [ -z "$router_key" ]; then
195
+ pass_through
196
+ fi
197
+
198
+ url="${base_url%/}"
199
+ url="${url%/v1}/v1/chat/completions"
200
+
201
+ # ---------- send ----------
202
+ #
203
+ # The leading space is what stops Codex's own slash-command handling from
204
+ # claiming the line; the router strips it. Sent as a user message (not a tool
205
+ # result) so the router takes its synthetic short-circuit and never calls a
206
+ # model — the same path Claude Code's slash commands already take.
207
+ line=" $directive"
208
+ [ -n "$args" ] && line="$line $args"
209
+
210
+ body="$(jq -cn --arg m "${requested_model:-gpt-5.6-sol}" --arg c "$line" \
211
+ '{model:$m, messages:[{role:"user", content:$c}]}' 2>/dev/null)" || pass_through
212
+
213
+ # Identity headers only when the install has them: the router must never see a
214
+ # header with an empty value, and omitting them is what an unattributed install
215
+ # already does on every ordinary turn.
216
+ identity_args=()
217
+ [ -n "$user_email" ] && identity_args+=(-H "X-Weave-User-Email: $user_email")
218
+ [ -n "$user_name" ] && identity_args+=(-H "X-Weave-User-Name: $user_name")
219
+
220
+ response="$(curl -fsS --max-time 10 \
221
+ -H "Content-Type: application/json" \
222
+ -H "X-Weave-Router-Key: $router_key" \
223
+ -H "Session-Id: $session_id" \
224
+ -H "X-App: codex" \
225
+ ${identity_args[@]+"${identity_args[@]}"} \
226
+ -d "$body" \
227
+ "$url" 2>/dev/null)" || pass_through
228
+ [ -n "$response" ] || pass_through
229
+
230
+ # `strings` filters to the string type: jq -r would otherwise render an object
231
+ # or array as JSON, which is non-empty and would block the turn with garbage.
232
+ marker="$(jq -r '[.choices[0].message.content | strings] | first // ""' <<<"$response" 2>/dev/null)" || pass_through
233
+ marker="$(printf '%s' "$marker" | sed -e 's/\*\*//g' -e '/^[[:space:]]*$/d')"
234
+ [ -n "$marker" ] || pass_through
235
+
236
+ block "$marker"
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: router-session
3
+ description: "Print the session id that correlates this Codex session in Weave Router telemetry and logs."
4
+ ---
5
+
6
+ <!-- weave-router managed router-session skill -->
7
+
8
+ When the user invokes `$router-session`, run this skill's `scripts/emit.sh` using the
9
+ absolute path shown in this skill's `<path>` (its directory + `/scripts/emit.sh`).
10
+ It takes no arguments.
11
+
12
+ The script prints the session id on its own line. Report that id back in one line,
13
+ formatted as inline code so the user can copy it. Do not send a user message and do
14
+ not type a Codex slash command.
15
+
16
+ The router carries this id as `Session-Id` on every request and stores it for
17
+ analytics joins, so it is also the lookup key in the router dashboard.
18
+
19
+ The Weave Router also installs a `UserPromptSubmit` hook that answers
20
+ `$router-session` directly, with no model turn at all — that is the normal path,
21
+ and it works whether or not this skill runs.
22
+
23
+ This skill is only the fallback for sessions where the hook is unavailable, and it
24
+ needs `CODEX_SESSION_ID` in the environment. If that is unset the script exits
25
+ non-zero rather than reporting an id: the alternative is reading the newest rollout
26
+ transcript, which names a different session whenever two run at once. Report the
27
+ error as-is instead of guessing an id.
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env bash
2
+ # Print this Codex session's id. Local only -- no router call, no model turn.
3
+ set -uo pipefail
4
+
5
+ if [ -n "${CODEX_SESSION_ID:-}" ]; then
6
+ printf '%s\n' "$CODEX_SESSION_ID"
7
+ exit 0
8
+ fi
9
+
10
+ # No CODEX_SESSION_ID means there is no way to identify *this* session from here.
11
+ # Reading the newest rollout transcript would name whichever session wrote last,
12
+ # which is a different session whenever two run concurrently -- and a wrong id
13
+ # silently attributes feedback to someone else's session. Fail instead.
14
+ echo "session id unavailable: CODEX_SESSION_ID is not set in this environment." >&2
15
+ echo "The Weave Router's UserPromptSubmit hook answers \$router-session directly" >&2
16
+ echo "from the session id Codex gives it; re-run the installer to enable it." >&2
17
+ exit 1
package/codex-status.sh CHANGED
@@ -93,11 +93,6 @@ state_root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/codex"
93
93
  helper_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
94
94
  disabled_marker="$helper_dir/.weave-router-disabled"
95
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
96
 
102
97
  emit_title() {
103
98
  local title="$1"
@@ -157,10 +152,18 @@ cost_file_for() {
157
152
  # Resolved from the helper's own location first so a project-scope install never
158
153
  # reads (or leaks) the user-scope key: the project helper lives in the same
159
154
  # .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.
155
+ # and reads ~/.codex. Values are scoped to the [model_providers.weave] table so
156
+ # a key-shaped string the user wrote elsewhere in the file is never adopted. awk,
157
+ # not a TOML parser, because the Codex target deliberately does not require jq
158
+ # for config reads.
159
+ #
160
+ # Scoped to the table rather than the managed comment markers, and matching the
161
+ # header name quoted or bare, because Codex rewrites config.toml through a TOML
162
+ # serializer whenever it persists its own state: comments do not survive, so the
163
+ # markers vanish while the table remains, and the inline http_headers come back
164
+ # as a subtable with the header name unquoted. A marker-scoped, quoted-only read
165
+ # resolved nothing on any config Codex had touched, which silently dropped the
166
+ # savings figure from the title with no error anywhere.
164
167
  read_codex_endpoint() {
165
168
  local config=""
166
169
  # Project/custom installs name the helper weave-status.sh and keep it next
@@ -173,19 +176,45 @@ read_codex_endpoint() {
173
176
  config="$HOME/.codex/config.toml"
174
177
  fi
175
178
  [ -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 }
179
+ awk '
180
+ # Cut a TOML comment, honouring quoted strings so a # inside a value stays.
181
+ # A full-line comment reduces to empty and matches nothing below, so this
182
+ # replaces a separate skip rule -- and unlike one, it also catches a comment
183
+ # trailing another assignment, which the unanchored matches would otherwise
184
+ # read as live config on any line preceding the real value.
185
+ function weave_strip_comment(line, i, c, out, indq, insq, esc) {
186
+ out = ""
187
+ indq = 0
188
+ insq = 0
189
+ esc = 0
190
+ for (i = 1; i <= length(line); i++) {
191
+ c = substr(line, i, 1)
192
+ if (esc) { out = out c; esc = 0; continue }
193
+ # Only basic strings have escapes; a backslash in a literal string is
194
+ # data, so consuming the next character there would mis-track the quote.
195
+ if (indq && c == "\\") { out = out c; esc = 1; continue }
196
+ if (!insq && c == "\"") { indq = !indq; out = out c; continue }
197
+ if (!indq && c == "'"'"'") { insq = !insq; out = out c; continue }
198
+ if (c == "#" && !indq && !insq) break
199
+ out = out c
200
+ }
201
+ return out
202
+ }
203
+ { $0 = weave_strip_comment($0) }
204
+ /^[[:space:]]*\[/ {
205
+ in_provider = ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/)
206
+ next
207
+ }
208
+ !in_provider { next }
180
209
  match($0, /base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
181
210
  v = substr($0, RSTART, RLENGTH)
182
211
  sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
183
- url = v
212
+ if (url == "") url = v
184
213
  }
185
- match($0, /"X-Weave-Router-Key"[[:space:]]*=[[:space:]]*"[^"]*"/) {
214
+ match($0, /"?X-Weave-Router-Key"?[[:space:]]*=[[:space:]]*"[^"]*"/) {
186
215
  v = substr($0, RSTART, RLENGTH)
187
216
  sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
188
- key = v
217
+ if (key == "") key = v
189
218
  }
190
219
  END { if (url != "" && key != "") printf "%s\n%s\n", url, key }
191
220
  ' "$config" 2>/dev/null || true
package/directives.tsv CHANGED
@@ -7,7 +7,7 @@ router-feedback|rf|prompt|yes|yes|yes|no|manual|command,skill
7
7
  router-off||local-toggle|yes|yes|no|no|manual|command,skill
8
8
  router-on||local-toggle|yes|yes|no|no|manual|command,skill
9
9
  router-status||local-toggle|yes|yes|no|no|manual|command,skill
10
- router-session||prompt|yes|no|no|no|manual|command
10
+ router-session||prompt|yes|yes|no|no|manual|command,skill
11
11
  router-models|models|local-toggle|yes|yes|no|no|manual|command,skill
12
12
  disable-routing||local-toggle|no|yes|no|no|manual|skill
13
13
  beta||prompt|yes|no|no|yes|manual|command
package/install.sh CHANGED
@@ -515,12 +515,13 @@ write_codex_config() {
515
515
  printf '%s' "${s//\"/\\\"}"
516
516
  }
517
517
 
518
- 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
519
519
  esc_key="$(toml_escape "$block_key")"
520
520
  esc_email="$(toml_escape "$block_email")"
521
521
  esc_name="$(toml_escape "$block_name")"
522
522
  esc_url="$(toml_escape "$block_url")"
523
523
  esc_status="$(toml_escape "$codex_status_file")"
524
+ esc_directive="$(toml_escape "$codex_directive_file")"
524
525
 
525
526
  # Plant whichever identity values we have alongside the router key so the
526
527
  # router can attribute Codex traffic to a person on shared keys. Build the
@@ -573,6 +574,19 @@ type = "command"
573
574
  command = "${esc_status}"
574
575
  TOML
575
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
576
590
  fi
577
591
  local block
578
592
  block="$(cat <<TOML
@@ -596,15 +610,34 @@ TOML
596
610
 
597
611
  if [ -f "$config_file" ]; then
598
612
  local tmp; tmp="$(mktemp -t weave-codex.XXXXXX)"
599
- # Strip the managed block (between markers) plus any top-level
600
- # `model_provider =` outside it. We define "top-level" as everything
601
- # before the first `[section]` header. The awk handles both passes in
602
- # 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.
603
628
  awk -v begin="$WEAVE_CODEX_BEGIN_MARKER" -v end="$WEAVE_CODEX_END_MARKER" '
604
629
  $0 == begin { skip = 1; next }
605
630
  $0 == end { skip = 0; next }
606
631
  skip { next }
607
- /^[[: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 }
608
641
  !in_section && /^[[:space:]]*model_provider[[:space:]]*=/ { next }
609
642
  { print }
610
643
  ' "$config_file" >"$tmp"
@@ -1509,7 +1542,7 @@ router-feedback|rf|prompt|yes|yes|yes|no|manual|command,skill
1509
1542
  router-off||local-toggle|yes|yes|no|no|manual|command,skill
1510
1543
  router-on||local-toggle|yes|yes|no|no|manual|command,skill
1511
1544
  router-status||local-toggle|yes|yes|no|no|manual|command,skill
1512
- router-session||prompt|yes|no|no|no|manual|command
1545
+ router-session||prompt|yes|yes|no|no|manual|command,skill
1513
1546
  router-models|models|local-toggle|yes|yes|no|no|manual|command,skill
1514
1547
  disable-routing||local-toggle|no|yes|no|no|manual|skill
1515
1548
  beta||prompt|yes|no|no|yes|manual|command
@@ -1682,8 +1715,10 @@ elif [ "$target" = "codex" ]; then
1682
1715
  codex_config_file="$codex_dir/config.toml"
1683
1716
  if [ "$scope" = "user" ] && [ -z "$install_dir" ]; then
1684
1717
  codex_status_file="$settings_base/.weave/codex-status.sh"
1718
+ codex_directive_file="$settings_base/.weave/codex-directive.sh"
1685
1719
  else
1686
1720
  codex_status_file="$codex_dir/weave-status.sh"
1721
+ codex_directive_file="$codex_dir/weave-directive.sh"
1687
1722
  fi
1688
1723
  codex_status_disabled_marker="$(dirname "$codex_status_file")/.weave-router-disabled"
1689
1724
 
@@ -1848,10 +1883,19 @@ key_source_is_own() {
1848
1883
  read_codex_key() {
1849
1884
  local f="$1"
1850
1885
  key_source_is_own "$f" || return 0
1851
- awk -v begin="$WEAVE_CODEX_BEGIN_MARKER" -v end="$WEAVE_CODEX_END_MARKER" '
1852
- $0 == begin { inblk = 1; next }
1853
- $0 == end { inblk = 0; next }
1854
- 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:]]*"[^"]*"/) {
1855
1899
  hdr = substr($0, RSTART, RLENGTH)
1856
1900
  sub(/^.*=[[:space:]]*"/, "", hdr)
1857
1901
  sub(/"$/, "", hdr)
@@ -2019,11 +2063,19 @@ resolve_installed_endpoint() {
2019
2063
  return 0
2020
2064
  ;;
2021
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.
2022
2072
  if key_source_is_own "$codex_config_file"; then
2023
- found="$(awk -v begin="$WEAVE_CODEX_BEGIN_MARKER" -v end="$WEAVE_CODEX_END_MARKER" '
2024
- $0 == begin { inblk = 1; next }
2025
- $0 == end { inblk = 0; next }
2026
- 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:]]*"[^"]*"/) {
2027
2079
  line = substr($0, RSTART, RLENGTH)
2028
2080
  sub(/^.*=[[:space:]]*"/, "", line)
2029
2081
  sub(/"$/, "", line)
@@ -2947,6 +2999,12 @@ if [ "$mode" = "models" ] || [ "$mode" = "accounts" ] || [ "$mode" = "login" ] |
2947
2999
  # branches below so `set -u` holds on every path.
2948
3000
  models_base_source=""
2949
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}"
2950
3008
  # Editing model selection needs the endpoint and key of one specific install,
2951
3009
  # never the hosted defaults: a self-hosted user pointing at their own router
2952
3010
  # would otherwise silently edit the hosted one's installation.
@@ -3630,11 +3688,6 @@ state_root="${XDG_CACHE_HOME:-$HOME/.cache}/weave-router/codex"
3630
3688
  helper_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
3631
3689
  disabled_marker="$helper_dir/.weave-router-disabled"
3632
3690
  router_badge_sentinel=$'⁣⁠⁣⁠'
3633
- # Must stay verbatim in sync with install.sh / uninstall.sh: the endpoint read
3634
- # below is scoped to this block so a key-shaped string elsewhere in the user's
3635
- # config.toml is never adopted.
3636
- codex_begin_marker="# >>> weave-router managed (do not edit between markers) >>>"
3637
- codex_end_marker="# <<< weave-router managed <<<"
3638
3691
 
3639
3692
  emit_title() {
3640
3693
  local title="$1"
@@ -3694,10 +3747,18 @@ cost_file_for() {
3694
3747
  # Resolved from the helper's own location first so a project-scope install never
3695
3748
  # reads (or leaks) the user-scope key: the project helper lives in the same
3696
3749
  # .codex directory as its config, while the user-scope helper sits in ~/.weave
3697
- # and reads ~/.codex. Values are scoped to the managed block so a key-shaped
3698
- # string the user wrote elsewhere in the file is never adopted. awk, not a TOML
3699
- # parser, because the Codex target deliberately does not require jq for config
3700
- # 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.
3701
3762
  read_codex_endpoint() {
3702
3763
  local config=""
3703
3764
  # Project/custom installs name the helper weave-status.sh and keep it next
@@ -3710,19 +3771,45 @@ read_codex_endpoint() {
3710
3771
  config="$HOME/.codex/config.toml"
3711
3772
  fi
3712
3773
  [ -n "$config" ] || return 0
3713
- awk -v begin="$codex_begin_marker" -v end="$codex_end_marker" '
3714
- $0 == begin { inblk = 1; next }
3715
- $0 == end { inblk = 0; next }
3716
- !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 }
3717
3804
  match($0, /base_url[[:space:]]*=[[:space:]]*"[^"]*"/) {
3718
3805
  v = substr($0, RSTART, RLENGTH)
3719
3806
  sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
3720
- url = v
3807
+ if (url == "") url = v
3721
3808
  }
3722
- match($0, /"X-Weave-Router-Key"[[:space:]]*=[[:space:]]*"[^"]*"/) {
3809
+ match($0, /"?X-Weave-Router-Key"?[[:space:]]*=[[:space:]]*"[^"]*"/) {
3723
3810
  v = substr($0, RSTART, RLENGTH)
3724
3811
  sub(/^.*=[[:space:]]*"/, "", v); sub(/"$/, "", v)
3725
- key = v
3812
+ if (key == "") key = v
3726
3813
  }
3727
3814
  END { if (url != "" && key != "") printf "%s\n%s\n", url, key }
3728
3815
  ' "$config" 2>/dev/null || true
@@ -3920,11 +4007,294 @@ CODEX_STATUS_EOF
3920
4007
  ok "Codex status integration installed at $codex_status_file"
3921
4008
  }
3922
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
+
3923
4289
  if [ "$target" = "codex" ]; then
3924
4290
  if ! install_codex_status_script; then
3925
4291
  err "Cannot install the Codex status helper safely; refusing to write hooks that could execute unowned code."
3926
4292
  exit 1
3927
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
3928
4298
  write_codex_config "$codex_config_file" "$base_url" "$api_key" "$user_email" "$user_name"
3929
4299
  ok "Codex config written to $codex_config_file"
3930
4300
  remove_obsolete_codex_prompt_wrappers "$codex_dir/prompts"
@@ -3941,6 +4311,7 @@ if [ "$target" = "codex" ]; then
3941
4311
  for entry in \
3942
4312
  ".codex/config.toml" \
3943
4313
  ".codex/weave-status.sh" \
4314
+ ".codex/weave-directive.sh" \
3944
4315
  ".codex/.weave-router-disabled"
3945
4316
  do
3946
4317
  if [ ! -f "$gitignore" ] || ! grep -qxF "$entry" "$gitignore"; then
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weave-os/router",
3
- "version": "0.2.16",
3
+ "version": "0.2.17",
4
4
  "description": "One-command installer that points Claude Code, Codex, opencode, or pi at the Weave Router. For pi it also ships the routing extension, loaded via pi.extensions.",
5
5
  "bin": {
6
6
  "weave-router": "bin.js",
@@ -20,6 +20,7 @@
20
20
  "uninstall.sh",
21
21
  "cc-statusline.sh",
22
22
  "codex-status.sh",
23
+ "codex-directive.sh",
23
24
  "registry.sh",
24
25
  "directives.tsv",
25
26
  "commands/",
package/uninstall.sh CHANGED
@@ -27,7 +27,6 @@ set -euo pipefail
27
27
  scope="user"
28
28
  scope_explicit="false"
29
29
  install_dir=""
30
- script_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
31
30
 
32
31
  # ---------- directive registry (embedded) ----------
33
32
  #
@@ -45,7 +44,7 @@ router-feedback|rf|prompt|yes|yes|yes|no|manual|command,skill
45
44
  router-off||local-toggle|yes|yes|no|no|manual|command,skill
46
45
  router-on||local-toggle|yes|yes|no|no|manual|command,skill
47
46
  router-status||local-toggle|yes|yes|no|no|manual|command,skill
48
- router-session||prompt|yes|no|no|no|manual|command
47
+ router-session||prompt|yes|yes|no|no|manual|command,skill
49
48
  router-models|models|local-toggle|yes|yes|no|no|manual|command,skill
50
49
  disable-routing||local-toggle|no|yes|no|no|manual|skill
51
50
  beta||prompt|yes|no|no|yes|manual|command
@@ -206,11 +205,17 @@ fi
206
205
  WEAVE_CODEX_BEGIN_MARKER="# >>> weave-router managed (do not edit between markers) >>>"
207
206
  WEAVE_CODEX_END_MARKER="# <<< weave-router managed <<<"
208
207
 
209
- # strip_codex_block rewrites config.toml without the managed block and any
208
+ # strip_codex_block rewrites config.toml without the managed block, any
210
209
  # top-level `model_provider = "weave"` that lived outside the markers (which
211
- # can happen if the user copy-pasted our key into their own config). Other
212
- # top-level model_provider values are preserved so we don't yank a user back
213
- # into the OpenAI default when they meant to keep their own.
210
+ # can happen if the user copy-pasted our key into their own config), and any
211
+ # `[model_providers.weave]` table outside them. Other top-level model_provider
212
+ # values are preserved so we don't yank a user back into the OpenAI default
213
+ # when they meant to keep their own.
214
+ #
215
+ # The out-of-marker table has to go for the same reason install.sh strips it:
216
+ # Codex rewrites config.toml through a TOML serializer and our comment markers
217
+ # do not survive, so a marker-only uninstall reported success while leaving the
218
+ # provider -- and the router key inside it -- on disk.
214
219
  strip_codex_block() {
215
220
  local config_file="$1"
216
221
  local tmp; tmp="$(mktemp -t weave-codex-uninstall.XXXXXX)"
@@ -218,7 +223,15 @@ strip_codex_block() {
218
223
  $0 == begin { skip = 1; next }
219
224
  $0 == end { skip = 0; next }
220
225
  skip { next }
221
- /^[[:space:]]*\[/ { in_section = 1 }
226
+ /^[[:space:]]*\[/ {
227
+ in_section = 1
228
+ if ($0 ~ /^[[:space:]]*\[[[:space:]]*model_providers[[:space:]]*\.[[:space:]]*weave[[:space:]]*(\.[^]]*)?\][[:space:]]*(#.*)?$/) {
229
+ in_weave_provider = 1
230
+ next
231
+ }
232
+ in_weave_provider = 0
233
+ }
234
+ in_weave_provider { next }
222
235
  !in_section && /^[[:space:]]*model_provider[[:space:]]*=[[:space:]]*"weave"[[:space:]]*$/ { next }
223
236
  { print }
224
237
  ' "$config_file" >"$tmp"
@@ -245,6 +258,9 @@ if [ "$target" = "opencode" ]; then
245
258
  printf "Project directory to uninstall from [default: %s]: " "$default_project_dir"
246
259
  read -r project_dir_choice </dev/tty || project_dir_choice=""
247
260
  project_dir="${project_dir_choice:-$default_project_dir}"
261
+ # Expand a leading ~ since `read` doesn't.
262
+ # The pattern intentionally matches a literal tilde.
263
+ # shellcheck disable=SC2088
248
264
  case "$project_dir" in
249
265
  "~") project_dir="$HOME" ;;
250
266
  "~/"*) project_dir="$HOME/${project_dir#~/}" ;;
@@ -395,6 +411,9 @@ if [ "$target" = "pi" ]; then
395
411
  printf "Project directory to uninstall from [default: %s]: " "$default_project_dir"
396
412
  read -r project_dir_choice </dev/tty || project_dir_choice=""
397
413
  project_dir="${project_dir_choice:-$default_project_dir}"
414
+ # Expand a leading ~ since `read` doesn't.
415
+ # The pattern intentionally matches a literal tilde.
416
+ # shellcheck disable=SC2088
398
417
  case "$project_dir" in
399
418
  "~") project_dir="$HOME" ;;
400
419
  "~/"*) project_dir="$HOME/${project_dir#~/}" ;;
@@ -501,6 +520,9 @@ if [ "$target" = "codex" ]; then
501
520
  printf "Project directory to uninstall from [default: %s]: " "$default_project_dir"
502
521
  read -r project_dir_choice </dev/tty || project_dir_choice=""
503
522
  project_dir="${project_dir_choice:-$default_project_dir}"
523
+ # Expand a leading ~ since `read` doesn't.
524
+ # The pattern intentionally matches a literal tilde.
525
+ # shellcheck disable=SC2088
504
526
  case "$project_dir" in
505
527
  "~") project_dir="$HOME" ;;
506
528
  "~/"*) project_dir="$HOME/${project_dir#~/}" ;;
@@ -525,12 +547,15 @@ if [ "$target" = "codex" ]; then
525
547
  codex_config_file="$codex_dir/config.toml"
526
548
  if [ "$scope" = "user" ] && [ -z "$install_dir" ]; then
527
549
  codex_status_file="$HOME/.weave/codex-status.sh"
550
+ codex_directive_file="$HOME/.weave/codex-directive.sh"
528
551
  else
529
552
  codex_status_file="$codex_dir/weave-status.sh"
553
+ codex_directive_file="$codex_dir/weave-directive.sh"
530
554
  fi
531
555
  codex_status_disabled_marker="$(dirname "$codex_status_file")/.weave-router-disabled"
532
556
  refuse_if_symlink "$codex_config_file"
533
557
  refuse_if_symlink "$codex_status_file"
558
+ refuse_if_symlink "$codex_directive_file"
534
559
  refuse_if_symlink "$codex_status_disabled_marker"
535
560
 
536
561
  if [ -f "$codex_config_file" ]; then
@@ -567,6 +592,16 @@ if [ "$target" = "codex" ]; then
567
592
  fi
568
593
  fi
569
594
 
595
+ if [ -f "$codex_directive_file" ]; then
596
+ if grep -Fq '<!-- weave-router managed codex directive -->' "$codex_directive_file"; then
597
+ rm -f "$codex_directive_file"
598
+ ok "Removed $codex_directive_file"
599
+ rmdir "$(dirname "$codex_directive_file")" 2>/dev/null || true
600
+ else
601
+ warn "Leaving user-owned Codex directive helper at $codex_directive_file untouched."
602
+ fi
603
+ fi
604
+
570
605
  # Remove only the prompt files this installer owns; leave any user-authored
571
606
  # entries in prompts/ alone. The dir itself is dropped only if empty after.
572
607
  codex_prompts_dir="$codex_dir/prompts"
@@ -672,6 +707,9 @@ else
672
707
  printf "Project directory to uninstall from [default: %s]: " "$default_project_dir"
673
708
  read -r project_dir_choice </dev/tty || project_dir_choice=""
674
709
  project_dir="${project_dir_choice:-$default_project_dir}"
710
+ # Expand a leading ~ since `read` doesn't.
711
+ # The pattern intentionally matches a literal tilde.
712
+ # shellcheck disable=SC2088
675
713
  case "$project_dir" in
676
714
  "~") project_dir="$HOME" ;;
677
715
  "~/"*) project_dir="$HOME/${project_dir#~/}" ;;