@weave-os/router 0.2.29 → 0.2.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -16
- package/bin.js +53 -10
- package/cc-statusline.sh +269 -56
- package/codex-skills/force-parent/SKILL.md +23 -0
- package/codex-skills/force-parent/scripts/emit.sh +7 -0
- package/codex-skills/router-models/SKILL.md +1 -1
- package/codex-status.sh +312 -48
- package/codex-toggle.sh +1 -1
- package/commands/force-parent.md +6 -0
- package/commands/models.md +1 -1
- package/commands/router-models.md +1 -1
- package/directives.tsv +1 -0
- package/install.sh +1566 -218
- package/package.json +8 -2
- package/pi-router/README.md +4 -2
- package/pi-router/src/force-model.ts +109 -38
- package/pi-router/src/pricing.generated.ts +8 -3
- package/pi-router/src/routed-model.ts +51 -7
- package/pi-router/src/ui.ts +3 -3
- package/uninstall.sh +167 -9
- package/windows.js +545 -0
package/windows.js
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Native Windows entrypoint. PowerShell users do not need Git Bash, jq, or
|
|
3
|
+
// another installation beyond the npx command they already ran.
|
|
4
|
+
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const { execFileSync, spawn } = require("node:child_process");
|
|
7
|
+
const path = require("node:path");
|
|
8
|
+
const { emitKeypressEvents } = require("node:readline");
|
|
9
|
+
const readline = require("node:readline/promises");
|
|
10
|
+
const { stdin, stdout } = require("node:process");
|
|
11
|
+
const TOML = require("smol-toml");
|
|
12
|
+
const git = require("isomorphic-git");
|
|
13
|
+
|
|
14
|
+
const defaultBaseUrl = process.env.WEAVE_ROUTER_URL || "https://router.workweave.ai";
|
|
15
|
+
const packageName = process.env.WEAVE_ROUTER_NPM_PACKAGE || "@weave-os/router";
|
|
16
|
+
const claudeAttribution = {
|
|
17
|
+
commit: "Co-Authored-By: Weave Router <router@weaveos.com>",
|
|
18
|
+
pr: "🤖 Generated with [Weave Router](https://router.workweave.ai)",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
let patchToml;
|
|
22
|
+
|
|
23
|
+
async function main() {
|
|
24
|
+
({ patch: patchToml } = await import("@decimalturn/toml-patch"));
|
|
25
|
+
const options = parseArgs(process.argv.slice(2));
|
|
26
|
+
if (options.help) {
|
|
27
|
+
console.log("Usage: npx @weave-os/router [--claude|--codex|--opencode|--pi|--copilot] [--wire anthropic|openai] [--scope user|project] [--dir PATH] [--base-url URL] [--email EMAIL] [--return-url URL] [--non-interactive] [--no-attribution] [--uninstall]");
|
|
28
|
+
console.log("On Windows, install and uninstall run natively in Node.js; no Git Bash or jq is needed.");
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (options.mode !== "install" && options.mode !== "uninstall") {
|
|
32
|
+
throw new Error("This Windows release supports install and --uninstall. Other router commands are not yet available natively.");
|
|
33
|
+
}
|
|
34
|
+
if (options.returnUrl && options.mode !== "install") throw new Error("--return-url is supported only for install.");
|
|
35
|
+
// npx.cmd re-parses arguments through cmd.exe, which splits a URL at '&'; the PowerShell command passes it by env instead.
|
|
36
|
+
if (!options.returnUrl && options.mode === "install" && process.env.WEAVE_ROUTER_RETURN_URL) {
|
|
37
|
+
options.returnUrl = validReturnUrl(process.env.WEAVE_ROUTER_RETURN_URL, "WEAVE_ROUTER_RETURN_URL");
|
|
38
|
+
}
|
|
39
|
+
if (options.target === "copilot" && options.scope === "project") throw new Error("--copilot installs in user scope only (Copilot CLI has no project-level providers.json).");
|
|
40
|
+
if (options.wire && options.target !== "copilot") throw new Error("--wire only applies to --copilot.");
|
|
41
|
+
if (options.scope === "project" && !options.directory) {
|
|
42
|
+
options.directory = findGitRoot(process.cwd());
|
|
43
|
+
if (!options.directory) throw new Error("--scope project must run inside a git repo, or pass --dir <path>.");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const root = path.resolve(options.directory || process.env.USERPROFILE || process.env.HOME);
|
|
47
|
+
const target = options.target || (options.nonInteractive ? "claude" : await selectTarget());
|
|
48
|
+
if (target === "copilot" && options.scope === "project") throw new Error("--copilot installs in user scope only (Copilot CLI has no project-level providers.json).");
|
|
49
|
+
const paths = configPaths(root, target, options.scope, options.explicitDirectory);
|
|
50
|
+
for (const filePath of Object.values(paths).filter(Boolean)) {
|
|
51
|
+
if (options.scope === "project") refuseSymlink(path.dirname(filePath));
|
|
52
|
+
refuseSymlink(filePath);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (options.mode === "uninstall") {
|
|
56
|
+
uninstall(paths, target);
|
|
57
|
+
console.log(`Weave Router removed from ${target} settings.`);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const trackedProjectPaths = options.scope === "project" ? await ensureProjectFilesPrivate(root, target) : new Set();
|
|
61
|
+
|
|
62
|
+
const baseUrl = (options.baseUrl || defaultBaseUrl).replace(/\/+$/, "");
|
|
63
|
+
let key = process.env.WEAVE_ROUTER_KEY || readInstalledKey(paths, target, trackedProjectPaths);
|
|
64
|
+
if (!key && options.nonInteractive) throw new Error("--non-interactive requires WEAVE_ROUTER_KEY.");
|
|
65
|
+
if (!key) {
|
|
66
|
+
console.log(`Get your Weave Router API key at ${baseUrl}`);
|
|
67
|
+
key = await promptForKey();
|
|
68
|
+
}
|
|
69
|
+
if (!key) throw new Error("No key provided.");
|
|
70
|
+
|
|
71
|
+
const routerIsHealthy = await probe(`${baseUrl}/health`, {});
|
|
72
|
+
const keyIsValid = await probe(`${baseUrl}/validate`, { "X-Weave-Router-Key": key });
|
|
73
|
+
if (!keyIsValid) console.warn("Warning: could not validate the key. Check the router URL and key if requests fail.");
|
|
74
|
+
|
|
75
|
+
const email = options.email || process.env.WEAVE_USER_EMAIL || "";
|
|
76
|
+
if (/[\x00-\x1f\x7f]/.test(email)) throw new Error("Email must not contain control characters.");
|
|
77
|
+
if (target === "claude") installClaude(paths, baseUrl, key, email, options.attribution);
|
|
78
|
+
else if (target === "codex") installCodex(paths, baseUrl, key, email);
|
|
79
|
+
else if (target === "opencode") installOpenCode(paths, baseUrl, key, email);
|
|
80
|
+
else if (target === "copilot") installCopilot(paths, baseUrl, key, email, options.wire);
|
|
81
|
+
else installPi(paths, baseUrl, key, email);
|
|
82
|
+
console.log(`Weave Router configured for ${target} at ${paths.config}.`);
|
|
83
|
+
if (!options.returnUrl) return;
|
|
84
|
+
if (!routerIsHealthy || !keyIsValid) {
|
|
85
|
+
console.warn("Skipping return URL because router verification did not complete successfully.");
|
|
86
|
+
} else if (await openInBrowser(options.returnUrl)) {
|
|
87
|
+
console.log(`Opened return URL in your browser: ${options.returnUrl}`);
|
|
88
|
+
} else {
|
|
89
|
+
console.warn(`Install succeeded, but no browser could be opened. Open this URL to continue: ${options.returnUrl}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function validReturnUrl(value, source) {
|
|
94
|
+
if (!/^https?:$/.test(safeUrlProtocol(value))) throw new Error(`${source} must be an http:// or https:// URL.`);
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// URL.parse needs Node 22; the package supports Node 18.
|
|
99
|
+
function safeUrlProtocol(value) {
|
|
100
|
+
try {
|
|
101
|
+
return new URL(value).protocol;
|
|
102
|
+
} catch {
|
|
103
|
+
return "";
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function probe(url, headers) {
|
|
108
|
+
return fetch(url, { headers, signal: AbortSignal.timeout(5000) }).then((response) => response.ok).catch(() => false);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// explorer.exe can exit without opening anything, and `cmd /c start` would parse the URL's '&' query separators as shell syntax.
|
|
112
|
+
function openInBrowser(url) {
|
|
113
|
+
const [opener, ...openerArgs] = process.platform === "win32" ? ["rundll32.exe", "url.dll,FileProtocolHandler"] : [process.platform === "darwin" ? "open" : "xdg-open"];
|
|
114
|
+
return new Promise((resolve) => {
|
|
115
|
+
const child = spawn(opener, [...openerArgs, url], { stdio: "ignore", windowsHide: true });
|
|
116
|
+
child.once("error", () => resolve(false));
|
|
117
|
+
child.once("exit", (code) => resolve(code === 0));
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function parseArgs(args) {
|
|
122
|
+
const options = { mode: "install", scope: "user", target: null, nonInteractive: false, explicitDirectory: false, help: false, attribution: true };
|
|
123
|
+
for (let index = 0; index < args.length; index++) {
|
|
124
|
+
const arg = args[index];
|
|
125
|
+
if (["--claude", "--codex", "--opencode", "--pi", "--copilot"].includes(arg)) options.target = arg.slice(2);
|
|
126
|
+
else if (arg === "--uninstall") options.mode = "uninstall";
|
|
127
|
+
else if (arg === "--non-interactive") options.nonInteractive = true;
|
|
128
|
+
else if (arg === "--no-attribution") options.attribution = false;
|
|
129
|
+
else if (arg === "--local") options.baseUrl = "http://localhost:8080";
|
|
130
|
+
else if (arg === "-h" || arg === "--help") options.help = true;
|
|
131
|
+
else if (arg === "--wire") {
|
|
132
|
+
const value = args[++index];
|
|
133
|
+
if (value !== "anthropic" && value !== "openai") throw new Error("--wire must be 'anthropic' or 'openai'.");
|
|
134
|
+
options.wire = value;
|
|
135
|
+
}
|
|
136
|
+
else if (["--scope", "--dir", "--base-url", "--email", "--return-url"].includes(arg)) {
|
|
137
|
+
const value = args[++index];
|
|
138
|
+
if (!value) throw new Error(`${arg} requires a value.`);
|
|
139
|
+
if (arg === "--scope") {
|
|
140
|
+
if (!["user", "project"].includes(value)) throw new Error("--scope must be user or project.");
|
|
141
|
+
options.scope = value;
|
|
142
|
+
} else if (arg === "--dir") { options.directory = value; options.explicitDirectory = true; }
|
|
143
|
+
else if (arg === "--base-url") options.baseUrl = value;
|
|
144
|
+
else if (arg === "--return-url") options.returnUrl = validReturnUrl(value, arg);
|
|
145
|
+
else options.email = value;
|
|
146
|
+
} else if (arg === "install" || arg === "setup") {
|
|
147
|
+
if (arg === "setup") throw new Error("'setup' is not yet available in the native Windows installer; choose one client with --claude or --codex.");
|
|
148
|
+
} else if (["off", "--off", "on", "--on", "status", "--status", "update", "--update", "models", "accounts", "login", "disable-routing"].includes(arg)) {
|
|
149
|
+
options.mode = "unsupported";
|
|
150
|
+
} else throw new Error(`Unsupported Windows installer option: ${arg}`);
|
|
151
|
+
}
|
|
152
|
+
return options;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function configPaths(root, target, scope, directory) {
|
|
156
|
+
if (target === "claude") return {
|
|
157
|
+
config: path.join(root, ".claude", "settings.json"),
|
|
158
|
+
localConfig: scope === "project" ? path.join(root, ".claude", "settings.local.json") : null,
|
|
159
|
+
state: path.join(root, ".claude", ".weave-router-state.json"),
|
|
160
|
+
};
|
|
161
|
+
if (target === "codex") return { config: path.join(root, ".codex", "config.toml"), state: path.join(root, ".codex", ".weave-router-state.json") };
|
|
162
|
+
if (target === "opencode") {
|
|
163
|
+
const configDirectory = scope === "project" || directory
|
|
164
|
+
? root
|
|
165
|
+
: path.join(process.env.XDG_CONFIG_HOME || path.join(root, ".config"), "opencode");
|
|
166
|
+
return { config: path.join(configDirectory, "opencode.json"), parked: path.join(configDirectory, ".weave-parked.json") };
|
|
167
|
+
}
|
|
168
|
+
if (target === "copilot") {
|
|
169
|
+
const copilotRoot = directory ? path.join(root, ".copilot") : process.env.COPILOT_HOME || path.join(root, ".copilot");
|
|
170
|
+
return { config: path.join(copilotRoot, "providers.json"), settings: path.join(copilotRoot, "settings.json"), parked: path.join(copilotRoot, ".weave-parked.json") };
|
|
171
|
+
}
|
|
172
|
+
const piRoot = path.join(root, ".pi", scope === "project" || directory ? "" : "agent");
|
|
173
|
+
return { config: path.join(piRoot, "models.json"), settings: path.join(piRoot, "settings.json"), state: path.join(piRoot, ".weave-router-state.json") };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function ensureProjectFilesPrivate(root, target) {
|
|
177
|
+
const projectConfigPaths = {
|
|
178
|
+
claude: [".claude/settings.local.json", ".claude/.weave-router-state.json"],
|
|
179
|
+
codex: [".codex/config.toml", ".codex/.weave-router-state.json"],
|
|
180
|
+
opencode: ["opencode.json", ".weave-parked.json"],
|
|
181
|
+
pi: [".pi/models.json", ".pi/settings.json", ".pi/.weave-router-state.json"],
|
|
182
|
+
}[target];
|
|
183
|
+
const gitignorePath = path.join(root, ".gitignore");
|
|
184
|
+
refuseSymlink(gitignorePath);
|
|
185
|
+
const repositoryRoot = findGitRoot(root);
|
|
186
|
+
const trackedProjectPaths = new Set();
|
|
187
|
+
if (repositoryRoot) {
|
|
188
|
+
let gitDirectory = path.join(repositoryRoot, ".git");
|
|
189
|
+
if (fs.statSync(gitDirectory).isFile()) {
|
|
190
|
+
const gitDirectoryPointer = fs.readFileSync(gitDirectory, "utf8").trim();
|
|
191
|
+
if (!gitDirectoryPointer.startsWith("gitdir: ")) throw new Error(`Invalid git directory pointer at ${gitDirectory}.`);
|
|
192
|
+
gitDirectory = path.resolve(repositoryRoot, gitDirectoryPointer.slice("gitdir: ".length));
|
|
193
|
+
}
|
|
194
|
+
let trackedFiles;
|
|
195
|
+
try {
|
|
196
|
+
trackedFiles = execFileSync("git", ["-C", repositoryRoot, "ls-files", "-z", "--", ...[...projectConfigPaths, ".claude/settings.json"].map((configPath) => `:(literal)${path.relative(repositoryRoot, path.join(root, configPath)).split(path.sep).join("/")}`)], { encoding: "utf8" }).split("\0").filter(Boolean);
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (error.code !== "ENOENT") throw error;
|
|
199
|
+
try {
|
|
200
|
+
trackedFiles = await git.listFiles({ fs, dir: repositoryRoot, gitdir: gitDirectory });
|
|
201
|
+
} catch (indexError) {
|
|
202
|
+
throw new Error(`Cannot safely inspect this project's Git index: ${indexError.message}. Use --scope user to install without Git.`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
for (const trackedFile of trackedFiles) trackedProjectPaths.add(path.resolve(repositoryRoot, trackedFile));
|
|
206
|
+
}
|
|
207
|
+
const trackedFiles = projectConfigPaths.filter((configPath) => trackedProjectPaths.has(path.join(root, configPath)));
|
|
208
|
+
if (trackedFiles.length) throw new Error(`Project config is already tracked by git and may expose credentials: ${trackedFiles.join(", ")}. Untrack it before installing.`);
|
|
209
|
+
const existingEntries = fs.existsSync(gitignorePath) ? fs.readFileSync(gitignorePath, "utf8").split(/\r?\n/) : [];
|
|
210
|
+
const missingEntries = projectConfigPaths.filter((entry) => !existingEntries.includes(entry));
|
|
211
|
+
if (missingEntries.length) {
|
|
212
|
+
fs.mkdirSync(root, { recursive: true });
|
|
213
|
+
fs.appendFileSync(gitignorePath, `${existingEntries.length && existingEntries.at(-1) ? "\n" : ""}${missingEntries.join("\n")}\n`);
|
|
214
|
+
}
|
|
215
|
+
return trackedProjectPaths;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function installClaude(paths, baseUrl, key, email, attribution) {
|
|
219
|
+
const settings = readJson(paths.config);
|
|
220
|
+
// Same rule as install.sh: an install without our attribution block is an opt-out that reinstalls keep.
|
|
221
|
+
const ownsAttribution = String(settings.attribution?.commit || "").startsWith("Co-Authored-By: Weave Router");
|
|
222
|
+
const optedOutOfAttribution = Object.hasOwn(settings.env || {}, "ANTHROPIC_BASE_URL") && settings.attribution == null;
|
|
223
|
+
const localSettings = paths.localConfig ? readJson(paths.localConfig) : null;
|
|
224
|
+
const state = readJson(paths.state);
|
|
225
|
+
state.env ||= Object.fromEntries(["ANTHROPIC_BASE_URL", "ENABLE_TOOL_SEARCH"].map((field) => [field, { exists: Object.hasOwn(settings.env || {}, field), value: settings.env?.[field] }]));
|
|
226
|
+
state.attribution ||= Object.fromEntries(Object.keys(claudeAttribution).map((field) => [field, { exists: Object.hasOwn(settings.attribution || {}, field), value: settings.attribution?.[field] }]));
|
|
227
|
+
state.originalAppHeaders ||= {
|
|
228
|
+
config: (settings.env?.ANTHROPIC_CUSTOM_HEADERS || "").split("\n").filter((header) => /^X-App:/i.test(header)),
|
|
229
|
+
localConfig: (localSettings?.env?.ANTHROPIC_CUSTOM_HEADERS ?? settings.env?.ANTHROPIC_CUSTOM_HEADERS ?? "").split("\n").filter((header) => /^X-App:/i.test(header)),
|
|
230
|
+
};
|
|
231
|
+
state.installedBaseUrl = baseUrl;
|
|
232
|
+
const customHeaders = localSettings?.env?.ANTHROPIC_CUSTOM_HEADERS ?? settings.env?.ANTHROPIC_CUSTOM_HEADERS ?? "";
|
|
233
|
+
const previousHeaders = customHeaders.split("\n").filter((header) => !/^X-(?:Weave-Router-Key|Weave-User-Email|Weave-User-Name|App):/i.test(header));
|
|
234
|
+
const routerHeaders = [
|
|
235
|
+
`X-Weave-Router-Key: ${key}`,
|
|
236
|
+
...(email ? [`X-Weave-User-Email: ${email}`] : []),
|
|
237
|
+
"X-App: claude-code",
|
|
238
|
+
];
|
|
239
|
+
settings.env ||= {};
|
|
240
|
+
settings.env.ANTHROPIC_BASE_URL = baseUrl;
|
|
241
|
+
if (paths.localConfig) {
|
|
242
|
+
if (settings.env.ANTHROPIC_CUSTOM_HEADERS) settings.env.ANTHROPIC_CUSTOM_HEADERS = settings.env.ANTHROPIC_CUSTOM_HEADERS.split("\n").filter((header) => !/^X-(?:Weave-Router-Key|Weave-User-Email|Weave-User-Name):/i.test(header)).join("\n");
|
|
243
|
+
localSettings.env ||= {};
|
|
244
|
+
localSettings.env.ANTHROPIC_CUSTOM_HEADERS = [...previousHeaders, ...routerHeaders].filter(Boolean).join("\n");
|
|
245
|
+
} else {
|
|
246
|
+
settings.env.ANTHROPIC_CUSTOM_HEADERS = [...previousHeaders, ...routerHeaders].filter(Boolean).join("\n");
|
|
247
|
+
}
|
|
248
|
+
settings.env.ENABLE_TOOL_SEARCH = "true";
|
|
249
|
+
if (attribution && (ownsAttribution || (settings.attribution == null && !optedOutOfAttribution))) {
|
|
250
|
+
settings.attribution = { ...claudeAttribution, ...settings.attribution, commit: claudeAttribution.commit };
|
|
251
|
+
} else if (!attribution && ownsAttribution) {
|
|
252
|
+
delete settings.attribution.commit;
|
|
253
|
+
if (settings.attribution.pr === claudeAttribution.pr) delete settings.attribution.pr;
|
|
254
|
+
if (!Object.keys(settings.attribution).length) delete settings.attribution;
|
|
255
|
+
}
|
|
256
|
+
writeJson(paths.config, settings);
|
|
257
|
+
if (paths.localConfig) writeJson(paths.localConfig, localSettings);
|
|
258
|
+
writeJson(paths.state, state);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function installCodex(paths, baseUrl, key, email) {
|
|
262
|
+
const settings = readToml(paths.config);
|
|
263
|
+
const state = readJson(paths.state);
|
|
264
|
+
state.modelProvider ||= { exists: Object.hasOwn(settings, "model_provider") && settings.model_provider !== "weave", value: settings.model_provider !== "weave" ? settings.model_provider : undefined };
|
|
265
|
+
writeJson(paths.state, state);
|
|
266
|
+
const currentModel = settings.model;
|
|
267
|
+
const hasUserModel = typeof currentModel === "string" && currentModel !== "weave-auto";
|
|
268
|
+
settings.model_provider = "weave";
|
|
269
|
+
if (!hasUserModel) settings.model = "weave-auto";
|
|
270
|
+
settings.model_providers ||= {};
|
|
271
|
+
settings.model_providers.weave = {
|
|
272
|
+
name: "Weave Router",
|
|
273
|
+
base_url: `${baseUrl}/v1`,
|
|
274
|
+
wire_api: "responses",
|
|
275
|
+
requires_openai_auth: true,
|
|
276
|
+
http_headers: {
|
|
277
|
+
"X-Weave-Router-Key": key,
|
|
278
|
+
...(email ? { "X-Weave-User-Email": email } : {}),
|
|
279
|
+
"X-App": "codex",
|
|
280
|
+
"X-Weave-Codex-Native-Model-Pin": "1",
|
|
281
|
+
},
|
|
282
|
+
};
|
|
283
|
+
writeToml(paths.config, settings);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function installOpenCode(paths, baseUrl, key, email) {
|
|
287
|
+
const settings = readJson(paths.config);
|
|
288
|
+
const parkedModel = readJson(paths.parked);
|
|
289
|
+
if (!Object.hasOwn(parkedModel, "direct_model") && typeof settings.model === "string" && !settings.model.startsWith("weave/")) {
|
|
290
|
+
writeJson(paths.parked, { direct_model: settings.model });
|
|
291
|
+
}
|
|
292
|
+
settings["$schema"] ||= "https://opencode.ai/config.json";
|
|
293
|
+
settings.provider ||= {};
|
|
294
|
+
settings.provider.weave = {
|
|
295
|
+
npm: "@ai-sdk/openai",
|
|
296
|
+
name: "Weave Router",
|
|
297
|
+
options: {
|
|
298
|
+
apiKey: key,
|
|
299
|
+
baseURL: `${baseUrl}/v1`,
|
|
300
|
+
headers: { "X-Weave-Router-Key": key, "X-App": "opencode", ...(email ? { "X-Weave-User-Email": email } : {}) },
|
|
301
|
+
},
|
|
302
|
+
models: { auto: { name: "Auto", reasoning: true, attachment: true, modalities: { input: ["text", "image", "pdf"], output: ["text"] }, limit: { context: 500000, output: 32000 } } },
|
|
303
|
+
};
|
|
304
|
+
settings.model = "weave/auto";
|
|
305
|
+
writeJson(paths.config, settings);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Copilot CLI lists providers.json models in /model next to its GitHub models,
|
|
309
|
+
// so the router is a selectable model rather than a replacement base URL.
|
|
310
|
+
function installCopilot(paths, baseUrl, key, email, requestedWire) {
|
|
311
|
+
const providers = readJson(paths.config);
|
|
312
|
+
const installedWire = (providers.providers || []).find((entry) => entry.name === "weave")?.type === "openai" ? "openai" : "anthropic";
|
|
313
|
+
const wire = requestedWire || installedWire;
|
|
314
|
+
const headers = { "X-Weave-Router-Key": key, "X-App": "copilot", ...(email ? { "X-Weave-User-Email": email } : {}) };
|
|
315
|
+
const provider = wire === "openai"
|
|
316
|
+
? { name: "weave", type: "openai", baseUrl: `${baseUrl}/v1`, wireApi: "responses", headers }
|
|
317
|
+
: { name: "weave", type: "anthropic", baseUrl, headers };
|
|
318
|
+
const model = { id: "auto", provider: "weave", name: "Weave Router", modelId: wire === "openai" ? "gpt-5.4" : "claude-sonnet-4", maxPromptTokens: 400000, maxOutputTokens: 32000 };
|
|
319
|
+
providers.providers = [...(providers.providers || []).filter((entry) => entry.name !== "weave"), provider];
|
|
320
|
+
providers.models = [...(providers.models || []).filter((entry) => entry.provider !== "weave"), model];
|
|
321
|
+
writeJson(paths.config, providers);
|
|
322
|
+
try { fs.chmodSync(paths.config, 0o600); } catch {}
|
|
323
|
+
const settings = readJson(paths.settings);
|
|
324
|
+
const parked = readJson(paths.parked);
|
|
325
|
+
const directModel = typeof settings.model === "string" && !settings.model.startsWith("weave/") ? settings.model : parked.direct_model || "";
|
|
326
|
+
writeJson(paths.parked, { direct_model: directModel, router_model: "weave/auto" });
|
|
327
|
+
settings.model = "weave/auto";
|
|
328
|
+
writeJson(paths.settings, settings);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function installPi(paths, baseUrl, key, email) {
|
|
332
|
+
const models = readJson(paths.config);
|
|
333
|
+
models.providers ||= {};
|
|
334
|
+
models.providers.weave = {
|
|
335
|
+
baseUrl,
|
|
336
|
+
api: "anthropic-messages",
|
|
337
|
+
apiKey: key,
|
|
338
|
+
authHeader: false,
|
|
339
|
+
headers: { "X-Weave-Router-Key": key, "X-App": "pi", "x-weave-routing-marker": "off", "x-weave-routing-alpha": "0.8", "x-weave-routing-speed-weight": "0.05", "x-weave-routing-output-cost-ratio": "0.5", "x-weave-routing-expected-output-tokens": "3000", ...(email ? { "X-Weave-User-Email": email } : {}) },
|
|
340
|
+
models: [{ id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6 (via Weave Router)", reasoning: true, input: ["text", "image"], contextWindow: 1000000, maxTokens: 64000 }],
|
|
341
|
+
};
|
|
342
|
+
const settings = readJson(paths.settings);
|
|
343
|
+
const state = readJson(paths.state);
|
|
344
|
+
if (!Object.hasOwn(state, "defaultProvider")) state.defaultProvider = { exists: Object.hasOwn(settings, "defaultProvider"), value: settings.defaultProvider };
|
|
345
|
+
if (!Object.hasOwn(state, "defaultModel")) state.defaultModel = { exists: Object.hasOwn(settings, "defaultModel"), value: settings.defaultModel };
|
|
346
|
+
settings.packages = [...new Set([...(settings.packages || []).filter((item) => !/^npm:@(?:workweave\/(?:pi-)?router|weave-os\/router)$/.test(item)), `npm:${packageName}`])];
|
|
347
|
+
settings.defaultProvider = "weave";
|
|
348
|
+
settings.defaultModel ||= "claude-sonnet-4-6";
|
|
349
|
+
writeJson(paths.config, models);
|
|
350
|
+
writeJson(paths.settings, settings);
|
|
351
|
+
writeJson(paths.state, state);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function uninstall(paths, target) {
|
|
355
|
+
if (target === "claude") {
|
|
356
|
+
if (!fs.existsSync(paths.config) && !fs.existsSync(paths.localConfig || "")) return;
|
|
357
|
+
const settings = readJson(paths.config);
|
|
358
|
+
const localSettings = paths.localConfig ? readJson(paths.localConfig) : null;
|
|
359
|
+
const state = readJson(paths.state);
|
|
360
|
+
const hadConfig = fs.existsSync(paths.config);
|
|
361
|
+
const hadLocalConfig = paths.localConfig && fs.existsSync(paths.localConfig);
|
|
362
|
+
if (!fs.existsSync(paths.state) && ![settings.env?.ANTHROPIC_CUSTOM_HEADERS, localSettings?.env?.ANTHROPIC_CUSTOM_HEADERS].some((headers) => /^X-Weave-Router-Key:/m.test(headers || ""))) return;
|
|
363
|
+
restoreField(settings.env, "ANTHROPIC_BASE_URL", state.env?.ANTHROPIC_BASE_URL, state.installedBaseUrl || settings.env?.ANTHROPIC_BASE_URL);
|
|
364
|
+
restoreField(settings.env, "ENABLE_TOOL_SEARCH", state.env?.ENABLE_TOOL_SEARCH, "true");
|
|
365
|
+
const customHeaders = (headerBlock, originalAppHeaders) => {
|
|
366
|
+
const preservedHeaders = (headerBlock || "").split("\n").filter((header) => !/^X-Weave-(?:Router-Key|User-Email|User-Name):/i.test(header) && !/^X-App:\s*claude-code\s*$/i.test(header));
|
|
367
|
+
if (!preservedHeaders.some((header) => /^X-App:/i.test(header))) preservedHeaders.push(...(originalAppHeaders || []));
|
|
368
|
+
return preservedHeaders.filter(Boolean).join("\n");
|
|
369
|
+
};
|
|
370
|
+
if (settings.env?.ANTHROPIC_CUSTOM_HEADERS) {
|
|
371
|
+
settings.env.ANTHROPIC_CUSTOM_HEADERS = customHeaders(settings.env.ANTHROPIC_CUSTOM_HEADERS, state.originalAppHeaders?.config);
|
|
372
|
+
if (!settings.env.ANTHROPIC_CUSTOM_HEADERS) delete settings.env.ANTHROPIC_CUSTOM_HEADERS;
|
|
373
|
+
}
|
|
374
|
+
if (localSettings?.env?.ANTHROPIC_CUSTOM_HEADERS) {
|
|
375
|
+
localSettings.env.ANTHROPIC_CUSTOM_HEADERS = customHeaders(localSettings.env.ANTHROPIC_CUSTOM_HEADERS, state.originalAppHeaders?.localConfig);
|
|
376
|
+
if (!localSettings.env.ANTHROPIC_CUSTOM_HEADERS) delete localSettings.env.ANTHROPIC_CUSTOM_HEADERS;
|
|
377
|
+
if (!Object.keys(localSettings.env).length) delete localSettings.env;
|
|
378
|
+
}
|
|
379
|
+
for (const field of Object.keys(claudeAttribution)) restoreField(settings.attribution, field, state.attribution?.[field], claudeAttribution[field]);
|
|
380
|
+
if (settings.env && !Object.keys(settings.env).length) delete settings.env;
|
|
381
|
+
if (settings.attribution && !Object.keys(settings.attribution).length) delete settings.attribution;
|
|
382
|
+
if (hadConfig) writeJson(paths.config, settings);
|
|
383
|
+
if (hadLocalConfig) writeJson(paths.localConfig, localSettings);
|
|
384
|
+
fs.rmSync(paths.state, { force: true });
|
|
385
|
+
} else if (target === "codex") {
|
|
386
|
+
if (!fs.existsSync(paths.config)) return;
|
|
387
|
+
const settings = readToml(paths.config);
|
|
388
|
+
if (!settings.model_providers?.weave?.http_headers?.["X-Weave-Router-Key"]) return;
|
|
389
|
+
restoreField(settings, "model_provider", readJson(paths.state).modelProvider, "weave");
|
|
390
|
+
if (settings.model === "weave-auto") delete settings.model;
|
|
391
|
+
delete settings.model_providers?.weave;
|
|
392
|
+
if (settings.model_providers && !Object.keys(settings.model_providers).length) delete settings.model_providers;
|
|
393
|
+
writeToml(paths.config, settings);
|
|
394
|
+
fs.rmSync(paths.state, { force: true });
|
|
395
|
+
} else if (target === "copilot") {
|
|
396
|
+
if (!fs.existsSync(paths.config)) return;
|
|
397
|
+
const providers = readJson(paths.config);
|
|
398
|
+
if (!(providers.providers || []).some((entry) => entry.name === "weave")) return;
|
|
399
|
+
providers.providers = (providers.providers || []).filter((entry) => entry.name !== "weave");
|
|
400
|
+
providers.models = (providers.models || []).filter((entry) => entry.provider !== "weave");
|
|
401
|
+
const { providers: remainingProviders, models: remainingModels, ...otherFields } = providers;
|
|
402
|
+
if (!remainingProviders.length && !remainingModels.length && !Object.keys(otherFields).length) fs.rmSync(paths.config, { force: true });
|
|
403
|
+
else writeJson(paths.config, providers);
|
|
404
|
+
if (fs.existsSync(paths.settings)) {
|
|
405
|
+
const settings = readJson(paths.settings);
|
|
406
|
+
if (typeof settings.model === "string" && settings.model.startsWith("weave/")) {
|
|
407
|
+
const directModel = readJson(paths.parked).direct_model;
|
|
408
|
+
if (directModel) settings.model = directModel;
|
|
409
|
+
else delete settings.model;
|
|
410
|
+
writeJson(paths.settings, settings);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
fs.rmSync(paths.parked, { force: true });
|
|
414
|
+
} else if (target === "opencode") {
|
|
415
|
+
if (!fs.existsSync(paths.config)) return;
|
|
416
|
+
const settings = readJson(paths.config);
|
|
417
|
+
if (!settings.provider?.weave) return;
|
|
418
|
+
const parkedModel = readJson(paths.parked);
|
|
419
|
+
delete settings.provider?.weave;
|
|
420
|
+
if (settings.model === "weave/auto") {
|
|
421
|
+
if (typeof parkedModel.direct_model === "string") settings.model = parkedModel.direct_model;
|
|
422
|
+
else delete settings.model;
|
|
423
|
+
}
|
|
424
|
+
writeJson(paths.config, settings);
|
|
425
|
+
fs.rmSync(paths.parked, { force: true });
|
|
426
|
+
} else {
|
|
427
|
+
if (!fs.existsSync(paths.config) && !fs.existsSync(paths.settings)) return;
|
|
428
|
+
const models = readJson(paths.config);
|
|
429
|
+
delete models.providers?.weave;
|
|
430
|
+
if (fs.existsSync(paths.config)) writeJson(paths.config, models);
|
|
431
|
+
if (fs.existsSync(paths.settings)) {
|
|
432
|
+
const settings = readJson(paths.settings);
|
|
433
|
+
const state = readJson(paths.state);
|
|
434
|
+
settings.packages = (settings.packages || []).filter((item) => item !== `npm:${packageName}`);
|
|
435
|
+
restoreField(settings, "defaultProvider", state.defaultProvider, "weave");
|
|
436
|
+
restoreField(settings, "defaultModel", state.defaultModel, "claude-sonnet-4-6");
|
|
437
|
+
writeJson(paths.settings, settings);
|
|
438
|
+
}
|
|
439
|
+
fs.rmSync(paths.state, { force: true });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function restoreField(record, field, savedValue, installedValue) {
|
|
444
|
+
if (!record || record[field] !== installedValue) return;
|
|
445
|
+
if (savedValue?.exists) record[field] = savedValue.value;
|
|
446
|
+
else delete record[field];
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function readInstalledKey(paths, target, trackedProjectPaths) {
|
|
450
|
+
try {
|
|
451
|
+
if (target === "claude") {
|
|
452
|
+
for (const configPath of [paths.localConfig, paths.config].filter(Boolean)) {
|
|
453
|
+
if (trackedProjectPaths.has(configPath)) continue;
|
|
454
|
+
const installedKey = (readJson(configPath).env?.ANTHROPIC_CUSTOM_HEADERS || "").match(/^X-Weave-Router-Key:\s*(\S+)/m)?.[1];
|
|
455
|
+
if (installedKey) return installedKey;
|
|
456
|
+
}
|
|
457
|
+
return "";
|
|
458
|
+
}
|
|
459
|
+
if (target === "codex") return readToml(paths.config).model_providers?.weave?.http_headers?.["X-Weave-Router-Key"] || "";
|
|
460
|
+
if (target === "opencode") return readJson(paths.config).provider?.weave?.options?.headers?.["X-Weave-Router-Key"] || "";
|
|
461
|
+
if (target === "copilot") return (readJson(paths.config).providers || []).find((entry) => entry.name === "weave")?.headers?.["X-Weave-Router-Key"] || "";
|
|
462
|
+
return readJson(paths.config).providers?.weave?.headers?.["X-Weave-Router-Key"] || "";
|
|
463
|
+
} catch { return ""; }
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async function selectTarget() {
|
|
467
|
+
const terminal = readline.createInterface({ input: stdin, output: stdout });
|
|
468
|
+
try {
|
|
469
|
+
const answer = (await terminal.question("Install target: [1] Claude Code (default), [2] Codex, [3] OpenCode, [4] pi, [5] Copilot CLI: ")).trim();
|
|
470
|
+
return ({ "": "claude", "1": "claude", "2": "codex", "3": "opencode", "4": "pi", "5": "copilot" })[answer] || (() => { throw new Error("Choose 1, 2, 3, 4, or 5."); })();
|
|
471
|
+
} finally { terminal.close(); }
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async function promptForKey() {
|
|
475
|
+
stdout.write("Paste your key (rk_…): ");
|
|
476
|
+
if (!stdin.isTTY || typeof stdin.setRawMode !== "function") {
|
|
477
|
+
const terminal = readline.createInterface({ input: stdin, output: stdout });
|
|
478
|
+
try { return (await terminal.question("")).trim(); }
|
|
479
|
+
finally { terminal.close(); }
|
|
480
|
+
}
|
|
481
|
+
emitKeypressEvents(stdin);
|
|
482
|
+
stdin.setRawMode(true);
|
|
483
|
+
stdin.resume();
|
|
484
|
+
return new Promise((resolve, reject) => {
|
|
485
|
+
let key = "";
|
|
486
|
+
const cleanup = () => {
|
|
487
|
+
stdin.removeListener("keypress", onKeypress);
|
|
488
|
+
stdin.setRawMode(false);
|
|
489
|
+
stdout.write("\n");
|
|
490
|
+
};
|
|
491
|
+
const onKeypress = (character, event) => {
|
|
492
|
+
if (event.ctrl && event.name === "c") {
|
|
493
|
+
cleanup();
|
|
494
|
+
reject(new Error("Cancelled."));
|
|
495
|
+
} else if (event.name === "return" || event.name === "enter") {
|
|
496
|
+
cleanup();
|
|
497
|
+
resolve(key.trim());
|
|
498
|
+
} else if (event.name === "backspace") {
|
|
499
|
+
key = key.slice(0, -1);
|
|
500
|
+
} else if (!event.ctrl && !event.meta) {
|
|
501
|
+
key += character;
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
stdin.on("keypress", onKeypress);
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function readJson(filePath) {
|
|
509
|
+
try {
|
|
510
|
+
const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
511
|
+
if (!value || Array.isArray(value) || typeof value !== "object") throw new Error("expected a JSON object");
|
|
512
|
+
return value;
|
|
513
|
+
} catch (error) {
|
|
514
|
+
if (error.code === "ENOENT") return {};
|
|
515
|
+
throw new Error(`Cannot safely read ${filePath}: ${error.message}`);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function writeJson(filePath, value) { writeText(filePath, `${JSON.stringify(value, null, 2)}\n`); }
|
|
520
|
+
function readToml(filePath) { return TOML.parse(readText(filePath), { integersAsBigInt: true }); }
|
|
521
|
+
function writeToml(filePath, settings) { writeText(filePath, patchToml(readText(filePath), settings)); }
|
|
522
|
+
function readText(filePath) { try { return fs.readFileSync(filePath, "utf8"); } catch (error) { if (error.code === "ENOENT") return ""; throw error; } }
|
|
523
|
+
function writeText(filePath, value) {
|
|
524
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
525
|
+
const temporaryPath = `${filePath}.weave-${process.pid}.tmp`;
|
|
526
|
+
fs.writeFileSync(temporaryPath, value, { mode: 0o600 });
|
|
527
|
+
fs.renameSync(temporaryPath, filePath);
|
|
528
|
+
}
|
|
529
|
+
function refuseSymlink(filePath) {
|
|
530
|
+
try { if (fs.lstatSync(filePath).isSymbolicLink()) throw new Error(`${filePath} is a symlink; refusing to write through it.`); }
|
|
531
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
532
|
+
}
|
|
533
|
+
function findGitRoot(directory) {
|
|
534
|
+
let current = path.resolve(directory);
|
|
535
|
+
while (true) {
|
|
536
|
+
if (fs.existsSync(path.join(current, ".git"))) return current;
|
|
537
|
+
const parent = path.dirname(current);
|
|
538
|
+
if (parent === current) return null;
|
|
539
|
+
current = parent;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
main().catch((error) => {
|
|
543
|
+
console.error(`Weave Router: ${error.message}`);
|
|
544
|
+
process.exitCode = 1;
|
|
545
|
+
});
|