velqa 0.0.0-stage → 0.1.0

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,21 @@
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`), plus `export VELQA_API_KEY=...` in a marked block of
13
+ `~/.zshrc` or `~/.bashrc`.
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` when it has no comments).
16
+ opencode 2 gets its `providers` format, opencode 1 the older `provider` one; the key is read
17
+ from the same `VELQA_API_KEY`.
18
+
19
+ Every file it changes is backed up next to itself first (`*.velqa-backup-<time>`) and left
20
+ readable by you only. Running it again replaces its own settings instead of duplicating them.
21
+ If `VELQA_API_KEY` is already set, it is used without asking.
package/dist/cli.js ADDED
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, 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
+ const rl = createInterface({ input: stdin, output, terminal: stdin.isTTY });
23
+ // The iterator buffers lines (piped input arrives before the questions) and ends on EOF.
24
+ const lines = rl[Symbol.asyncIterator]();
25
+ async function readLine() {
26
+ const next = await lines.next();
27
+ if (next.done)
28
+ throw new Error("Input closed before setup finished; nothing more was changed.");
29
+ return next.value.trim();
30
+ }
31
+ async function ask(question) {
32
+ stdout.write(question);
33
+ return readLine();
34
+ }
35
+ async function askSecret(question) {
36
+ stdout.write(question);
37
+ muted = true;
38
+ try {
39
+ return await readLine();
40
+ }
41
+ finally {
42
+ muted = false;
43
+ stdout.write("\n");
44
+ }
45
+ }
46
+ async function confirm(question, byDefault) {
47
+ const answer = (await ask(`${question} ${byDefault ? "[Y/n]" : "[y/N]"} `)).toLowerCase();
48
+ return answer === "" ? byDefault : answer.startsWith("y") || answer.startsWith("o");
49
+ }
50
+ function onPath(command) {
51
+ const names = platform === "win32" ? [`${command}.cmd`, `${command}.exe`, command] : [command];
52
+ return (env.PATH ?? "").split(delimiter).some((dir) => dir && names.some((n) => existsSync(join(dir, n))));
53
+ }
54
+ /** opencode 2 changed its config format; unknown (not installed, odd output) means 1. */
55
+ function opencodeMajor() {
56
+ try {
57
+ const out = execFileSync("opencode", ["--version"], { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] });
58
+ return Number(/(\d+)\.\d+/.exec(out)?.[1] ?? 1);
59
+ }
60
+ catch {
61
+ return 1;
62
+ }
63
+ }
64
+ function readOrNull(path) {
65
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
66
+ }
67
+ /** Back up, then write; files carrying the key are readable by the user only. */
68
+ function writeWithBackup(path, content) {
69
+ const before = readOrNull(path);
70
+ if (before === content)
71
+ return;
72
+ if (before !== null) {
73
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
74
+ const backup = `${path}.velqa-backup-${stamp}`;
75
+ copyFileSync(path, backup);
76
+ chmodSync(backup, 0o600);
77
+ }
78
+ mkdirSync(dirname(path), { recursive: true });
79
+ writeFileSync(path, content, { mode: 0o600 });
80
+ chmodSync(path, 0o600); // mode above only applies to new files; this one may now hold the key
81
+ }
82
+ async function fetchJson(url, key) {
83
+ const res = await fetch(url, { headers: key ? { Authorization: `Bearer ${key}` } : {} });
84
+ return { status: res.status, body: res.ok ? await res.json() : null };
85
+ }
86
+ async function chatModelsFor(key) {
87
+ const keyModels = await fetchJson(`${OAI_BASE}/models`, key);
88
+ if (keyModels.status === 401 || keyModels.status === 403) {
89
+ throw new Error("Velqa refused this key (revoked or mistyped). Create one at https://velqa.dev/dashboard/keys");
90
+ }
91
+ if (keyModels.status !== 200)
92
+ throw new Error(`Velqa answered ${keyModels.status} while checking the key; try again shortly.`);
93
+ const allowed = new Set((keyModels.body.data ?? []).map((m) => m.id));
94
+ const catalog = await fetchJson(`${ANTHROPIC_BASE}/api/models`);
95
+ const chat = (catalog.body?.models ?? [])
96
+ .filter((m) => m.mode === "chat")
97
+ .map((m) => m.id);
98
+ const usable = chat.filter((id) => allowed.has(id));
99
+ return usable.length > 0 ? usable : [...allowed];
100
+ }
101
+ async function pickModel(models) {
102
+ const fallback = models.includes(DEFAULT_MODEL) ? DEFAULT_MODEL : models[0];
103
+ models.forEach((id, i) => stdout.write(` ${String(i + 1).padStart(2)}. ${id}${id === fallback ? " (recommended)" : ""}\n`));
104
+ const answer = await ask(`Model [${fallback}]: `);
105
+ if (answer === "")
106
+ return fallback;
107
+ const byNumber = models[Number(answer) - 1];
108
+ if (byNumber)
109
+ return byNumber;
110
+ if (models.includes(answer))
111
+ return answer;
112
+ throw new Error(`Unknown model "${answer}".`);
113
+ }
114
+ function rcFile() {
115
+ const shell = basename(env.SHELL ?? "");
116
+ if (shell === "zsh")
117
+ return join(homedir(), ".zshrc");
118
+ if (shell === "bash")
119
+ return join(homedir(), platform === "darwin" ? ".bash_profile" : ".bashrc");
120
+ return null;
121
+ }
122
+ async function init() {
123
+ stdout.write("Velqa: point Claude Code, Codex and opencode at open-weight models.\n\n");
124
+ const fromEnv = env[KEY_ENV]?.trim();
125
+ const key = fromEnv && isPlausibleKey(fromEnv) ? fromEnv : await askSecret("Velqa API key (sk-..., input hidden): ");
126
+ if (!isPlausibleKey(key))
127
+ throw new Error("That does not look like a Velqa key (it starts with sk-).");
128
+ const models = await chatModelsFor(key);
129
+ if (models.length === 0)
130
+ throw new Error("This key has access to no chat model.");
131
+ stdout.write("Key accepted. Chat models available to it:\n");
132
+ const model = await pickModel(models);
133
+ const done = [];
134
+ if (await confirm(`Configure Claude Code${onPath("claude") ? "" : " (not found on PATH)"}?`, onPath("claude"))) {
135
+ const path = join(homedir(), ".claude", "settings.json");
136
+ writeWithBackup(path, claudeSettings(readOrNull(path), key, model));
137
+ done.push(`Claude Code: ${path}\n try: claude "explain this repo in 3 sentences"`);
138
+ }
139
+ let needsKeyEnv = false;
140
+ if (await confirm(`Configure Codex${onPath("codex") ? "" : " (not found on PATH)"}?`, onPath("codex"))) {
141
+ const codexHome = env.CODEX_HOME || join(homedir(), ".codex");
142
+ const path = join(codexHome, "config.toml");
143
+ writeWithBackup(path, codexConfig(readOrNull(path), model));
144
+ done.push(`Codex: ${path}\n then: codex`);
145
+ needsKeyEnv = true;
146
+ }
147
+ if (await confirm(`Configure opencode${onPath("opencode") ? "" : " (not found on PATH)"}?`, onPath("opencode"))) {
148
+ const dir = join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode");
149
+ const jsonc = join(dir, "opencode.jsonc");
150
+ const path = existsSync(jsonc) ? jsonc : join(dir, "opencode.json");
151
+ writeWithBackup(path, opencodeConfig(readOrNull(path), models, model, opencodeMajor() >= 2));
152
+ done.push(`opencode: ${path}\n then: opencode (switch models with /models)`);
153
+ needsKeyEnv = true;
154
+ }
155
+ if (needsKeyEnv) {
156
+ const rc = rcFile();
157
+ if (rc) {
158
+ writeWithBackup(rc, shellExport(readOrNull(rc), key));
159
+ done.push(`${KEY_ENV} exported in ${rc}: open a new terminal (or: source ${rc}) first`);
160
+ }
161
+ else {
162
+ const how = platform === "win32" ? `setx ${KEY_ENV} "${key}"` : `export ${KEY_ENV}="${key}"`;
163
+ done.push(`set the key in your shell profile yourself: ${how}`);
164
+ }
165
+ }
166
+ stdout.write(done.length ? `\nDone.\n${done.map((d) => `- ${d}`).join("\n")}\n` : "\nNothing configured.\n");
167
+ }
168
+ const command = argv[2] ?? "init";
169
+ if (command === "-h" || command === "--help" || command === "help") {
170
+ stdout.write(`${HELP}\n`);
171
+ exit(0);
172
+ }
173
+ if (command !== "init") {
174
+ stdout.write(`Unknown command "${command}".\n\n${HELP}\n`);
175
+ exit(1);
176
+ }
177
+ init()
178
+ .then(() => {
179
+ rl.close();
180
+ })
181
+ .catch((error) => {
182
+ rl.close();
183
+ stdout.write(`\nError: ${error instanceof Error ? error.message : String(error)}\n`);
184
+ exit(1);
185
+ });
package/dist/config.js ADDED
@@ -0,0 +1,155 @@
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
+ export const OAI_BASE = "https://api.velqa.dev/v1";
5
+ export const ANTHROPIC_BASE = "https://api.velqa.dev";
6
+ export const DEFAULT_MODEL = "glm-5.3-flash";
7
+ export const SMALL_FAST_MODEL = "glm-5.3-flash";
8
+ export const KEY_ENV = "VELQA_API_KEY";
9
+ // Mirrors MODEL_LIMITS in apps/web/src/lib/tools.ts (the dashboard snippets).
10
+ // shortcut: duplicated because /api/models carries no context window; serve it there if this drifts.
11
+ const MODEL_LIMITS = {
12
+ "kimi-k2.6": { context: 131072, output: 16384 },
13
+ "minimax-m3": { context: 131072, output: 16384 },
14
+ "hy3": { context: 262144, output: 16384 },
15
+ "mimo-v2.5": { context: 262144, output: 16384 },
16
+ "mimo-v2.6-flash": { context: 262144, output: 16384 },
17
+ "deepseek-v4-pro": { context: 160000, output: 16384 },
18
+ "deepseek-v4-flash": { context: 65536, output: 8192 },
19
+ "glm-4.7": { context: 131072, output: 16384 },
20
+ "glm-4.7-flash": { context: 200000, output: 16384 },
21
+ "glm-5.3-flash": { context: 200000, output: 16384 },
22
+ "glm-5.2": { context: 131072, output: 16384 },
23
+ };
24
+ export function modelLimit(model) {
25
+ return MODEL_LIMITS[model] ?? { context: 131072, output: 16384 };
26
+ }
27
+ /** ~/.claude/settings.json: set Velqa's variables in `env`, keep everything else. */
28
+ export function claudeSettings(existing, key, model) {
29
+ const settings = existing?.trim() ? JSON.parse(existing) : {};
30
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
31
+ throw new Error("~/.claude/settings.json is not a JSON object");
32
+ }
33
+ const env = typeof settings.env === "object" && settings.env !== null && !Array.isArray(settings.env)
34
+ ? settings.env
35
+ : {};
36
+ settings.env = {
37
+ ...env,
38
+ ANTHROPIC_BASE_URL: ANTHROPIC_BASE,
39
+ ANTHROPIC_AUTH_TOKEN: key,
40
+ ANTHROPIC_MODEL: model,
41
+ ANTHROPIC_SMALL_FAST_MODEL: SMALL_FAST_MODEL,
42
+ CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(modelLimit(model).output),
43
+ };
44
+ return JSON.stringify(settings, null, 2) + "\n";
45
+ }
46
+ const CODEX_TOP_KEYS = /^\s*(model|model_provider|model_context_window)\s*=/;
47
+ const TABLE_HEADER = /^\s*\[/;
48
+ const VELQA_TABLE = /^\s*\[model_providers\.velqa\]\s*(#.*)?$/;
49
+ /**
50
+ * ~/.codex/config.toml: Codex reads `model`, `model_provider` and
51
+ * `model_context_window` only before the first [table], so they are replaced
52
+ * there and our provider table replaces any previous [model_providers.velqa].
53
+ * Other keys, tables and [profiles.*] are left untouched.
54
+ */
55
+ export function codexConfig(existing, model) {
56
+ const lines = (existing ?? "").split("\n");
57
+ const firstTable = lines.findIndex((line) => TABLE_HEADER.test(line));
58
+ const topEnd = firstTable === -1 ? lines.length : firstTable;
59
+ const top = lines.slice(0, topEnd).filter((line) => !CODEX_TOP_KEYS.test(line));
60
+ const rest = [];
61
+ let inVelqaTable = false;
62
+ for (const line of lines.slice(topEnd)) {
63
+ if (TABLE_HEADER.test(line))
64
+ inVelqaTable = VELQA_TABLE.test(line);
65
+ if (!inVelqaTable)
66
+ rest.push(line);
67
+ }
68
+ const ours = [
69
+ `model = "${model}"`,
70
+ `model_provider = "velqa"`,
71
+ `model_context_window = ${modelLimit(model).context}`,
72
+ ];
73
+ const table = [
74
+ "[model_providers.velqa]",
75
+ 'name = "Velqa"',
76
+ `base_url = "${OAI_BASE}"`,
77
+ `env_key = "${KEY_ENV}"`,
78
+ 'wire_api = "responses"',
79
+ ];
80
+ const body = [...ours, ...trimBlank(top), "", ...trimBlank(rest)];
81
+ return [...trimBlank(body), "", ...table, ""].join("\n");
82
+ }
83
+ /**
84
+ * ~/.config/opencode/opencode.json: a `velqa` provider listing the key's chat
85
+ * models (key read from VELQA_API_KEY) and the chosen model as default.
86
+ * opencode 2 reads `providers` (package + settings.baseURL); opencode 1, still
87
+ * the npm `latest`, only knows `provider` (npm + options), which 2 migrates.
88
+ * The entry in the other format is removed so the two never disagree.
89
+ */
90
+ export function opencodeConfig(existing, models, model, v2) {
91
+ let config;
92
+ try {
93
+ config = existing?.trim() ? JSON.parse(existing) : {};
94
+ }
95
+ catch {
96
+ throw new Error("the opencode config has comments or trailing commas; add the Velqa provider by hand (https://velqa.dev/docs/opencode)");
97
+ }
98
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
99
+ throw new Error("the opencode config is not a JSON object");
100
+ }
101
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? { ...value } : {};
102
+ const modelMap = Object.fromEntries(models.map((id) => [id, { name: id, limit: modelLimit(id) }]));
103
+ const ours = v2
104
+ ? {
105
+ name: "Velqa",
106
+ env: [KEY_ENV],
107
+ package: "@opencode/ai/providers/openai-compatible",
108
+ settings: { baseURL: OAI_BASE },
109
+ models: modelMap,
110
+ }
111
+ : {
112
+ npm: "@ai-sdk/openai-compatible",
113
+ name: "Velqa",
114
+ options: { baseURL: OAI_BASE, apiKey: `{env:${KEY_ENV}}` },
115
+ models: modelMap,
116
+ };
117
+ const [mine, other] = v2 ? ["providers", "provider"] : ["provider", "providers"];
118
+ const stale = record(config[other]);
119
+ if ("velqa" in stale) {
120
+ delete stale.velqa;
121
+ if (Object.keys(stale).length)
122
+ config[other] = stale;
123
+ else
124
+ delete config[other];
125
+ }
126
+ config[mine] = { ...record(config[mine]), velqa: ours };
127
+ return JSON.stringify({ $schema: "https://opencode.ai/config.json", ...config, model: `velqa/${model}` }, null, 2) + "\n";
128
+ }
129
+ const RC_START = "# >>> velqa >>>";
130
+ const RC_END = "# <<< velqa <<<";
131
+ /** Shell rc file: one marked block exporting the key Codex reads, replaced on rerun. */
132
+ export function shellExport(existing, key) {
133
+ const block = [RC_START, `export ${KEY_ENV}="${key}"`, RC_END].join("\n");
134
+ const text = existing ?? "";
135
+ const start = text.indexOf(RC_START);
136
+ const end = text.indexOf(RC_END);
137
+ if (start !== -1 && end > start) {
138
+ return text.slice(0, start) + block + text.slice(end + RC_END.length);
139
+ }
140
+ const sep = text === "" || text.endsWith("\n") ? "" : "\n";
141
+ return `${text}${sep}${text === "" ? "" : "\n"}${block}\n`;
142
+ }
143
+ /** A Velqa key as the dashboard issues it; also keeps quotes out of the files above. */
144
+ export function isPlausibleKey(key) {
145
+ return /^sk-[A-Za-z0-9_-]{8,}$/.test(key);
146
+ }
147
+ function trimBlank(lines) {
148
+ let a = 0;
149
+ let b = lines.length;
150
+ while (a < b && lines[a].trim() === "")
151
+ a++;
152
+ while (b > a && lines[b - 1].trim() === "")
153
+ b--;
154
+ return lines.slice(a, b);
155
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
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.0",
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
+ }