@weave-os/router 0.2.17 → 0.2.19

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weave-os/router",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
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,7 +20,7 @@
20
20
  "uninstall.sh",
21
21
  "cc-statusline.sh",
22
22
  "codex-status.sh",
23
- "codex-directive.sh",
23
+ "codex-toggle.sh",
24
24
  "registry.sh",
25
25
  "directives.tsv",
26
26
  "commands/",
package/uninstall.sh CHANGED
@@ -216,6 +216,140 @@ WEAVE_CODEX_END_MARKER="# <<< weave-router managed <<<"
216
216
  # Codex rewrites config.toml through a TOML serializer and our comment markers
217
217
  # do not survive, so a marker-only uninstall reported success while leaving the
218
218
  # provider -- and the router key inside it -- on disk.
219
+ # strip_weave_codex_hooks removes every hook registration this installer owns,
220
+ # matched by helper filename. Marker-scoped removal is not enough: Codex
221
+ # rewrites config.toml through a TOML serializer and our registrations often end
222
+ # up outside the markers, which used to leave them behind after an uninstall.
223
+ # Removal is per sub-entry so a group shared with a third party keeps theirs.
224
+ # Ownership contract for the Codex hook helpers. Every rule here was a bug
225
+ # first; keep them together so the next change has the whole set.
226
+ #
227
+ # 1. Ours is decided per path by that helper's EXACT marker. A prefix match
228
+ # lets the status marker vouch for the directive path, and the two
229
+ # deletion sites check exact markers -- so the strip would unwire a file
230
+ # it then declines to delete.
231
+ # 2. A missing file is ours. Its registration points at nothing, which is
232
+ # residue we left behind.
233
+ # 3. What a symlink means depends on the helper's lifecycle, so the caller
234
+ # says which it is.
235
+ # rewrite (status): the file is rewritten in place and never deleted, so
236
+ # the link is followed to read the marker. Disowning it instead leaves
237
+ # the old registrations while the managed block adds a fresh pair,
238
+ # stacking the duplicates this strip exists to remove.
239
+ # delete (directive): the file is removed, and removal refuses to act
240
+ # through a link. Claiming one would strip the registration and then
241
+ # decline the delete, leaving a helper Codex no longer runs -- rule 4
242
+ # violated in the one case it exists for.
243
+ # Either way the check precedes -e, which is false for a dangling link: it
244
+ # then fails the marker test and stays the user's, rather than being
245
+ # claimed by rule 2.
246
+ # 4. Registration and file must be decided together. Removing one while
247
+ # keeping the other leaves a script Codex never runs, with nothing on
248
+ # screen to explain it.
249
+ # 5. Compare decoded paths. The command value is a TOML basic string and the
250
+ # writer escapes it, so a raw comparison misses any path with a quote or
251
+ # backslash.
252
+ # warn_if_symlink reports a symlinked path and returns non-zero so the caller
253
+ # can skip just that file. refuse_if_symlink exits the process, which is right
254
+ # for a path we are about to write but wrong for these helpers: one symlinked
255
+ # helper would abort the whole run, stranding the config rewrite that is the
256
+ # actual work. Neither is deleted through a link either way.
257
+ warn_if_symlink() {
258
+ local target="$1"
259
+ [ -L "$target" ] || return 0
260
+ warn "$target is a symlink (-> $(readlink "$target")); leaving it untouched."
261
+ return 1
262
+ }
263
+
264
+ weave_owns_codex_helper() {
265
+ local path="$1" marker="$2" lifecycle="$3"
266
+ [ -n "$path" ] && [ -n "$marker" ] && [ -n "$lifecycle" ] || return 1
267
+ if [ -L "$path" ]; then
268
+ [ "$lifecycle" = "rewrite" ] || return 1
269
+ grep -Fq "$marker" "$path" 2>/dev/null
270
+ return $?
271
+ fi
272
+ [ -e "$path" ] || return 0
273
+ grep -Fq "$marker" "$path" 2>/dev/null
274
+ }
275
+
276
+ # weave_owned_codex_helpers prints, one per line, whichever of the two helper
277
+ # paths this installation may unwire.
278
+ weave_owned_codex_helpers() {
279
+ weave_owns_codex_helper "${codex_status_file:-}" '<!-- weave-router managed codex status -->' rewrite \
280
+ && printf '%s\n' "$codex_status_file"
281
+ weave_owns_codex_helper "${codex_directive_file:-}" '<!-- weave-router managed codex directive -->' delete \
282
+ && printf '%s\n' "$codex_directive_file"
283
+ return 0
284
+ }
285
+
286
+ strip_weave_codex_hooks() {
287
+ local config_file="$1"; shift
288
+ [ -f "$config_file" ] || return 0
289
+ # Exact paths, never a filename pattern: a third party's hook is free to be
290
+ # called weave-status.sh, and matching on the basename would delete it.
291
+ local owned="" candidate
292
+ for candidate in "$@"; do
293
+ [ -n "$candidate" ] || continue
294
+ # A unit separator, not a newline: BSD awk rejects an embedded newline in a
295
+ # -v value outright ("newline in string"), which silently disabled the whole
296
+ # pass on macOS.
297
+ owned="${owned}${candidate}$(printf '\037')"
298
+ done
299
+ [ -n "$owned" ] || return 0
300
+ local tmp; tmp="$(mktemp -t weave-codex-hooks.XXXXXX)"
301
+ awk -v owned="$owned" '
302
+ BEGIN {
303
+ n = split(owned, list, "\037")
304
+ for (i = 1; i <= n; i++) if (list[i] != "") own[list[i]] = 1
305
+ }
306
+ function flush_sub( i) {
307
+ if (sub_n == 0) return
308
+ if (!sub_is_weave) {
309
+ if (group_pending != "") {
310
+ print group_pending
311
+ group_pending = ""
312
+ if (group_blank) { print ""; group_blank = 0 }
313
+ }
314
+ for (i = 1; i <= sub_n; i++) print sub_line[i]
315
+ }
316
+ sub_n = 0
317
+ sub_is_weave = 0
318
+ }
319
+ function close_group() { flush_sub(); group_pending = ""; group_blank = 0 }
320
+ /^[[:space:]]*\[\[hooks\.[A-Za-z]+\.hooks\]\][[:space:]]*$/ {
321
+ flush_sub(); sub_n = 1; sub_line[1] = $0; next
322
+ }
323
+ /^[[:space:]]*\[\[hooks\.[A-Za-z]+\]\][[:space:]]*$/ {
324
+ close_group(); group_pending = $0; next
325
+ }
326
+ /^[[:space:]]*\[/ { close_group(); print; next }
327
+ {
328
+ if (sub_n > 0) {
329
+ sub_line[++sub_n] = $0
330
+ if (match($0, /^[[:space:]]*command[[:space:]]*=[[:space:]]*"([^"\\]|\\.)*"/)) {
331
+ v = substr($0, RSTART, RLENGTH)
332
+ sub(/^[^"]*"/, "", v); sub(/"$/, "", v)
333
+ # write_codex_config escapes the path before writing it, so undo that
334
+ # before comparing; quotes first, then backslashes.
335
+ gsub(/\\"/, "\"", v)
336
+ gsub(/\\\\/, "\\", v)
337
+ if (v in own) sub_is_weave = 1
338
+ }
339
+ next
340
+ }
341
+ if (group_pending != "" && $0 ~ /^[[:space:]]*$/) { group_blank = 1; next }
342
+ if (group_pending != "") {
343
+ print group_pending; group_pending = ""
344
+ if (group_blank) { print ""; group_blank = 0 }
345
+ }
346
+ print
347
+ }
348
+ END { close_group() }
349
+ ' "$config_file" >"$tmp" && mv "$tmp" "$config_file"
350
+ rm -f "$tmp" 2>/dev/null || true
351
+ }
352
+
219
353
  strip_codex_block() {
220
354
  local config_file="$1"
221
355
  local tmp; tmp="$(mktemp -t weave-codex-uninstall.XXXXXX)"
@@ -236,6 +370,13 @@ strip_codex_block() {
236
370
  { print }
237
371
  ' "$config_file" >"$tmp"
238
372
  mv "$tmp" "$config_file"
373
+ local owned_helpers=()
374
+ while IFS= read -r owned_helper; do
375
+ [ -n "$owned_helper" ] && owned_helpers+=("$owned_helper")
376
+ done <<EOF
377
+ $(weave_owned_codex_helpers)
378
+ EOF
379
+ strip_weave_codex_hooks "$config_file" ${owned_helpers[@]+"${owned_helpers[@]}"}
239
380
  }
240
381
 
241
382
  # ---------- opencode uninstall path ----------
@@ -554,9 +695,10 @@ if [ "$target" = "codex" ]; then
554
695
  fi
555
696
  codex_status_disabled_marker="$(dirname "$codex_status_file")/.weave-router-disabled"
556
697
  refuse_if_symlink "$codex_config_file"
557
- refuse_if_symlink "$codex_status_file"
558
- refuse_if_symlink "$codex_directive_file"
559
698
  refuse_if_symlink "$codex_status_disabled_marker"
699
+ # The helpers are checked at their own removal sites instead. Refusing here
700
+ # exits before strip_codex_block, so one symlinked helper left the config
701
+ # wired to a router the uninstall had just been asked to remove.
560
702
 
561
703
  if [ -f "$codex_config_file" ]; then
562
704
  strip_codex_block "$codex_config_file"
@@ -581,7 +723,7 @@ if [ "$target" = "codex" ]; then
581
723
  mv "$tmp" "$codex_config_file"
582
724
  fi
583
725
 
584
- if [ -f "$codex_status_file" ]; then
726
+ if [ -f "$codex_status_file" ] && warn_if_symlink "$codex_status_file"; then
585
727
  if grep -Fq '<!-- weave-router managed codex status -->' "$codex_status_file"; then
586
728
  rm -f "$codex_status_file"
587
729
  rm -f "$codex_status_disabled_marker"
@@ -592,7 +734,7 @@ if [ "$target" = "codex" ]; then
592
734
  fi
593
735
  fi
594
736
 
595
- if [ -f "$codex_directive_file" ]; then
737
+ if [ -f "$codex_directive_file" ] && warn_if_symlink "$codex_directive_file"; then
596
738
  if grep -Fq '<!-- weave-router managed codex directive -->' "$codex_directive_file"; then
597
739
  rm -f "$codex_directive_file"
598
740
  ok "Removed $codex_directive_file"
@@ -1,236 +0,0 @@
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"