velqa 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Velqa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # velqa
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Point Claude Code, Codex and opencode at [Velqa](https://velqa.dev)'s open-weight models in one command.
4
+
5
+ npx velqa init
6
+
7
+ It asks for an API key (create one at https://velqa.dev/dashboard/keys), lists the chat
8
+ models that key can use, and writes:
9
+
10
+ - **Claude Code**: the `env` block of `~/.claude/settings.json` (base URL, token, model, output cap).
11
+ - **Codex**: `model`, `model_provider` and a `[model_providers.velqa]` table in
12
+ `~/.codex/config.toml` (or `$CODEX_HOME`). Your own keys in that table are kept; a layout it
13
+ cannot edit safely is left untouched and reported.
14
+ - **opencode**: a `velqa` provider with every chat model the key can use, and the chosen one as
15
+ default, in `~/.config/opencode/opencode.json` (or `opencode.jsonc`, comments kept). It uses
16
+ the `provider` format, which opencode 1 reads and opencode 2 migrates.
17
+
18
+ Codex and opencode read the key from `VELQA_API_KEY`: it is set in a marked block of `~/.zshrc`
19
+ or `~/.bashrc`, in `~/.config/fish/conf.d/velqa.fish`, or in your Windows user environment. On
20
+ any other shell, set it yourself; the key is never printed.
21
+
22
+ Nothing is written until every file has been prepared, so a config it cannot edit stops the
23
+ run with no change. Every file it changes is backed up next to itself first
24
+ (`*.velqa-backup-<time>`), replaced in one step, and readable by you only. Running it again
25
+ updates its own settings and keeps the ones you added.
26
+ If `VELQA_API_KEY` is already set, it is used without asking.
package/dist/cli.js ADDED
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { execFileSync } from "node:child_process";
4
+ import { homedir } from "node:os";
5
+ import { basename, delimiter, dirname, join } from "node:path";
6
+ import { argv, env, exit, platform, stdin, stdout } from "node:process";
7
+ import { createInterface } from "node:readline";
8
+ import { Writable } from "node:stream";
9
+ import { ANTHROPIC_BASE, DEFAULT_MODEL, KEY_ENV, OAI_BASE, claudeSettings, codexConfig, isPlausibleKey, opencodeConfig, shellExport, } from "./config.js";
10
+ const HELP = `velqa init Point Claude Code, Codex and opencode at Velqa (asks for your API key)
11
+
12
+ Create a key at https://velqa.dev/dashboard/keys first. Existing config files
13
+ are backed up next to themselves before any change.`;
14
+ let muted = false;
15
+ const output = new Writable({
16
+ write(chunk, encoding, done) {
17
+ if (!muted)
18
+ stdout.write(chunk, encoding);
19
+ done();
20
+ },
21
+ });
22
+ // No history: Up at a later prompt would otherwise recall the hidden key.
23
+ const rl = createInterface({ input: stdin, output, terminal: stdin.isTTY, historySize: 0 });
24
+ // The iterator buffers lines (piped input arrives before the questions) and ends on EOF.
25
+ const lines = rl[Symbol.asyncIterator]();
26
+ async function readLine() {
27
+ const next = await lines.next();
28
+ if (next.done)
29
+ throw new Error("Input closed before setup finished; nothing more was changed.");
30
+ return next.value.trim();
31
+ }
32
+ async function ask(question) {
33
+ stdout.write(question);
34
+ return readLine();
35
+ }
36
+ async function askSecret(question) {
37
+ stdout.write(question);
38
+ muted = true;
39
+ try {
40
+ return await readLine();
41
+ }
42
+ finally {
43
+ muted = false;
44
+ stdout.write("\n");
45
+ }
46
+ }
47
+ async function confirm(question, byDefault) {
48
+ const answer = (await ask(`${question} ${byDefault ? "[Y/n]" : "[y/N]"} `)).toLowerCase();
49
+ return answer === "" ? byDefault : answer.startsWith("y") || answer.startsWith("o");
50
+ }
51
+ function onPath(command) {
52
+ const names = platform === "win32" ? [`${command}.cmd`, `${command}.exe`, command] : [command];
53
+ return (env.PATH ?? "").split(delimiter).some((dir) => dir && names.some((n) => existsSync(join(dir, n))));
54
+ }
55
+ function readOrNull(path) {
56
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
57
+ }
58
+ /**
59
+ * Back up, then replace in one rename: a reader never sees half a file, and the
60
+ * new file and its backup are created readable by the user only (they may hold
61
+ * the key). A symlinked file (dotfiles repo) is written at its target.
62
+ */
63
+ function target(path) {
64
+ if (existsSync(path))
65
+ return realpathSync(path);
66
+ let link = false;
67
+ try {
68
+ link = lstatSync(path).isSymbolicLink();
69
+ }
70
+ catch { }
71
+ if (link)
72
+ throw new Error(`${path} is a broken symlink; fix it first`);
73
+ return path;
74
+ }
75
+ /** Refuse a file that changed while we asked questions, or that is not UTF-8 (rewriting it would lose bytes). */
76
+ function unchanged(change) {
77
+ target(change.path);
78
+ const now = existsSync(change.path) ? readFileSync(change.path) : null;
79
+ const same = now === null ? change.before === null : change.before !== null && now.equals(Buffer.from(change.before, "utf8"));
80
+ if (!same)
81
+ throw new Error(`${change.path} changed during setup or is not UTF-8 text; nothing was changed, run again`);
82
+ }
83
+ function apply(change) {
84
+ if (change.before === change.content)
85
+ return;
86
+ const path = target(change.path);
87
+ if (change.before !== null) {
88
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
89
+ writeFileSync(`${path}.velqa-backup-${stamp}`, change.before, { mode: 0o600, flag: "wx" });
90
+ }
91
+ mkdirSync(dirname(path), { recursive: true });
92
+ const tmp = `${path}.velqa-tmp-${process.pid}`;
93
+ writeFileSync(tmp, change.content, { mode: 0o600, flag: "wx" });
94
+ try {
95
+ renameSync(tmp, path);
96
+ }
97
+ catch (error) {
98
+ rmSync(tmp, { force: true });
99
+ throw error;
100
+ }
101
+ }
102
+ function change(path, build) {
103
+ const before = readOrNull(path);
104
+ return { path, before, content: build(before) };
105
+ }
106
+ async function fetchJson(url, key) {
107
+ const res = await fetch(url, { headers: key ? { Authorization: `Bearer ${key}` } : {} });
108
+ return { status: res.status, body: res.ok ? await res.json() : null };
109
+ }
110
+ async function chatModelsFor(key) {
111
+ const keyModels = await fetchJson(`${OAI_BASE}/models`, key);
112
+ if (keyModels.status === 401 || keyModels.status === 403) {
113
+ throw new Error("Velqa refused this key (revoked or mistyped). Create one at https://velqa.dev/dashboard/keys");
114
+ }
115
+ if (keyModels.status !== 200)
116
+ throw new Error(`Velqa answered ${keyModels.status} while checking the key; try again shortly.`);
117
+ const allowed = new Set((keyModels.body.data ?? []).map((m) => m.id));
118
+ const catalog = await fetchJson(`${ANTHROPIC_BASE}/api/models`);
119
+ const chat = (catalog.body?.models ?? [])
120
+ .filter((m) => m.mode === "chat")
121
+ .map((m) => m.id);
122
+ const usable = chat.filter((id) => allowed.has(id));
123
+ return usable.length > 0 ? usable : [...allowed];
124
+ }
125
+ async function pickModel(models) {
126
+ const fallback = models.includes(DEFAULT_MODEL) ? DEFAULT_MODEL : models[0];
127
+ models.forEach((id, i) => stdout.write(` ${String(i + 1).padStart(2)}. ${id}${id === fallback ? " (recommended)" : ""}\n`));
128
+ const answer = await ask(`Model [${fallback}]: `);
129
+ if (answer === "")
130
+ return fallback;
131
+ const byNumber = models[Number(answer) - 1];
132
+ if (byNumber)
133
+ return byNumber;
134
+ if (models.includes(answer))
135
+ return answer;
136
+ throw new Error(`Unknown model "${answer}".`);
137
+ }
138
+ /** Where the key goes for Codex and opencode; null when we do not know the shell. */
139
+ function keyFile(key) {
140
+ const shell = basename(env.SHELL ?? "");
141
+ if (shell === "zsh")
142
+ return change(join(env.ZDOTDIR || homedir(), ".zshrc"), (before) => shellExport(before, key));
143
+ if (shell === "bash") {
144
+ // macOS terminals start login shells: bash reads the first of these that exists, so creating another would hide it.
145
+ const login = [".bash_profile", ".bash_login", ".profile"].map((f) => join(homedir(), f));
146
+ const rc = platform === "darwin" ? (login.find((f) => existsSync(f)) ?? login[0]) : join(homedir(), ".bashrc");
147
+ return change(rc, (before) => shellExport(before, key));
148
+ }
149
+ if (shell === "fish") {
150
+ const conf = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "fish", "conf.d", "velqa.fish");
151
+ return change(conf, () => `set -gx ${KEY_ENV} "${key}"\n`);
152
+ }
153
+ return null;
154
+ }
155
+ async function init() {
156
+ stdout.write("Velqa: point Claude Code, Codex and opencode at open-weight models.\n\n");
157
+ const fromEnv = env[KEY_ENV]?.trim();
158
+ const key = fromEnv && isPlausibleKey(fromEnv) ? fromEnv : await askSecret("Velqa API key (sk-..., input hidden): ");
159
+ if (!isPlausibleKey(key))
160
+ throw new Error("That does not look like a Velqa key (it starts with sk-).");
161
+ const models = await chatModelsFor(key);
162
+ if (models.length === 0)
163
+ throw new Error("This key has access to no chat model.");
164
+ stdout.write("Key accepted. Chat models available to it:\n");
165
+ const model = await pickModel(models);
166
+ // Ask and build everything first: a config we cannot edit stops the run before any file changes.
167
+ const changes = [];
168
+ const done = [];
169
+ if (await confirm(`Configure Claude Code${onPath("claude") ? "" : " (not found on PATH)"}?`, onPath("claude"))) {
170
+ const path = join(homedir(), ".claude", "settings.json");
171
+ changes.push(change(path, (before) => claudeSettings(before, key, model)));
172
+ done.push(`Claude Code: ${path}\n try: claude "explain this repo in 3 sentences"`);
173
+ }
174
+ let needsKeyEnv = false;
175
+ if (await confirm(`Configure Codex${onPath("codex") ? "" : " (not found on PATH)"}?`, onPath("codex"))) {
176
+ const path = join(env.CODEX_HOME || join(homedir(), ".codex"), "config.toml");
177
+ changes.push(change(path, (before) => codexConfig(before, model)));
178
+ done.push(`Codex: ${path}\n then: codex`);
179
+ needsKeyEnv = true;
180
+ }
181
+ if (await confirm(`Configure opencode${onPath("opencode") ? "" : " (not found on PATH)"}?`, onPath("opencode"))) {
182
+ const dir = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode");
183
+ const jsonc = join(dir, "opencode.jsonc");
184
+ const path = existsSync(jsonc) ? jsonc : join(dir, "opencode.json");
185
+ changes.push(change(path, (before) => opencodeConfig(before, models, model)));
186
+ done.push(`opencode: ${path}\n then: opencode (switch models with /models)`);
187
+ needsKeyEnv = true;
188
+ }
189
+ let setxNeeded = false;
190
+ if (needsKeyEnv) {
191
+ const file = platform === "win32" ? null : keyFile(key);
192
+ if (file) {
193
+ changes.push(file);
194
+ done.push(`${KEY_ENV} set in ${file.path}: open a new terminal first`);
195
+ }
196
+ else if (platform === "win32") {
197
+ setxNeeded = true;
198
+ done.push(`${KEY_ENV} saved in your Windows user environment: open a new terminal first`);
199
+ }
200
+ else {
201
+ // Never print the key: it would land in the terminal's scrollback and history.
202
+ done.push(`set ${KEY_ENV} to your key in your shell's startup file`);
203
+ }
204
+ }
205
+ changes.forEach(unchanged);
206
+ const written = [];
207
+ try {
208
+ for (const c of changes) {
209
+ apply(c);
210
+ written.push(c.path);
211
+ }
212
+ // setx stores the variable for new terminals; run without a shell, so the key reaches no history.
213
+ if (setxNeeded) {
214
+ try {
215
+ execFileSync("setx", [KEY_ENV, key], { stdio: "ignore" });
216
+ }
217
+ catch {
218
+ throw new Error(`setx could not save ${KEY_ENV}`); // the original error quotes the command line, key included
219
+ }
220
+ }
221
+ }
222
+ catch (error) {
223
+ const kept = written.length ? ` Already updated (backups next to them): ${written.join(", ")}.` : "";
224
+ throw new Error(`${error instanceof Error ? error.message : String(error)}.${kept}`);
225
+ }
226
+ stdout.write(done.length ? `\nDone.\n${done.map((d) => `- ${d}`).join("\n")}\n` : "\nNothing configured.\n");
227
+ }
228
+ const command = argv[2] ?? "init";
229
+ if (command === "-h" || command === "--help" || command === "help") {
230
+ stdout.write(`${HELP}\n`);
231
+ exit(0);
232
+ }
233
+ if (command !== "init") {
234
+ stdout.write(`Unknown command "${command}".\n\n${HELP}\n`);
235
+ exit(1);
236
+ }
237
+ init()
238
+ .then(() => {
239
+ rl.close();
240
+ })
241
+ .catch((error) => {
242
+ rl.close();
243
+ stdout.write(`\nError: ${error instanceof Error ? error.message : String(error)}\n`);
244
+ exit(1);
245
+ });
package/dist/config.js ADDED
@@ -0,0 +1,220 @@
1
+ // Pure config writers: each takes the current file content (null when the file
2
+ // does not exist) and returns the new content. No I/O here, so they are tested
3
+ // directly and the CLI only decides where to read and write.
4
+ import { applyEdits, modify, parse as parseJsonc } from "jsonc-parser";
5
+ import { parse as parseToml } from "smol-toml";
6
+ import { isDeepStrictEqual } from "node:util";
7
+ export const OAI_BASE = "https://api.velqa.dev/v1";
8
+ export const ANTHROPIC_BASE = "https://api.velqa.dev";
9
+ export const DEFAULT_MODEL = "glm-5.3-flash";
10
+ export const SMALL_FAST_MODEL = "glm-5.3-flash";
11
+ export const KEY_ENV = "VELQA_API_KEY";
12
+ // Mirrors MODEL_LIMITS in apps/web/src/lib/tools.ts (the dashboard snippets).
13
+ // shortcut: duplicated because /api/models carries no context window; serve it there if this drifts.
14
+ const MODEL_LIMITS = {
15
+ "kimi-k2.6": { context: 131072, output: 16384 },
16
+ "minimax-m3": { context: 131072, output: 16384 },
17
+ "hy3": { context: 262144, output: 16384 },
18
+ "mimo-v2.5": { context: 262144, output: 16384 },
19
+ "mimo-v2.6-flash": { context: 262144, output: 16384 },
20
+ "deepseek-v4-pro": { context: 160000, output: 16384 },
21
+ "deepseek-v4-flash": { context: 65536, output: 8192 },
22
+ "glm-4.7": { context: 131072, output: 16384 },
23
+ "glm-4.7-flash": { context: 200000, output: 16384 },
24
+ "glm-5.3-flash": { context: 200000, output: 16384 },
25
+ "glm-5.2": { context: 131072, output: 16384 },
26
+ };
27
+ export function modelLimit(model) {
28
+ return MODEL_LIMITS[model] ?? { context: 131072, output: 16384 };
29
+ }
30
+ /** ~/.claude/settings.json: set Velqa's variables in `env`, keep everything else. */
31
+ export function claudeSettings(existing, key, model) {
32
+ let settings;
33
+ try {
34
+ settings = existing?.trim() ? JSON.parse(existing) : {};
35
+ }
36
+ catch {
37
+ // Fixed message: JSON.parse quotes the text around the error, which may be the old key.
38
+ throw new Error("~/.claude/settings.json is not valid JSON; fix it first");
39
+ }
40
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
41
+ throw new Error("~/.claude/settings.json is not a JSON object");
42
+ }
43
+ const env = typeof settings.env === "object" && settings.env !== null && !Array.isArray(settings.env)
44
+ ? settings.env
45
+ : {};
46
+ // A rerun keeps the user's own small model and any lower output cap; the cap never exceeds the model's.
47
+ const cap = modelLimit(model).output;
48
+ const ownCap = Number(env.CLAUDE_CODE_MAX_OUTPUT_TOKENS);
49
+ settings.env = {
50
+ ...env,
51
+ ANTHROPIC_BASE_URL: ANTHROPIC_BASE,
52
+ ANTHROPIC_AUTH_TOKEN: key,
53
+ ANTHROPIC_MODEL: model,
54
+ ANTHROPIC_SMALL_FAST_MODEL: typeof env.ANTHROPIC_SMALL_FAST_MODEL === "string" ? env.ANTHROPIC_SMALL_FAST_MODEL : SMALL_FAST_MODEL,
55
+ CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(ownCap > 0 && ownCap < cap ? ownCap : cap),
56
+ };
57
+ return JSON.stringify(settings, null, 2) + "\n";
58
+ }
59
+ // Bare or quoted TOML keys: `model`, `"model"` and `'model'` are the same key.
60
+ const tomlKey = (names) => `\\s*(?:${names}|"(?:${names})"|'(?:${names})')\\s*`;
61
+ const CODEX_TOP_KEYS = new RegExp(`^${tomlKey("model|model_provider|model_context_window")}=`);
62
+ const VELQA_KEYS = new RegExp(`^${tomlKey("name|base_url|env_key|wire_api")}=`);
63
+ const TABLE_HEADER = /^\s*\[/;
64
+ const VELQA_TABLE = new RegExp(`^\\s*\\[${tomlKey("model_providers")}\\.${tomlKey("velqa")}\\]\\s*(#.*)?$`);
65
+ /**
66
+ * ~/.codex/config.toml: Codex reads `model`, `model_provider` and
67
+ * `model_context_window` only before the first [table], so they are replaced
68
+ * there and our provider table replaces any previous [model_providers.velqa].
69
+ * Other keys, tables and [profiles.*] are left untouched.
70
+ */
71
+ export function codexConfig(existing, model) {
72
+ const lines = (existing ?? "").split("\n");
73
+ const firstTable = lines.findIndex((line) => TABLE_HEADER.test(line));
74
+ const topEnd = firstTable === -1 ? lines.length : firstTable;
75
+ const top = lines.slice(0, topEnd).filter((line) => !CODEX_TOP_KEYS.test(line));
76
+ // Our table is rebuilt at the end; keys the user added to it (retries, headers...) are kept.
77
+ const rest = [];
78
+ const ownVelqaLines = [];
79
+ let inVelqaTable = false;
80
+ for (const line of lines.slice(topEnd)) {
81
+ if (TABLE_HEADER.test(line)) {
82
+ inVelqaTable = VELQA_TABLE.test(line);
83
+ if (inVelqaTable)
84
+ continue;
85
+ }
86
+ if (!inVelqaTable)
87
+ rest.push(line);
88
+ else if (!VELQA_KEYS.test(line))
89
+ ownVelqaLines.push(line);
90
+ }
91
+ const ours = [
92
+ `model = "${model}"`,
93
+ `model_provider = "velqa"`,
94
+ `model_context_window = ${modelLimit(model).context}`,
95
+ ];
96
+ const table = [
97
+ "[model_providers.velqa]",
98
+ 'name = "Velqa"',
99
+ `base_url = "${OAI_BASE}"`,
100
+ `env_key = "${KEY_ENV}"`,
101
+ 'wire_api = "responses"',
102
+ ];
103
+ const body = [...ours, ...trimBlank(top), "", ...trimBlank(rest)];
104
+ const result = [...trimBlank(body), "", ...table, ...trimBlank(ownVelqaLines), ""].join("\n");
105
+ checkCodex(existing, result, model);
106
+ return result;
107
+ }
108
+ /** The line edit above covers ordinary files; a real parse catches every layout it does not (dotted keys, inline tables...). */
109
+ function checkCodex(existing, result, model) {
110
+ const byHand = "add the Velqa provider by hand (https://velqa.dev/docs/codex)";
111
+ let before;
112
+ try {
113
+ before = parseToml(existing ?? "");
114
+ }
115
+ catch {
116
+ throw new Error(`the Codex config.toml is not valid TOML; fix it or ${byHand}`);
117
+ }
118
+ let parsed;
119
+ try {
120
+ parsed = parseToml(result);
121
+ }
122
+ catch {
123
+ throw new Error(`the Codex config.toml has a layout this tool cannot edit safely; ${byHand}`);
124
+ }
125
+ const provider = parsed.model_providers?.velqa;
126
+ // Apart from the fields we own, the parsed config must not change (a `model = ` line inside a multi-line string, say).
127
+ const others = (config) => {
128
+ const copy = structuredClone(config);
129
+ for (const k of ["model", "model_provider", "model_context_window"])
130
+ delete copy[k];
131
+ const velqa = copy.model_providers?.velqa;
132
+ if (velqa)
133
+ for (const k of ["name", "base_url", "env_key", "wire_api"])
134
+ delete velqa[k];
135
+ if (velqa && Object.keys(velqa).length === 0)
136
+ delete copy.model_providers.velqa;
137
+ if (copy.model_providers && Object.keys(copy.model_providers).length === 0)
138
+ delete copy.model_providers;
139
+ return copy;
140
+ };
141
+ if (!isDeepStrictEqual(others(before), others(parsed)) ||
142
+ parsed.model_context_window !== modelLimit(model).context ||
143
+ parsed.model !== model ||
144
+ parsed.model_provider !== "velqa" ||
145
+ provider?.base_url !== OAI_BASE ||
146
+ provider?.env_key !== KEY_ENV ||
147
+ provider?.wire_api !== "responses") {
148
+ throw new Error(`the Codex config.toml has a layout this tool cannot edit safely; ${byHand}`);
149
+ }
150
+ }
151
+ /**
152
+ * ~/.config/opencode/opencode.json(c): a `velqa` provider listing the key's chat
153
+ * models (key read from VELQA_API_KEY) and the chosen model as default. Written
154
+ * in opencode 1's `provider` format, which opencode 2 migrates at startup. The
155
+ * file is edited in place, so comments and unrelated settings survive, and
156
+ * fields the user added to the velqa entry or its models are kept.
157
+ */
158
+ export function opencodeConfig(existing, models, model) {
159
+ let text = existing?.trim() ? existing : '{\n "$schema": "https://opencode.ai/config.json"\n}\n';
160
+ const errors = [];
161
+ const config = parseJsonc(text, errors, { allowTrailingComma: true });
162
+ if (errors.length)
163
+ throw new Error("the opencode config has a syntax error; fix it first (https://velqa.dev/docs/opencode)");
164
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
165
+ throw new Error("the opencode config is not a JSON object");
166
+ }
167
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
168
+ const root = record(config);
169
+ const previous = record(record(root.provider).velqa);
170
+ const previousModels = record(previous.models);
171
+ const velqa = {
172
+ ...previous,
173
+ npm: "@ai-sdk/openai-compatible",
174
+ name: typeof previous.name === "string" ? previous.name : "Velqa",
175
+ options: { ...record(previous.options), baseURL: OAI_BASE, apiKey: `{env:${KEY_ENV}}` },
176
+ models: {
177
+ ...previousModels,
178
+ ...Object.fromEntries(models.map((id) => [id, { name: id, ...record(previousModels[id]), limit: modelLimit(id) }])),
179
+ },
180
+ };
181
+ const edit = (path, value) => {
182
+ text = applyEdits(text, modify(text, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2 } }));
183
+ };
184
+ // An entry 0.1.0 wrote in opencode 2's `providers` format would shadow this one.
185
+ if ("velqa" in record(root.providers)) {
186
+ edit(["providers", "velqa"], undefined);
187
+ if (Object.keys(record(root.providers)).length === 1)
188
+ edit(["providers"], undefined);
189
+ }
190
+ edit(["provider", "velqa"], velqa);
191
+ edit(["model"], `velqa/${model}`);
192
+ return text.endsWith("\n") ? text : `${text}\n`;
193
+ }
194
+ const RC_START = "# >>> velqa >>>";
195
+ const RC_END = "# <<< velqa <<<";
196
+ /** Shell rc file: one marked block exporting the key Codex reads, replaced on rerun. */
197
+ export function shellExport(existing, key) {
198
+ const block = [RC_START, `export ${KEY_ENV}="${key}"`, RC_END].join("\n");
199
+ const text = existing ?? "";
200
+ const start = text.indexOf(RC_START);
201
+ const end = text.indexOf(RC_END);
202
+ if (start !== -1 && end > start) {
203
+ return text.slice(0, start) + block + text.slice(end + RC_END.length);
204
+ }
205
+ const sep = text === "" || text.endsWith("\n") ? "" : "\n";
206
+ return `${text}${sep}${text === "" ? "" : "\n"}${block}\n`;
207
+ }
208
+ /** A Velqa key as the dashboard issues it; also keeps quotes out of the files above. */
209
+ export function isPlausibleKey(key) {
210
+ return /^sk-[A-Za-z0-9_-]{8,}$/.test(key);
211
+ }
212
+ function trimBlank(lines) {
213
+ let a = 0;
214
+ let b = lines.length;
215
+ while (a < b && lines[a].trim() === "")
216
+ a++;
217
+ while (b > a && lines[b - 1].trim() === "")
218
+ b--;
219
+ return lines.slice(a, b);
220
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "velqa",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Point Claude Code and Codex at Velqa's open-weight models in one command.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "velqa": "dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "scripts": {
17
+ "build": "tsc -p tsconfig.build.json",
18
+ "test": "node --test --import tsx 'test/**/*.test.ts'",
19
+ "typecheck": "tsc --noEmit",
20
+ "prepublishOnly": "tsc -p tsconfig.build.json"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^24.0.0",
24
+ "tsx": "^4.20.0",
25
+ "typescript": "^5.9.0"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "homepage": "https://velqa.dev/docs/en/integrations-overview",
31
+ "dependencies": {
32
+ "jsonc-parser": "^3.3.1",
33
+ "smol-toml": "^1.9.1"
34
+ }
35
+ }