@weave-os/router 0.2.25 → 0.2.26
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/README.md +7 -7
- package/cc-statusline.sh +2 -2
- package/install.sh +65 -52
- package/package.json +1 -2
- package/pi-router/src/pricing.generated.ts +3 -3
- package/uninstall.sh +30 -22
- package/opencode-weave/README.md +0 -128
- package/opencode-weave/package.json +0 -20
- package/opencode-weave/src/classifier-thread.ts +0 -145
- package/opencode-weave/src/directives.ts +0 -72
- package/opencode-weave/src/index.ts +0 -188
package/README.md
CHANGED
|
@@ -129,13 +129,13 @@ Four install targets:
|
|
|
129
129
|
- **opencode** (`--opencode`) — merges a Responses-format `provider.weave`
|
|
130
130
|
entry backed by `@ai-sdk/openai` into
|
|
131
131
|
`~/.config/opencode/opencode.json` (or `<repo>/opencode.json` with
|
|
132
|
-
`--scope project`).
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
132
|
+
`--scope project`). OpenCode major version 2 is required when the CLI is
|
|
133
|
+
installed and available on `PATH`. Installation activates `weave/auto` and
|
|
134
|
+
parks any prior default model so `off` and uninstall can restore it exactly.
|
|
135
|
+
The installer uses OpenCode's native Responses provider and session headers;
|
|
136
|
+
no plugin is installed. Re-install rewrites only the managed provider and
|
|
137
|
+
removes any stale v1 plugin registration/files while preserving unrelated
|
|
138
|
+
providers, MCP servers, agents, and plugins.
|
|
139
139
|
- **pi** (`--pi`) — registers the `weave` provider and installs this package as
|
|
140
140
|
a pi extension. Stock pi then gets the Loom startup header, Wooly's animated
|
|
141
141
|
mascot, the persistent actual-route display, cumulative session savings,
|
package/cc-statusline.sh
CHANGED
|
@@ -659,8 +659,8 @@ prices='{
|
|
|
659
659
|
"claude-sonnet-4-6": 0.1,
|
|
660
660
|
"claude-sonnet-5": 0.1,
|
|
661
661
|
"deepseek/deepseek-v4-flash": 0.2,
|
|
662
|
-
"deepseek/deepseek-v4-pro": 0.
|
|
663
|
-
"deepseek/deepseek-v4-pro-0813": 0.
|
|
662
|
+
"deepseek/deepseek-v4-pro": 0.0862,
|
|
663
|
+
"deepseek/deepseek-v4-pro-0813": 0.0862,
|
|
664
664
|
"deepseek/deepseek-v4.1-flash": 0.031818181818181815,
|
|
665
665
|
"gemini-2.0-flash": 0.25,
|
|
666
666
|
"gemini-2.0-flash-lite": 0.25,
|
package/install.sh
CHANGED
|
@@ -361,6 +361,28 @@ require_cmd() {
|
|
|
361
361
|
fi
|
|
362
362
|
}
|
|
363
363
|
|
|
364
|
+
# check_opencode_major_version rejects OpenCode versions whose config schema or
|
|
365
|
+
# provider contract is incompatible with this installer. A missing executable
|
|
366
|
+
# is handled by the target-specific warning below so the installer can still
|
|
367
|
+
# prepare a config before OpenCode is installed.
|
|
368
|
+
check_opencode_major_version() {
|
|
369
|
+
local version version_line major
|
|
370
|
+
if ! version="$(opencode --version 2>/dev/null)"; then
|
|
371
|
+
err "Unable to determine the installed opencode version; 'opencode --version' failed. OpenCode major version 2 is required."
|
|
372
|
+
return 1
|
|
373
|
+
fi
|
|
374
|
+
version_line="$(printf '%s\n' "$version" | sed -n '1p' | tr -d '\r')"
|
|
375
|
+
major="$(printf '%s\n' "$version_line" | sed -nE 's/^[^0-9]*([0-9]+)(\..*)?$/\1/p')"
|
|
376
|
+
if [ -z "$major" ]; then
|
|
377
|
+
err "Unable to determine the installed opencode major version from '${version_line:-unknown}'. OpenCode major version 2 is required."
|
|
378
|
+
return 1
|
|
379
|
+
fi
|
|
380
|
+
if [ "$major" != "2" ]; then
|
|
381
|
+
err "OpenCode major version 2 is required; detected ${version_line:-unknown}."
|
|
382
|
+
return 1
|
|
383
|
+
fi
|
|
384
|
+
}
|
|
385
|
+
|
|
364
386
|
# Refuse to write through a symlink. Project scope reads the install path from
|
|
365
387
|
# the user's git repo; a malicious checkout could ship `.claude/settings.json`
|
|
366
388
|
# (or `.claude/` itself) as a symlink to e.g. `~/.ssh/authorized_keys`, and
|
|
@@ -999,15 +1021,13 @@ EOF
|
|
|
999
1021
|
}
|
|
1000
1022
|
|
|
1001
1023
|
# write_opencode_config merges the managed Weave provider into opencode's
|
|
1002
|
-
# opencode.json
|
|
1003
|
-
#
|
|
1004
|
-
# this provider and its router key:
|
|
1024
|
+
# opencode.json. Subscription enrollment is handled by the router's login
|
|
1025
|
+
# command, so opencode only needs this provider and its router key:
|
|
1005
1026
|
# - provider.weave : OpenAI/Responses-shaped (@ai-sdk/openai → /v1/responses).
|
|
1006
1027
|
# The single request provider. The router routes every
|
|
1007
1028
|
# turn across the models the router can serve. The default.
|
|
1008
|
-
# Re-running rewrites the block in-place via jq
|
|
1009
|
-
#
|
|
1010
|
-
# directive hooks, but has no login or subscription-header transport.
|
|
1029
|
+
# Re-running rewrites the block in-place via jq, strips legacy provider blocks
|
|
1030
|
+
# and removes the obsolete v1 plugin registration and files.
|
|
1011
1031
|
#
|
|
1012
1032
|
# Usage: write_opencode_config <config_file_path> <base_url> <api_key> [user_email] [user_name]
|
|
1013
1033
|
write_opencode_config() {
|
|
@@ -1065,29 +1085,6 @@ write_opencode_config() {
|
|
|
1065
1085
|
}
|
|
1066
1086
|
')"
|
|
1067
1087
|
|
|
1068
|
-
# Drop the routing plugin next to the config and register its absolute path
|
|
1069
|
-
# so it loads regardless of OpenCode scope. It contains lifecycle,
|
|
1070
|
-
# classifier, and directive hooks; managed subscription enrollment lives in
|
|
1071
|
-
# the router's login command and is never transported in request headers.
|
|
1072
|
-
local plugin_dir plugin_spec plugin_src plugin_directives_src plugin_classifier_src plugin_arg=""
|
|
1073
|
-
plugin_dir="$(cd "$(dirname "$config_file")" && pwd)/.weave"
|
|
1074
|
-
plugin_spec="$plugin_dir/opencode-weave.ts"
|
|
1075
|
-
plugin_src="$script_dir/opencode-weave/src/index.ts"
|
|
1076
|
-
plugin_directives_src="$script_dir/opencode-weave/src/directives.ts"
|
|
1077
|
-
plugin_classifier_src="$script_dir/opencode-weave/src/classifier-thread.ts"
|
|
1078
|
-
if [ -f "$plugin_src" ] && [ -f "$plugin_directives_src" ] && [ -f "$plugin_classifier_src" ]; then
|
|
1079
|
-
mkdir -p "$plugin_dir"
|
|
1080
|
-
cp "$plugin_src" "$plugin_spec"
|
|
1081
|
-
chmod 644 "$plugin_spec"
|
|
1082
|
-
cp "$plugin_directives_src" "$plugin_dir/directives.ts"
|
|
1083
|
-
chmod 644 "$plugin_dir/directives.ts"
|
|
1084
|
-
cp "$plugin_classifier_src" "$plugin_dir/classifier-thread.ts"
|
|
1085
|
-
chmod 644 "$plugin_dir/classifier-thread.ts"
|
|
1086
|
-
plugin_arg="$plugin_spec"
|
|
1087
|
-
else
|
|
1088
|
-
warn "opencode routing plugin source not found at $plugin_src — skipping lifecycle and classifier hooks. (Use a packaged 'npx $npm_package_name' install.)"
|
|
1089
|
-
fi
|
|
1090
|
-
|
|
1091
1088
|
# Installing must actually activate the router. Preserve a prior direct model
|
|
1092
1089
|
# beside the config so off/uninstall can restore the user's exact choice.
|
|
1093
1090
|
local parked_file previous_model
|
|
@@ -1107,28 +1104,40 @@ write_opencode_config() {
|
|
|
1107
1104
|
esac
|
|
1108
1105
|
fi
|
|
1109
1106
|
|
|
1107
|
+
# Validate cleanup paths before the key-bearing config is written.
|
|
1108
|
+
local legacy_plugin_dir legacy_plugin_file legacy_plugin_files="opencode-weave.ts directives.ts classifier-thread.ts"
|
|
1109
|
+
legacy_plugin_dir="$(dirname "$config_file")/.weave"
|
|
1110
|
+
refuse_if_symlink "$legacy_plugin_dir"
|
|
1111
|
+
for legacy_plugin_file in $legacy_plugin_files; do
|
|
1112
|
+
refuse_if_symlink "$legacy_plugin_dir/$legacy_plugin_file"
|
|
1113
|
+
done
|
|
1114
|
+
|
|
1110
1115
|
# Merge into any existing opencode.json. We always overwrite provider.weave
|
|
1111
1116
|
# so re-install reflects the latest key/identity, but we leave the rest of the
|
|
1112
1117
|
# file (other providers, mcp, agent settings) untouched. The managed model is
|
|
1113
1118
|
# always weave/auto; a prior direct choice was parked above for exact restore.
|
|
1114
1119
|
#
|
|
1115
|
-
# Legacy subscription providers are
|
|
1116
|
-
#
|
|
1117
|
-
# bundled source is available, while removing stale duplicate registrations.
|
|
1120
|
+
# Legacy subscription providers and the v1 plugin are removed during the
|
|
1121
|
+
# migration; unrelated providers and plugins remain untouched.
|
|
1118
1122
|
local merged
|
|
1119
1123
|
if [ -f "$config_file" ]; then
|
|
1120
1124
|
merged="$(jq \
|
|
1121
1125
|
--argjson block "$block" \
|
|
1122
|
-
--arg plugin "$plugin_arg" \
|
|
1123
1126
|
'
|
|
1124
1127
|
.provider = ((.provider // {}) | .weave = $block)
|
|
1125
1128
|
| (.provider |= del(."weave-codex"))
|
|
1126
1129
|
| (.provider |= del(."weave-claude"))
|
|
1127
|
-
| (if
|
|
1128
|
-
then .
|
|
1129
|
-
else
|
|
1130
|
-
|
|
1131
|
-
|
|
1130
|
+
| (if (.providers | type) == "object"
|
|
1131
|
+
then .providers |= del(.weave, ."weave-codex", ."weave-claude")
|
|
1132
|
+
else .
|
|
1133
|
+
end)
|
|
1134
|
+
| (if (.providers | type) == "object" and (.providers | length) == 0
|
|
1135
|
+
then del(.providers)
|
|
1136
|
+
else .
|
|
1137
|
+
end)
|
|
1138
|
+
| (if (.plugin | type) == "array"
|
|
1139
|
+
then .plugin |= map(select((tostring | test("(^|/)opencode-weave\\.ts$")) | not))
|
|
1140
|
+
else .
|
|
1132
1141
|
end)
|
|
1133
1142
|
| (if (.plugin | type) == "array" and (.plugin | length) == 0 then del(.plugin) else . end)
|
|
1134
1143
|
| .model = "weave/auto"
|
|
@@ -1137,20 +1146,24 @@ write_opencode_config() {
|
|
|
1137
1146
|
else
|
|
1138
1147
|
merged="$(jq -n \
|
|
1139
1148
|
--argjson block "$block" \
|
|
1140
|
-
--arg plugin "$plugin_arg" \
|
|
1141
1149
|
'
|
|
1142
1150
|
{
|
|
1143
1151
|
"$schema": "https://opencode.ai/config.json",
|
|
1144
1152
|
model: "weave/auto",
|
|
1145
1153
|
provider: { weave: $block }
|
|
1146
1154
|
}
|
|
1147
|
-
| (if $plugin != "" then .plugin = [$plugin] else . end)
|
|
1148
1155
|
')"
|
|
1149
1156
|
fi
|
|
1150
|
-
|
|
1151
|
-
# 0600
|
|
1152
|
-
#
|
|
1153
|
-
chmod 600 "$config_file"
|
|
1157
|
+
|
|
1158
|
+
# 0600 before the key lands: even at user scope, mode 644 would leak the key
|
|
1159
|
+
# to any local user on a shared box.
|
|
1160
|
+
[ ! -f "$config_file" ] || chmod 600 "$config_file"
|
|
1161
|
+
(umask 077 && printf '%s\n' "$merged" >"$config_file")
|
|
1162
|
+
|
|
1163
|
+
for legacy_plugin_file in $legacy_plugin_files; do
|
|
1164
|
+
[ ! -f "$legacy_plugin_dir/$legacy_plugin_file" ] || rm -f "$legacy_plugin_dir/$legacy_plugin_file"
|
|
1165
|
+
done
|
|
1166
|
+
rmdir "$legacy_plugin_dir" 2>/dev/null || true
|
|
1154
1167
|
}
|
|
1155
1168
|
|
|
1156
1169
|
# write_pi_models_config merges a managed `weave` provider into pi's
|
|
@@ -1831,8 +1844,10 @@ case "$target" in
|
|
|
1831
1844
|
;;
|
|
1832
1845
|
opencode)
|
|
1833
1846
|
if ! command -v opencode >/dev/null 2>&1; then
|
|
1834
|
-
warn "'opencode' not found on PATH. Install from https://opencode.ai (
|
|
1847
|
+
warn "'opencode' not found on PATH. Install OpenCode v2 from https://opencode.ai (Homebrew: 'brew install anomalyco/tap/opencode-v2'), then re-run this script."
|
|
1835
1848
|
warn "Continuing — opencode.json will be written and will take effect once opencode is installed."
|
|
1849
|
+
elif ! check_opencode_major_version; then
|
|
1850
|
+
exit 1
|
|
1836
1851
|
fi
|
|
1837
1852
|
;;
|
|
1838
1853
|
pi)
|
|
@@ -5055,24 +5070,22 @@ if [ "$target" = "opencode" ]; then
|
|
|
5055
5070
|
|
|
5056
5071
|
# Project scope: the per-teammate config carries the router key, so it
|
|
5057
5072
|
# stays out of git. Same reasoning as the Codex path — base URL is shared,
|
|
5058
|
-
# but the key is per-person
|
|
5059
|
-
# config references it by absolute path), so ignore it alongside.
|
|
5073
|
+
# but the key is per-person, so ignore the config alongside.
|
|
5060
5074
|
if [ "$scope" = "project" ] && [ -z "$install_dir" ] && [ -n "${git_root:-}" ]; then
|
|
5061
5075
|
gitignore="$git_root/.gitignore"
|
|
5062
5076
|
refuse_if_symlink "$gitignore"
|
|
5063
5077
|
for entry in \
|
|
5064
5078
|
"opencode.json" \
|
|
5065
|
-
".weave/" \
|
|
5066
5079
|
".weave-parked.json"
|
|
5067
5080
|
do
|
|
5068
5081
|
if [ ! -f "$gitignore" ] || ! grep -qxF "$entry" "$gitignore"; then
|
|
5069
5082
|
printf '%s\n' "$entry" >>"$gitignore"
|
|
5070
5083
|
fi
|
|
5071
5084
|
done
|
|
5072
|
-
ok "Updated $gitignore (ignored opencode.json
|
|
5085
|
+
ok "Updated $gitignore (ignored opencode.json)"
|
|
5073
5086
|
fi
|
|
5074
5087
|
|
|
5075
|
-
#
|
|
5088
|
+
# Native slash command files: opencode discovers commands in *.md files under
|
|
5076
5089
|
# ~/.config/opencode/commands/ (user scope) and .opencode/commands/ (project
|
|
5077
5090
|
# scope). Install command wrappers for /rf (±), /force-model, /unforce-model
|
|
5078
5091
|
# so typing /rf + in the TUI expands to /router-feedback + and reaches the
|
|
@@ -5829,8 +5842,8 @@ prices='{
|
|
|
5829
5842
|
"claude-sonnet-4-6": 0.1,
|
|
5830
5843
|
"claude-sonnet-5": 0.1,
|
|
5831
5844
|
"deepseek/deepseek-v4-flash": 0.2,
|
|
5832
|
-
"deepseek/deepseek-v4-pro": 0.
|
|
5833
|
-
"deepseek/deepseek-v4-pro-0813": 0.
|
|
5845
|
+
"deepseek/deepseek-v4-pro": 0.0862,
|
|
5846
|
+
"deepseek/deepseek-v4-pro-0813": 0.0862,
|
|
5834
5847
|
"deepseek/deepseek-v4.1-flash": 0.031818181818181815,
|
|
5835
5848
|
"gemini-2.0-flash": 0.25,
|
|
5836
5849
|
"gemini-2.0-flash-lite": 0.25,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weave-os/router",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.26",
|
|
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",
|
|
@@ -26,7 +26,6 @@
|
|
|
26
26
|
"commands/",
|
|
27
27
|
"codex-skills/",
|
|
28
28
|
"pi-router/",
|
|
29
|
-
"opencode-weave/",
|
|
30
29
|
"README.md",
|
|
31
30
|
"LICENSE",
|
|
32
31
|
"NOTICE"
|
|
@@ -7,7 +7,7 @@ export interface ModelPricing {
|
|
|
7
7
|
cacheReadMultiplier: number;
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
export const PRICING_VERSION = "catalog-sha256:
|
|
10
|
+
export const PRICING_VERSION = "catalog-sha256:128e641ea3a4ffe9";
|
|
11
11
|
|
|
12
12
|
export const MODEL_PRICING: Readonly<Record<string, ModelPricing>> = Object.freeze({
|
|
13
13
|
"claude-fable-5": { inputUsdPerMillion: 10, outputUsdPerMillion: 50, cacheReadMultiplier: 0.1 },
|
|
@@ -25,8 +25,8 @@ export const MODEL_PRICING: Readonly<Record<string, ModelPricing>> = Object.free
|
|
|
25
25
|
"claude-sonnet-4-6": { inputUsdPerMillion: 3, outputUsdPerMillion: 15, cacheReadMultiplier: 0.1 },
|
|
26
26
|
"claude-sonnet-5": { inputUsdPerMillion: 3, outputUsdPerMillion: 15, cacheReadMultiplier: 0.1 },
|
|
27
27
|
"deepseek/deepseek-v4-flash": { inputUsdPerMillion: 0.1134, outputUsdPerMillion: 0.2791, cacheReadMultiplier: 0.2 },
|
|
28
|
-
"deepseek/deepseek-v4-pro": { inputUsdPerMillion: 1.74, outputUsdPerMillion: 3.48, cacheReadMultiplier: 0.
|
|
29
|
-
"deepseek/deepseek-v4-pro-0813": { inputUsdPerMillion: 1.74, outputUsdPerMillion: 3.48, cacheReadMultiplier: 0.
|
|
28
|
+
"deepseek/deepseek-v4-pro": { inputUsdPerMillion: 1.74, outputUsdPerMillion: 3.48, cacheReadMultiplier: 0.0862 },
|
|
29
|
+
"deepseek/deepseek-v4-pro-0813": { inputUsdPerMillion: 1.74, outputUsdPerMillion: 3.48, cacheReadMultiplier: 0.0862 },
|
|
30
30
|
"deepseek/deepseek-v4.1-flash": { inputUsdPerMillion: 0.22, outputUsdPerMillion: 0.66, cacheReadMultiplier: 0.031818181818181815 },
|
|
31
31
|
"gemini-2.0-flash": { inputUsdPerMillion: 0.1, outputUsdPerMillion: 0.4, cacheReadMultiplier: 0.25 },
|
|
32
32
|
"gemini-2.0-flash-lite": { inputUsdPerMillion: 0.075, outputUsdPerMillion: 0.3, cacheReadMultiplier: 0.25 },
|
package/uninstall.sh
CHANGED
|
@@ -664,27 +664,38 @@ if [ "$target" = "opencode" ]; then
|
|
|
664
664
|
opencode_direct_model="$(jq -r '.direct_model // empty' "$opencode_parked" 2>/dev/null || true)"
|
|
665
665
|
fi
|
|
666
666
|
|
|
667
|
-
#
|
|
668
|
-
#
|
|
667
|
+
# Older installers registered a v1 plugin in opencode.json and copied its
|
|
668
|
+
# sources into .weave/. Remove those exact legacy registrations and assets.
|
|
669
669
|
if [ -d "$opencode_dir" ]; then
|
|
670
|
-
|
|
670
|
+
opencode_plugin_dir="$(cd "$opencode_dir" && pwd)/.weave"
|
|
671
671
|
else
|
|
672
|
-
|
|
672
|
+
opencode_plugin_dir="$opencode_dir/.weave"
|
|
673
673
|
fi
|
|
674
674
|
|
|
675
675
|
report_opencode_uninstall_event "$opencode_config_file" || true
|
|
676
676
|
if [ -f "$opencode_config_file" ]; then
|
|
677
677
|
# Strip every managed provider (`weave`, `weave-claude`, and the legacy
|
|
678
|
-
# `weave-codex` from pre-upgrade installs), remove
|
|
679
|
-
#
|
|
678
|
+
# `weave-codex` from pre-upgrade installs), remove any stale legacy plugin
|
|
679
|
+
# registration, and restore the direct model parked during
|
|
680
680
|
# install. Other providers, direct models selected while routing was off,
|
|
681
681
|
# other plugins, and unrelated keys are preserved.
|
|
682
|
-
cleaned="$(jq --arg
|
|
682
|
+
cleaned="$(jq --arg direct_model "$opencode_direct_model" '
|
|
683
683
|
(if .provider.weave then del(.provider.weave) else . end)
|
|
684
684
|
| (if .provider["weave-claude"] then del(.provider["weave-claude"]) else . end)
|
|
685
685
|
| (if .provider["weave-codex"] then del(.provider["weave-codex"]) else . end)
|
|
686
686
|
| (if (.provider // {}) == {} then del(.provider) else . end)
|
|
687
|
-
| (if (.
|
|
687
|
+
| (if (.providers | type) == "object"
|
|
688
|
+
then .providers |= del(.weave, ."weave-codex", ."weave-claude")
|
|
689
|
+
else .
|
|
690
|
+
end)
|
|
691
|
+
| (if (.providers | type) == "object" and (.providers | length) == 0
|
|
692
|
+
then del(.providers)
|
|
693
|
+
else .
|
|
694
|
+
end)
|
|
695
|
+
| (if (.plugin | type) == "array"
|
|
696
|
+
then .plugin |= map(select((tostring | test("(^|/)opencode-weave\\.ts$")) | not))
|
|
697
|
+
else .
|
|
698
|
+
end)
|
|
688
699
|
| (if (.plugin | type) == "array" and (.plugin | length) == 0 then del(.plugin) else . end)
|
|
689
700
|
| (if (.model // "" | tostring | (startswith("weave/") or startswith("weave-claude/") or startswith("weave-codex/")))
|
|
690
701
|
then (if $direct_model != "" then .model = $direct_model else del(.model) end)
|
|
@@ -705,21 +716,18 @@ if [ "$target" = "opencode" ]; then
|
|
|
705
716
|
info "No opencode config at $opencode_config_file (already uninstalled?)"
|
|
706
717
|
fi
|
|
707
718
|
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
if [ -f "$
|
|
713
|
-
|
|
714
|
-
|
|
719
|
+
refuse_if_symlink "$opencode_plugin_dir"
|
|
720
|
+
legacy_opencode_assets_removed=false
|
|
721
|
+
for opencode_asset in opencode-weave.ts directives.ts classifier-thread.ts; do
|
|
722
|
+
refuse_if_symlink "$opencode_plugin_dir/$opencode_asset"
|
|
723
|
+
if [ -f "$opencode_plugin_dir/$opencode_asset" ]; then
|
|
724
|
+
rm -f "$opencode_plugin_dir/$opencode_asset"
|
|
725
|
+
legacy_opencode_assets_removed=true
|
|
715
726
|
fi
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
fi
|
|
721
|
-
rmdir "$opencode_dir/.weave" 2>/dev/null || true
|
|
722
|
-
ok "Removed legacy opencode plugin"
|
|
727
|
+
done
|
|
728
|
+
rmdir "$opencode_plugin_dir" 2>/dev/null || true
|
|
729
|
+
if [ "$legacy_opencode_assets_removed" = "true" ]; then
|
|
730
|
+
ok "Removed legacy opencode plugin files"
|
|
723
731
|
fi
|
|
724
732
|
|
|
725
733
|
# Drop the toggle parked sidecar after its prior model has been restored.
|
package/opencode-weave/README.md
DELETED
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
# Legacy opencode Weave integration
|
|
2
|
-
|
|
3
|
-
This source is bundled and installed for OpenCode's lifecycle, classifier, and
|
|
4
|
-
directive hooks. Subscription enrollment now happens in the router with
|
|
5
|
-
`npx @weave-os/router login claude` or `npx @weave-os/router login codex`;
|
|
6
|
-
requests must not carry subscription headers.
|
|
7
|
-
|
|
8
|
-
The plugin is loaded by new installs, but it does not own subscription
|
|
9
|
-
enrollment or transport subscription credentials.
|
|
10
|
-
|
|
11
|
-
The installer writes only the Responses-format `weave` provider into
|
|
12
|
-
`opencode.json`.
|
|
13
|
-
|
|
14
|
-
## Why this source remains
|
|
15
|
-
|
|
16
|
-
Older manually-installed copies may also load this module for lifecycle and
|
|
17
|
-
directive hooks. It intentionally contains no OAuth login, token refresh, or
|
|
18
|
-
subscription-header transport.
|
|
19
|
-
|
|
20
|
-
## Wire shape it produces
|
|
21
|
-
|
|
22
|
-
opencode talks to one Responses-format `weave` provider. Subscription enrollment
|
|
23
|
-
is managed by the router (`npx @weave-os/router login claude`), not by request
|
|
24
|
-
headers from this plugin:
|
|
25
|
-
|
|
26
|
-
| | |
|
|
27
|
-
|---|---|
|
|
28
|
-
| `POST {router}/v1/responses` | Responses wire format (opencode's default for an `@ai-sdk/openai` provider) |
|
|
29
|
-
| `X-Weave-Router-Key: rk_…` | from `opencode.json` `options.headers` — the router authenticates off this |
|
|
30
|
-
|
|
31
|
-
The router routes each request across the models available to the managed
|
|
32
|
-
installation and its configured credentials.
|
|
33
|
-
|
|
34
|
-
## Router directives
|
|
35
|
-
|
|
36
|
-
OpenCode is a plugin, not a Codex skill runner. The plugin's `chat.message` hook
|
|
37
|
-
rewrites `$rf` / `$router-feedback`, `$fm` / `$force-model`, `$ufm` /
|
|
38
|
-
`$unforce-model`, and `$router-session` (slash forms too) into the leading-space
|
|
39
|
-
`/…` prompts the router already parses. Local toggles (`router-on` / `router-off`
|
|
40
|
-
/ `router-status` / `disable-routing`) stay CLI-only — this installer does not
|
|
41
|
-
own a per-session config flip the way Claude Code and Codex do.
|
|
42
|
-
|
|
43
|
-
## Enrollment
|
|
44
|
-
|
|
45
|
-
Enroll subscriptions through the managed router rather than OpenCode:
|
|
46
|
-
|
|
47
|
-
```sh
|
|
48
|
-
npx @weave-os/router login claude # or: npx @weave-os/router login codex
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
The router stores and refreshes the enrollment server-side; OpenCode does not
|
|
52
|
-
need to carry subscription credentials in request headers.
|
|
53
|
-
|
|
54
|
-
## Env overrides (self-host + tests)
|
|
55
|
-
|
|
56
|
-
- `WEAVE_OPENCODE_LLM_CLASSIFIER=1` — enroll only sessions created while this
|
|
57
|
-
plugin is running. The plugin stores a separate handshake UUID and router
|
|
58
|
-
ticket for each parent/child session under OpenCode's data directory. An
|
|
59
|
-
enrollment failure or missing new-session event blocks inference while the
|
|
60
|
-
opt-in is set; resume an older session with the opt-in unset. Classifier
|
|
61
|
-
sessions cannot compact or change router origins; start
|
|
62
|
-
a new session instead. Requires a router deployment with the exact release
|
|
63
|
-
and installation explicitly allowlisted. Deploy the router's non-retryable
|
|
64
|
-
client-failure response before enabling this opt-in on developer machines.
|
|
65
|
-
|
|
66
|
-
## Verification
|
|
67
|
-
|
|
68
|
-
The required CI contract pins **OpenCode and `@opencode-ai/plugin` 1.18.27**.
|
|
69
|
-
The CLI install reads that pin from `package.json`; the direct Responses tests
|
|
70
|
-
use **`@ai-sdk/openai` 3.0.84**, matching the
|
|
71
|
-
[pinned OpenCode dependencies](https://github.com/anomalyco/opencode/blob/v1.18.27/packages/opencode/package.json).
|
|
72
|
-
Neither required dependency floats. The separate weekly/manual
|
|
73
|
-
[latest compatibility workflow](../../.github/workflows/opencode_latest.yml)
|
|
74
|
-
is not a merge gate.
|
|
75
|
-
|
|
76
|
-
From the router repository root (Node, Bun, Python 3.11+, and jq required):
|
|
77
|
-
|
|
78
|
-
```bash
|
|
79
|
-
npm ci --prefix install/opencode-weave --ignore-scripts
|
|
80
|
-
npm run --prefix install/opencode-weave typecheck
|
|
81
|
-
bun test install/opencode-weave/test/
|
|
82
|
-
make test-install
|
|
83
|
-
npm install --global opencode-ai@1.18.27
|
|
84
|
-
bash install/pi-router/test/opencode_smoke.sh
|
|
85
|
-
go test ./internal/proxy ./internal/translate -count=1
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
`OPENCODE_BIN` selects an already-installed CLI. To explicitly test another
|
|
89
|
-
version, set `OPENCODE_EXPECTED_VERSION` to its exact version; the smoke otherwise
|
|
90
|
-
rejects anything other than the supported pin. The driver gives each command
|
|
91
|
-
60 seconds, kills its process group on timeout, limits mock requests per session,
|
|
92
|
-
and isolates HOME, XDG directories, provider selection, and credentials. Package
|
|
93
|
-
bootstrap may use the network; inference and OAuth tests never use real credentials
|
|
94
|
-
or real providers.
|
|
95
|
-
|
|
96
|
-
| Layer | Contract |
|
|
97
|
-
|---|---|
|
|
98
|
-
| Bun integration tests | Router/lifecycle header continuity, directive rewriting, and no subscription/account header injection |
|
|
99
|
-
| Pinned Responses SDK fixtures | Streaming and non-streaming text/usage, two tool calls, upstream errors, malformed/unknown events, truncated streams, absent usage |
|
|
100
|
-
| Installed real CLI | Exact `/v1/responses`, `auto`, `X-App`, router key, nonempty session IDs, parsed text, usage, completion, two executed tools and matching tool results |
|
|
101
|
-
| Real lifecycle hooks | Main `build`, title `title`, task child `explore`, and automatic `compaction` followed by resumed `build`; parent/child session boundaries |
|
|
102
|
-
| Real plugin loader | Routing hooks remain loadable when explicitly installed as a legacy plugin |
|
|
103
|
-
| Installer/package | Install/toggle/uninstall, packed npm `--opencode` entrypoint; existing Claude/Codex/Pi installer coverage |
|
|
104
|
-
| Go proxy/translation | Native and translated Responses history hygiene, actionable tool-output commands, Codex feedback-skill preservation, wire lifecycle and usage |
|
|
105
|
-
|
|
106
|
-
The lifecycle observer is a **test-only** `chat.headers` hook recording OpenCode's
|
|
107
|
-
actual `input.agent`, not a prompt heuristic or a router-policy change. A synthetic
|
|
108
|
-
high-usage response triggers automatic compaction without a huge prompt. Title
|
|
109
|
-
generation uses the configured local `small_model`; task execution uses the actual
|
|
110
|
-
`task` tool and a child session. No separate classifier/probe invocation was
|
|
111
|
-
observed in these headless flows. Tool-less SDK fixtures cover that wire shape
|
|
112
|
-
without claiming a classifier fingerprint. Non-streaming requests are direct SDK
|
|
113
|
-
fixtures: the tested CLI flows use streaming.
|
|
114
|
-
|
|
115
|
-
The pinned SDK silently ignores an ill-shaped known event, treats an unfinished
|
|
116
|
-
stream as `other`, and tolerates unknown event types. It also requires usage on a
|
|
117
|
-
streaming `response.completed`: missing usage produces `other` rather than `stop`
|
|
118
|
-
(and can cause CLI continuation), while non-streaming missing usage remains
|
|
119
|
-
unknown token counts. These are explicit compatibility observations, **not** claims
|
|
120
|
-
of clean failure or successful completion. The normal CLI cases require both a
|
|
121
|
-
successful terminal event and exact usage, so removing completion/usage fails them.
|
|
122
|
-
|
|
123
|
-
The source intentionally keeps the
|
|
124
|
-
[legacy all-export loader](https://github.com/anomalyco/opencode/blob/v1.18.27/packages/opencode/src/plugin/index.ts)
|
|
125
|
-
shape required by the pinned OpenCode version.
|
|
126
|
-
See the current [CLI](https://opencode.ai/docs/cli/),
|
|
127
|
-
[plugin](https://opencode.ai/docs/plugins/), and
|
|
128
|
-
[server](https://opencode.ai/docs/server/) references when updating the pin.
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@weave-os/router-opencode-extension",
|
|
3
|
-
"private": true,
|
|
4
|
-
"type": "module",
|
|
5
|
-
"description": "OpenCode lifecycle, classifier, and directive hooks for @weave-os/router; managed subscription enrollment belongs to the router.",
|
|
6
|
-
"scripts": {
|
|
7
|
-
"test": "bun test test/",
|
|
8
|
-
"typecheck": "tsc --project tsconfig.json"
|
|
9
|
-
},
|
|
10
|
-
"peerDependencies": {
|
|
11
|
-
"@opencode-ai/plugin": "*"
|
|
12
|
-
},
|
|
13
|
-
"devDependencies": {
|
|
14
|
-
"@ai-sdk/openai": "3.0.84",
|
|
15
|
-
"@opencode-ai/plugin": "1.18.27",
|
|
16
|
-
"@types/bun": "1.3.14",
|
|
17
|
-
"@types/node": "24.13.3",
|
|
18
|
-
"typescript": "5.9.3"
|
|
19
|
-
}
|
|
20
|
-
}
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"
|
|
2
|
-
import { homedir } from "node:os"
|
|
3
|
-
import { dirname, join } from "node:path"
|
|
4
|
-
import type { Session } from "@opencode-ai/sdk"
|
|
5
|
-
|
|
6
|
-
const SESSION_ID = /^[a-zA-Z0-9_-]{1,128}$/
|
|
7
|
-
export const CLASSIFIER_THREAD_HEADER = "X-Weave-Classifier-Thread"
|
|
8
|
-
export const CLASSIFIER_UNAVAILABLE_TICKET = "weave-classifier-unavailable"
|
|
9
|
-
|
|
10
|
-
interface SavedThread {
|
|
11
|
-
sessionID: string
|
|
12
|
-
newChatID: string
|
|
13
|
-
routerOrigin?: string
|
|
14
|
-
threadToken?: string
|
|
15
|
-
compacted?: boolean
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function threadDirectory(): string {
|
|
19
|
-
const authFile = process.env.WEAVE_OPENCODE_AUTH_FILE ??
|
|
20
|
-
join(process.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share"), "opencode", "auth.json")
|
|
21
|
-
return join(dirname(authFile), "weave-classifier-threads")
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function threadPath(sessionID: string): string {
|
|
25
|
-
if (!SESSION_ID.test(sessionID)) throw new Error("Invalid OpenCode session identity")
|
|
26
|
-
return join(threadDirectory(), `${sessionID}.json`)
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
async function readThread(sessionID: string): Promise<SavedThread | undefined> {
|
|
30
|
-
let saved: string
|
|
31
|
-
try {
|
|
32
|
-
saved = await readFile(threadPath(sessionID), "utf8")
|
|
33
|
-
} catch (error) {
|
|
34
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
|
|
35
|
-
throw error
|
|
36
|
-
}
|
|
37
|
-
const parsed: unknown = JSON.parse(saved)
|
|
38
|
-
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Invalid classifier enrollment state")
|
|
39
|
-
const thread = parsed as Partial<SavedThread>
|
|
40
|
-
if (thread.sessionID !== sessionID || typeof thread.newChatID !== "string" ||
|
|
41
|
-
!/^[0-9a-f-]{36}$/.test(thread.newChatID) ||
|
|
42
|
-
(thread.routerOrigin !== undefined && typeof thread.routerOrigin !== "string") ||
|
|
43
|
-
(thread.threadToken !== undefined && (typeof thread.threadToken !== "string" || !thread.threadToken || thread.threadToken.length > 4096)) ||
|
|
44
|
-
(thread.compacted !== undefined && typeof thread.compacted !== "boolean")) {
|
|
45
|
-
throw new Error("Invalid classifier enrollment state")
|
|
46
|
-
}
|
|
47
|
-
return thread as SavedThread
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
async function replaceThread(thread: SavedThread): Promise<void> {
|
|
51
|
-
const destination = threadPath(thread.sessionID)
|
|
52
|
-
const temporary = `${destination}.${crypto.randomUUID()}.tmp`
|
|
53
|
-
await writeFile(temporary, JSON.stringify(thread), { flag: "wx", mode: 0o600 })
|
|
54
|
-
try {
|
|
55
|
-
await rename(temporary, destination)
|
|
56
|
-
} catch (error) {
|
|
57
|
-
await unlink(temporary)
|
|
58
|
-
throw error
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** The session-created event is the only enrollment authority; a short request is not. */
|
|
63
|
-
export class ClassifierThreads {
|
|
64
|
-
private creations = new Map<string, Promise<void>>()
|
|
65
|
-
private handshakes = new Map<string, Promise<string | undefined>>()
|
|
66
|
-
|
|
67
|
-
async hasThread(sessionID: string): Promise<boolean> {
|
|
68
|
-
await this.creations.get(sessionID)
|
|
69
|
-
return (await readThread(sessionID)) !== undefined
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
created(session: Session): Promise<void> {
|
|
73
|
-
if (process.env.WEAVE_OPENCODE_LLM_CLASSIFIER !== "1") return Promise.resolve()
|
|
74
|
-
const sessionID = session.id
|
|
75
|
-
if (this.creations.has(sessionID)) return this.creations.get(sessionID)!
|
|
76
|
-
const creation = (async () => {
|
|
77
|
-
const path = threadPath(sessionID)
|
|
78
|
-
await mkdir(threadDirectory(), { recursive: true, mode: 0o700 })
|
|
79
|
-
try {
|
|
80
|
-
await writeFile(path, JSON.stringify({ sessionID, newChatID: crypto.randomUUID() }), { flag: "wx", mode: 0o600 })
|
|
81
|
-
} catch (error) {
|
|
82
|
-
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
|
|
83
|
-
await readThread(sessionID)
|
|
84
|
-
}
|
|
85
|
-
})()
|
|
86
|
-
this.creations.set(sessionID, creation)
|
|
87
|
-
return creation
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
compacted(sessionID: string): Promise<void> {
|
|
91
|
-
return this.updateCompacted(sessionID)
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
private async updateCompacted(sessionID: string): Promise<void> {
|
|
95
|
-
await this.creations.get(sessionID)
|
|
96
|
-
await this.handshakes.get(sessionID)?.catch(() => undefined)
|
|
97
|
-
const thread = await readThread(sessionID)
|
|
98
|
-
if (thread) await replaceThread({ ...thread, compacted: true })
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
async header(sessionID: string, routerOrigin: string, routerKey: string, agent?: string): Promise<Record<string, string>> {
|
|
102
|
-
await this.creations.get(sessionID)
|
|
103
|
-
if (agent === "title" || agent === "compaction") {
|
|
104
|
-
const ticket = await this.resolveTicket(sessionID, routerOrigin, routerKey, agent)
|
|
105
|
-
return ticket ? { [CLASSIFIER_THREAD_HEADER]: ticket } : {}
|
|
106
|
-
}
|
|
107
|
-
if (this.handshakes.has(sessionID)) {
|
|
108
|
-
const ticket = await this.handshakes.get(sessionID)!
|
|
109
|
-
return ticket ? { [CLASSIFIER_THREAD_HEADER]: ticket } : {}
|
|
110
|
-
}
|
|
111
|
-
const handshake = this.resolveTicket(sessionID, routerOrigin, routerKey, agent)
|
|
112
|
-
this.handshakes.set(sessionID, handshake)
|
|
113
|
-
try {
|
|
114
|
-
const ticket = await handshake
|
|
115
|
-
return ticket ? { [CLASSIFIER_THREAD_HEADER]: ticket } : {}
|
|
116
|
-
} finally {
|
|
117
|
-
if (this.handshakes.get(sessionID) === handshake) this.handshakes.delete(sessionID)
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
private async resolveTicket(sessionID: string, routerOrigin: string, routerKey: string, agent?: string): Promise<string | undefined> {
|
|
122
|
-
const thread = await readThread(sessionID)
|
|
123
|
-
if (!thread) return undefined
|
|
124
|
-
if (thread.compacted || (thread.routerOrigin && thread.routerOrigin !== routerOrigin)) {
|
|
125
|
-
throw new Error("Classifier session cannot continue after compaction or router change")
|
|
126
|
-
}
|
|
127
|
-
if (agent === "title") return undefined
|
|
128
|
-
if (agent === "compaction") throw new Error("Classifier sessions require complete history; compaction is unavailable")
|
|
129
|
-
if (thread.threadToken) return thread.threadToken
|
|
130
|
-
if (!routerKey) throw new Error("Classifier enrollment requires a router key")
|
|
131
|
-
const response = await fetch(`${routerOrigin}/v1/router/threads`, {
|
|
132
|
-
method: "POST", redirect: "error", signal: AbortSignal.timeout(10_000),
|
|
133
|
-
headers: { "X-Weave-Router-Key": routerKey, "X-App": "opencode", "Content-Type": "application/json" },
|
|
134
|
-
body: JSON.stringify({ new_chat_id: thread.newChatID }),
|
|
135
|
-
})
|
|
136
|
-
if (!response.ok) throw new Error(`Classifier enrollment returned HTTP ${response.status}`)
|
|
137
|
-
const ticket: unknown = await response.json()
|
|
138
|
-
if (ticket === null || typeof ticket !== "object" || !("thread_token" in ticket) ||
|
|
139
|
-
typeof ticket.thread_token !== "string" || !ticket.thread_token || ticket.thread_token.length > 4096) {
|
|
140
|
-
throw new Error("Invalid classifier enrollment response")
|
|
141
|
-
}
|
|
142
|
-
await replaceThread({ ...thread, routerOrigin, threadToken: ticket.thread_token })
|
|
143
|
-
return ticket.thread_token
|
|
144
|
-
}
|
|
145
|
-
}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Rewrite OpenCode user text so Weave Router prompt directives reach the
|
|
3
|
-
* same parser Codex and pi already hit. OpenCode is not a skill runner: `$rf`
|
|
4
|
-
* would otherwise go to the LLM. The router already accepts both `/name` and
|
|
5
|
-
* `$name` on the wire; rewriting `$…` to the leading-space `/…` form matches
|
|
6
|
-
* the Codex emit.sh contract and keeps aliases out of model context.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
const FORCE_MODEL = /^(?:\$|\/)(?:force-model|fm)(?:\s+|$)/i
|
|
10
|
-
const UNFORCE_MODEL = /^(?:\$|\/)(?:unforce-model|ufm)\s*$/i
|
|
11
|
-
const ROUTER_FEEDBACK = /^(?:\$|\/)(?:router-feedback|rf)(?:\s|$)/i
|
|
12
|
-
const ROUTER_SESSION = /^(?:\$|\/)router-session\s*$/i
|
|
13
|
-
|
|
14
|
-
export type RouterDirective =
|
|
15
|
-
| { kind: "force-model"; model: string }
|
|
16
|
-
| { kind: "unforce-model" }
|
|
17
|
-
| { kind: "router-feedback"; payload: string }
|
|
18
|
-
| { kind: "router-session" }
|
|
19
|
-
|
|
20
|
-
export function parseRouterDirective(text: string): RouterDirective | undefined {
|
|
21
|
-
const line = text.trim()
|
|
22
|
-
if (!line) return undefined
|
|
23
|
-
|
|
24
|
-
if (UNFORCE_MODEL.test(line) || line === "$ufm" || line === "/ufm") {
|
|
25
|
-
return { kind: "unforce-model" }
|
|
26
|
-
}
|
|
27
|
-
if (ROUTER_SESSION.test(line)) {
|
|
28
|
-
return { kind: "router-session" }
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const force = line.match(/^(?:\$|\/)(?:force-model|fm)\s+(\S[\s\S]*)$/i)
|
|
32
|
-
if (force) {
|
|
33
|
-
const model = force[1].trim()
|
|
34
|
-
if (model) return { kind: "force-model", model }
|
|
35
|
-
return undefined
|
|
36
|
-
}
|
|
37
|
-
if (FORCE_MODEL.test(line)) return undefined
|
|
38
|
-
|
|
39
|
-
const feedback = line.match(/^(?:\$|\/)(?:router-feedback|rf)(?:\s+([\s\S]*))?$/i)
|
|
40
|
-
if (feedback && ROUTER_FEEDBACK.test(line)) {
|
|
41
|
-
return { kind: "router-feedback", payload: (feedback[1] ?? "").trim() }
|
|
42
|
-
}
|
|
43
|
-
return undefined
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export function rewriteRouterDirective(text: string): string | undefined {
|
|
47
|
-
const directive = parseRouterDirective(text)
|
|
48
|
-
if (!directive) return undefined
|
|
49
|
-
switch (directive.kind) {
|
|
50
|
-
case "force-model":
|
|
51
|
-
return ` /force-model ${directive.model}`
|
|
52
|
-
case "unforce-model":
|
|
53
|
-
return " /unforce-model"
|
|
54
|
-
case "router-feedback":
|
|
55
|
-
return directive.payload ? ` /router-feedback ${directive.payload}` : " /router-feedback"
|
|
56
|
-
case "router-session":
|
|
57
|
-
return " /router-session"
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function rewriteDirectiveParts<T extends { type: string; text?: string }>(parts: T[]): boolean {
|
|
62
|
-
let rewritten = false
|
|
63
|
-
for (const part of parts) {
|
|
64
|
-
if (part.type !== "text" || typeof part.text !== "string") continue
|
|
65
|
-
const next = rewriteRouterDirective(part.text)
|
|
66
|
-
if (next === undefined) continue
|
|
67
|
-
part.text = next
|
|
68
|
-
rewritten = true
|
|
69
|
-
break
|
|
70
|
-
}
|
|
71
|
-
return rewritten
|
|
72
|
-
}
|
|
@@ -1,188 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Legacy opencode integration. Subscription enrollment is handled by the
|
|
3
|
-
* router (`npx @weave-os/router login claude`); this module is no longer
|
|
4
|
-
* bundled by the installer.
|
|
5
|
-
*
|
|
6
|
-
* opencode talks to one Responses-format `weave` provider:
|
|
7
|
-
* - POST {router}/v1/responses (Responses wire format)
|
|
8
|
-
* - X-Weave-Router-Key: rk_... (from config options.headers)
|
|
9
|
-
*
|
|
10
|
-
* The router authenticates off X-Weave-Router-Key and managed enrollment.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin"
|
|
14
|
-
import type { AssistantMessage, Message } from "@opencode-ai/sdk"
|
|
15
|
-
import { CLASSIFIER_THREAD_HEADER, CLASSIFIER_UNAVAILABLE_TICKET, ClassifierThreads } from "./classifier-thread.ts"
|
|
16
|
-
import { rewriteDirectiveParts } from "./directives.ts"
|
|
17
|
-
|
|
18
|
-
// Provider id this legacy plugin owns. Deliberately NOT "openai"/"anthropic" —
|
|
19
|
-
// those ids are claimed by opencode's bundled provider plugins.
|
|
20
|
-
const PROVIDER_ID = "weave"
|
|
21
|
-
const HEADER_ROUTER_MODEL = "x-router-model"
|
|
22
|
-
const TOAST_TITLE = "Weave Router"
|
|
23
|
-
const TOAST_DURATION_MS = 6000
|
|
24
|
-
|
|
25
|
-
// Lifecycle metadata for turn classification only (title/subagent/compaction
|
|
26
|
-
// pin safety). Must match internal/requestcontext.OpenCodeAgentHeader; the
|
|
27
|
-
// router ignores it for auth, billing, and provider eligibility.
|
|
28
|
-
const HEADER_OPENCODE_AGENT = "X-Weave-OpenCode-Agent"
|
|
29
|
-
const HEADER_OPENCODE_REQUEST_ID = "X-Weave-OpenCode-Request-ID"
|
|
30
|
-
type OpenCodeAgent = "build" | "title" | "explore" | "compaction"
|
|
31
|
-
const OPENCODE_AGENTS: ReadonlySet<string> = new Set<OpenCodeAgent>(["build", "title", "explore", "compaction"])
|
|
32
|
-
|
|
33
|
-
function knownOpenCodeAgent(agent: string | undefined): OpenCodeAgent | undefined {
|
|
34
|
-
return agent !== undefined && OPENCODE_AGENTS.has(agent) ? (agent as OpenCodeAgent) : undefined
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// Placeholder so the @ai-sdk/openai provider considers auth configured. The
|
|
38
|
-
// router key is supplied by opencode.json and is preserved by the fetch wrapper.
|
|
39
|
-
const DUMMY_KEY = "weave-router-oauth"
|
|
40
|
-
// ---- Request provider: `weave` (Responses) ---------------------------------
|
|
41
|
-
|
|
42
|
-
function compactTokenCount(n: number): string {
|
|
43
|
-
if (n >= 1000) {
|
|
44
|
-
const k = n / 1000
|
|
45
|
-
return `${k >= 10 ? k.toFixed(0) : k.toFixed(1).replace(/\.0$/, "")}k`
|
|
46
|
-
}
|
|
47
|
-
return String(n)
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function formatCost(cost: number): string {
|
|
51
|
-
if (!Number.isFinite(cost) || cost <= 0) return ""
|
|
52
|
-
if (cost < 0.001) return "<$0.001"
|
|
53
|
-
return `$${cost.toFixed(3).replace(/0+$/, "").replace(/\.$/, "")}`
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function formatRoutedToast(routedModelID: string, cost: number, tokens: { input: number; output: number }): string {
|
|
57
|
-
const parts = [`→ ${routedModelID}`]
|
|
58
|
-
const costLabel = formatCost(cost)
|
|
59
|
-
if (costLabel) parts.push(costLabel)
|
|
60
|
-
const usage: string[] = []
|
|
61
|
-
if (tokens.input > 0) usage.push(`${compactTokenCount(tokens.input)} in`)
|
|
62
|
-
if (tokens.output > 0) usage.push(`${compactTokenCount(tokens.output)} out`)
|
|
63
|
-
if (usage.length > 0) parts.push(usage.join(" / "))
|
|
64
|
-
return parts.join(" · ")
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function isCompletedWeaveAssistant(info: Message): info is AssistantMessage {
|
|
68
|
-
if (info.role !== "assistant") return false
|
|
69
|
-
if (info.providerID !== PROVIDER_ID) return false
|
|
70
|
-
if (!info.modelID) return false
|
|
71
|
-
return info.time.completed !== undefined
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export const WeaveCodex: Plugin = async (input: PluginInput): Promise<Hooks> => {
|
|
75
|
-
const classifierThreads = new ClassifierThreads()
|
|
76
|
-
const pendingRequestMessageIDs = new Map<string, string>()
|
|
77
|
-
const routedModelIDsByMessage = new Map<string, string>()
|
|
78
|
-
const toastedMessageIDs = new Set<string>()
|
|
79
|
-
return {
|
|
80
|
-
"chat.message": async (_hookInput, output) => {
|
|
81
|
-
rewriteDirectiveParts(output.parts)
|
|
82
|
-
},
|
|
83
|
-
event: async ({ event }) => {
|
|
84
|
-
if (event.type === "session.created") {
|
|
85
|
-
await classifierThreads.created(event.properties.info)
|
|
86
|
-
return
|
|
87
|
-
}
|
|
88
|
-
if (event.type === "session.compacted") {
|
|
89
|
-
await classifierThreads.compacted(event.properties.sessionID)
|
|
90
|
-
return
|
|
91
|
-
}
|
|
92
|
-
if (event.type !== "message.updated") return
|
|
93
|
-
const info = event.properties.info
|
|
94
|
-
if (!isCompletedWeaveAssistant(info)) return
|
|
95
|
-
if (toastedMessageIDs.has(info.id)) return
|
|
96
|
-
toastedMessageIDs.add(info.id)
|
|
97
|
-
const routedModelID = routedModelIDsByMessage.get(info.parentID) ?? info.modelID
|
|
98
|
-
routedModelIDsByMessage.delete(info.parentID)
|
|
99
|
-
for (const [requestID, messageID] of pendingRequestMessageIDs) {
|
|
100
|
-
if (messageID === info.parentID) pendingRequestMessageIDs.delete(requestID)
|
|
101
|
-
}
|
|
102
|
-
try {
|
|
103
|
-
await input.client.tui.showToast({
|
|
104
|
-
body: {
|
|
105
|
-
title: TOAST_TITLE,
|
|
106
|
-
message: formatRoutedToast(routedModelID, info.cost, info.tokens),
|
|
107
|
-
variant: "info",
|
|
108
|
-
duration: TOAST_DURATION_MS,
|
|
109
|
-
},
|
|
110
|
-
})
|
|
111
|
-
} catch {
|
|
112
|
-
// Toast is best-effort; a TUI miss must not fail the turn.
|
|
113
|
-
}
|
|
114
|
-
},
|
|
115
|
-
auth: {
|
|
116
|
-
provider: PROVIDER_ID,
|
|
117
|
-
async loader() {
|
|
118
|
-
return {
|
|
119
|
-
apiKey: DUMMY_KEY,
|
|
120
|
-
async fetch(requestInput: RequestInfo | URL, init?: RequestInit) {
|
|
121
|
-
// Preserve the configured router and lifecycle headers.
|
|
122
|
-
const headers = new Headers(init?.headers as HeadersInit | undefined)
|
|
123
|
-
|
|
124
|
-
const requestID = headers.get(HEADER_OPENCODE_REQUEST_ID)
|
|
125
|
-
let routedModelCaptured = false
|
|
126
|
-
try {
|
|
127
|
-
const response = await fetch(requestInput, { ...init, headers })
|
|
128
|
-
const messageID = requestID ? pendingRequestMessageIDs.get(requestID) : undefined
|
|
129
|
-
const routedModelID = response.headers.get(HEADER_ROUTER_MODEL)
|
|
130
|
-
if (messageID && routedModelID) {
|
|
131
|
-
routedModelIDsByMessage.set(messageID, routedModelID)
|
|
132
|
-
routedModelCaptured = true
|
|
133
|
-
}
|
|
134
|
-
return response
|
|
135
|
-
} finally {
|
|
136
|
-
if (requestID && routedModelCaptured) pendingRequestMessageIDs.delete(requestID)
|
|
137
|
-
}
|
|
138
|
-
},
|
|
139
|
-
}
|
|
140
|
-
},
|
|
141
|
-
methods: [],
|
|
142
|
-
},
|
|
143
|
-
// The Codex backend (which the router forwards GPT turns to) keys session
|
|
144
|
-
// continuity off these headers; mirror opencode's bundled codex plugin.
|
|
145
|
-
// Scoped to our provider so other providers are untouched.
|
|
146
|
-
"chat.headers": async (hookInput, output) => {
|
|
147
|
-
if (hookInput.model.providerID !== PROVIDER_ID) return
|
|
148
|
-
if (hookInput.agent !== "title") {
|
|
149
|
-
// OpenCode swallows plugin hook exceptions. A failure must reach the
|
|
150
|
-
// router as an invalid ticket, never as an unticketed HMM request.
|
|
151
|
-
output.headers[CLASSIFIER_THREAD_HEADER] = CLASSIFIER_UNAVAILABLE_TICKET
|
|
152
|
-
try {
|
|
153
|
-
const enrolled = await classifierThreads.hasThread(hookInput.sessionID)
|
|
154
|
-
if (!enrolled && process.env.WEAVE_OPENCODE_LLM_CLASSIFIER !== "1") {
|
|
155
|
-
delete output.headers[CLASSIFIER_THREAD_HEADER]
|
|
156
|
-
} else {
|
|
157
|
-
if (!hookInput.provider?.options?.baseURL) throw new Error("Weave router origin unavailable")
|
|
158
|
-
const routerOrigin = new URL(hookInput.provider.options.baseURL).origin
|
|
159
|
-
const configuredHeaders = new Headers(hookInput.provider.options.headers as HeadersInit | undefined)
|
|
160
|
-
Object.assign(output.headers, await classifierThreads.header(hookInput.sessionID, routerOrigin,
|
|
161
|
-
configuredHeaders.get("X-Weave-Router-Key") ?? "", hookInput.agent))
|
|
162
|
-
}
|
|
163
|
-
} catch (error) {
|
|
164
|
-
console.error("Classifier enrollment blocked this OpenCode request", hookInput.sessionID,
|
|
165
|
-
error instanceof Error ? error.message : "unknown failure")
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
output.headers["originator"] = "codex_cli_ts"
|
|
169
|
-
output.headers["session-id"] = hookInput.sessionID
|
|
170
|
-
const messageID = hookInput.message?.id
|
|
171
|
-
if (messageID) {
|
|
172
|
-
const requestID = crypto.randomUUID()
|
|
173
|
-
pendingRequestMessageIDs.set(requestID, messageID)
|
|
174
|
-
output.headers[HEADER_OPENCODE_REQUEST_ID] = requestID
|
|
175
|
-
}
|
|
176
|
-
// Custom agents are user-named; only OpenCode's own lifecycle agents are forwarded.
|
|
177
|
-
const agent = knownOpenCodeAgent(hookInput.agent)
|
|
178
|
-
if (agent) output.headers[HEADER_OPENCODE_AGENT] = agent
|
|
179
|
-
},
|
|
180
|
-
"chat.params": async (hookInput, output) => {
|
|
181
|
-
if (hookInput.model.providerID !== PROVIDER_ID) return
|
|
182
|
-
// Match codex cli: the Codex backend rejects an explicit max output cap.
|
|
183
|
-
output.maxOutputTokens = undefined
|
|
184
|
-
},
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
export default WeaveCodex
|