@arthovlabs/liber 0.0.0-stage → 0.5.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 +21 -0
- package/README.md +348 -2
- package/bin/liber +706 -0
- package/bin/liber-tui +244 -0
- package/bin/liber-tui.py +825 -0
- package/bin/liberd-entry +17 -0
- package/liber.yaml +84 -0
- package/package.json +43 -4
- package/resources/icons/appIcon.png +0 -0
- package/resources/icons/appIcon.svg +20 -0
- package/resources/icons/appIcon@512.png +0 -0
- package/resources/icons/atom-transparent-256.png +0 -0
- package/resources/icons/atom-transparent.png +0 -0
- package/resources/icons/atom-transparent.svg +19 -0
- package/resources/icons/make-atom.js +168 -0
- package/src/cli/ui.js +520 -0
- package/src/daemon/core/auth.js +217 -0
- package/src/daemon/core/automations.js +130 -0
- package/src/daemon/core/budget.js +145 -0
- package/src/daemon/core/circuit-breaker.js +31 -0
- package/src/daemon/core/config-apply.js +223 -0
- package/src/daemon/core/connectors.js +131 -0
- package/src/daemon/core/engine.js +1029 -0
- package/src/daemon/core/evidence.js +306 -0
- package/src/daemon/core/executor.js +10 -0
- package/src/daemon/core/grounding.js +420 -0
- package/src/daemon/core/injection.js +24 -0
- package/src/daemon/core/journal.js +81 -0
- package/src/daemon/core/liber-soul.js +157 -0
- package/src/daemon/core/lock.js +32 -0
- package/src/daemon/core/memory.js +106 -0
- package/src/daemon/core/model-switch.js +58 -0
- package/src/daemon/core/policy.js +102 -0
- package/src/daemon/core/providers.js +503 -0
- package/src/daemon/core/registry.js +356 -0
- package/src/daemon/core/secrets.js +35 -0
- package/src/daemon/core/skills.js +264 -0
- package/src/daemon/core/tools/browser-tool.js +280 -0
- package/src/daemon/core/tools/file-tools.js +277 -0
- package/src/daemon/core/tools/memory-tool.js +127 -0
- package/src/daemon/core/tools/skill-tool.js +44 -0
- package/src/daemon/core/tools/task-tool.js +41 -0
- package/src/daemon/core/tools/terminal-tool.js +449 -0
- package/src/daemon/core/tools/todo-tool.js +100 -0
- package/src/daemon/core/tools/web-tool.js +181 -0
- package/src/daemon/core/trace.js +40 -0
- package/src/daemon/core/validate.js +105 -0
- package/src/daemon/core/vault.js +158 -0
- package/src/daemon/core/verifier.js +98 -0
- package/src/daemon/core/voice.js +83 -0
- package/src/daemon/core/workspace.js +199 -0
- package/src/daemon/liberd.js +1343 -0
- package/src/daemon/llm/adapters/anthropic-adapter.js +190 -0
- package/src/daemon/llm/adapters/gemini-adapter.js +148 -0
- package/src/daemon/llm/adapters/ollama-adapter.js +74 -0
- package/src/daemon/llm/adapters/openai-adapter.js +148 -0
- package/src/daemon/llm/base.js +31 -0
- package/src/daemon/llm/manager.js +134 -0
- package/src/utils/config-loader.js +109 -0
- package/src/utils/logger.js +56 -0
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
// src/daemon/core/providers.js — provider catalog, credential store, live checks.
|
|
2
|
+
//
|
|
3
|
+
// Keys live in .liber/credentials.json (mode 0600). Nothing here ever returns a
|
|
4
|
+
// secret to a client: status() reports presence, source and a last-4 hint only.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const vault = require('./vault');
|
|
8
|
+
const os = require('os');
|
|
9
|
+
const { execFileSync } = require('child_process');
|
|
10
|
+
|
|
11
|
+
const STORE = () => path.resolve(process.cwd(), '.liber', 'credentials.json');
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Environment values, including the project's .env file. The daemon resolves
|
|
15
|
+
* keys from .env at boot, so the Providers page must report the same truth.
|
|
16
|
+
*/
|
|
17
|
+
let dotenvCache = null;
|
|
18
|
+
let dotenvMtime = 0;
|
|
19
|
+
function dotenv() {
|
|
20
|
+
try {
|
|
21
|
+
const file = path.resolve(process.cwd(), '.env');
|
|
22
|
+
const st = fs.statSync(file);
|
|
23
|
+
if (dotenvCache && st.mtimeMs === dotenvMtime) return dotenvCache;
|
|
24
|
+
const map = {};
|
|
25
|
+
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
26
|
+
const t = line.trim();
|
|
27
|
+
if (!t || t.startsWith('#') || !t.includes('=')) continue;
|
|
28
|
+
const i = t.indexOf('=');
|
|
29
|
+
const k = t.slice(0, i).trim();
|
|
30
|
+
let v = t.slice(i + 1).trim();
|
|
31
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
|
|
32
|
+
if (k) map[k] = v;
|
|
33
|
+
}
|
|
34
|
+
dotenvCache = map;
|
|
35
|
+
dotenvMtime = st.mtimeMs;
|
|
36
|
+
return map;
|
|
37
|
+
} catch {
|
|
38
|
+
dotenvCache = {};
|
|
39
|
+
return dotenvCache;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function envValue(name) {
|
|
44
|
+
if (!name) return null;
|
|
45
|
+
if (process.env[name]) return process.env[name];
|
|
46
|
+
const v = dotenv()[name];
|
|
47
|
+
return v || null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** adapter: how the daemon talks to it. kind: api | local | custom */
|
|
51
|
+
const CATALOG = [
|
|
52
|
+
// — OpenAI-compatible cloud APIs
|
|
53
|
+
{ id: 'openai', label: 'OpenAI', adapter: 'openai', base: 'https://api.openai.com/v1', env: 'OPENAI_API_KEY', docs: 'platform.openai.com/api-keys', kind: 'api' },
|
|
54
|
+
{ id: 'anthropic', label: 'Anthropic', adapter: 'anthropic', base: 'https://api.anthropic.com', env: 'ANTHROPIC_API_KEY', docs: 'console.anthropic.com', kind: 'api' },
|
|
55
|
+
{ id: 'google', label: 'Google Gemini', adapter: 'gemini', base: 'https://generativelanguage.googleapis.com', env: 'GEMINI_API_KEY', docs: 'aistudio.google.com/apikey', kind: 'api' },
|
|
56
|
+
{ id: 'xai', label: 'xAI Grok', adapter: 'openai', base: 'https://api.x.ai/v1', env: 'XAI_API_KEY', docs: 'console.x.ai', kind: 'api' },
|
|
57
|
+
{ id: 'groq', label: 'Groq', adapter: 'openai', base: 'https://api.groq.com/openai/v1', env: 'GROQ_API_KEY', docs: 'console.groq.com/keys', kind: 'api' },
|
|
58
|
+
{ id: 'mistral', label: 'Mistral', adapter: 'openai', base: 'https://api.mistral.ai/v1', env: 'MISTRAL_API_KEY', docs: 'console.mistral.ai', kind: 'api' },
|
|
59
|
+
{ id: 'deepseek', label: 'DeepSeek', adapter: 'openai', base: 'https://api.deepseek.com/v1', env: 'DEEPSEEK_API_KEY', docs: 'platform.deepseek.com', kind: 'api' },
|
|
60
|
+
{ id: 'together', label: 'Together AI', adapter: 'openai', base: 'https://api.together.xyz/v1', env: 'TOGETHER_API_KEY', docs: 'api.together.ai/settings/api-keys', kind: 'api' },
|
|
61
|
+
{ id: 'openrouter', label: 'OpenRouter', adapter: 'openai', base: 'https://openrouter.ai/api/v1', env: 'OPENROUTER_API_KEY', docs: 'openrouter.ai/keys', kind: 'api' },
|
|
62
|
+
{ id: 'fireworks', label: 'Fireworks AI', adapter: 'openai', base: 'https://api.fireworks.ai/inference/v1', env: 'FIREWORKS_API_KEY', docs: 'fireworks.ai/account/api-keys', kind: 'api' },
|
|
63
|
+
{ id: 'cerebras', label: 'Cerebras', adapter: 'openai', base: 'https://api.cerebras.ai/v1', env: 'CEREBRAS_API_KEY', docs: 'cloud.cerebras.ai', kind: 'api' },
|
|
64
|
+
{ id: 'sambanova', label: 'SambaNova', adapter: 'openai', base: 'https://api.sambanova.ai/v1', env: 'SAMBANOVA_API_KEY', docs: 'cloud.sambanova.ai', kind: 'api' },
|
|
65
|
+
{ id: 'novita', label: 'Novita AI', adapter: 'openai', base: 'https://api.novita.ai/v3/openai', env: 'NOVITA_API_KEY', docs: 'novita.ai/settings/key-management', kind: 'api' },
|
|
66
|
+
{ id: 'hyperbolic', label: 'Hyperbolic', adapter: 'openai', base: 'https://api.hyperbolic.xyz/v1', env: 'HYPERBOLIC_API_KEY', docs: 'app.hyperbolic.xyz/settings', kind: 'api' },
|
|
67
|
+
{ id: 'deepinfra', label: 'DeepInfra', adapter: 'openai', base: 'https://api.deepinfra.com/v1/openai', env: 'DEEPINFRA_API_KEY', docs: 'deepinfra.com/dash/api_keys', kind: 'api' },
|
|
68
|
+
{ id: 'nebius', label: 'Nebius AI Studio', adapter: 'openai', base: 'https://api.studio.nebius.ai/v1', env: 'NEBIUS_API_KEY', docs: 'studio.nebius.ai', kind: 'api' },
|
|
69
|
+
{ id: 'lambda', label: 'Lambda Labs', adapter: 'openai', base: 'https://api.lambdalabs.com/v1', env: 'LAMBDA_API_KEY', docs: 'cloud.lambdalabs.com/api-keys', kind: 'api' },
|
|
70
|
+
{ id: 'perplexity', label: 'Perplexity', adapter: 'openai', base: 'https://api.perplexity.ai', env: 'PERPLEXITY_API_KEY', docs: 'perplexity.ai/settings/api', kind: 'api' },
|
|
71
|
+
{ id: 'cohere', label: 'Cohere', adapter: 'openai', base: 'https://api.cohere.ai/compatibility/v1', env: 'COHERE_API_KEY', docs: 'dashboard.cohere.com/api-keys', kind: 'api' },
|
|
72
|
+
{ id: 'ai21', label: 'AI21 Labs', adapter: 'openai', base: 'https://api.ai21.com/studio/v1', env: 'AI21_API_KEY', docs: 'studio.ai21.com/account/api-key', kind: 'api' },
|
|
73
|
+
{ id: 'reka', label: 'Reka', adapter: 'openai', base: 'https://api.reka.ai/v1', env: 'REKA_API_KEY', docs: 'platform.reka.ai', kind: 'api' },
|
|
74
|
+
// — China / Asia providers
|
|
75
|
+
{ id: 'moonshot', label: 'Moonshot Kimi', adapter: 'openai', base: 'https://api.moonshot.ai/v1', env: 'MOONSHOT_API_KEY', docs: 'platform.moonshot.ai', kind: 'api' },
|
|
76
|
+
{ id: 'zai', label: 'Z.ai (GLM)', adapter: 'openai', base: 'https://api.z.ai/api/paas/v4', env: 'ZAI_API_KEY', docs: 'z.ai/manage-apikey', kind: 'api' },
|
|
77
|
+
{ id: 'qwen', label: 'Alibaba DashScope (Qwen)', adapter: 'openai', base: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1', env: 'DASHSCOPE_API_KEY', docs: 'bailian.console.alibabacloud.com', kind: 'api' },
|
|
78
|
+
{ id: 'minimax', label: 'MiniMax', adapter: 'openai', base: 'https://api.minimax.io/v1', env: 'MINIMAX_API_KEY', docs: 'platform.minimax.io', kind: 'api' },
|
|
79
|
+
{ id: 'stepfun', label: 'StepFun', adapter: 'openai', base: 'https://api.stepfun.ai/v1', env: 'STEPFUN_API_KEY', docs: 'platform.stepfun.ai', kind: 'api' },
|
|
80
|
+
{ id: 'bytedance', label: 'ByteDance Ark (Doubao)', adapter: 'openai', base: 'https://ark.cn-beijing.volces.com/api/v3', env: 'ARK_API_KEY', docs: 'console.volcengine.com/ark', kind: 'api' },
|
|
81
|
+
{ id: 'baidu', label: 'Baidu Qianfan', adapter: 'openai', base: 'https://qianfan.baidubce.com/v2', env: 'QIANFAN_API_KEY', docs: 'console.bce.baidu.com', kind: 'api' },
|
|
82
|
+
{ id: 'lingyi', label: '01.AI (Yi)', adapter: 'openai', base: 'https://api.lingyiwanwu.com/v1', env: 'LINGYI_API_KEY', docs: 'platform.lingyiwanwu.com', kind: 'api' },
|
|
83
|
+
{ id: 'siliconflow', label: 'SiliconFlow', adapter: 'openai', base: 'https://api.siliconflow.cn/v1', env: 'SILICONFLOW_API_KEY', docs: 'cloud.siliconflow.cn', kind: 'api' },
|
|
84
|
+
{ id: 'upstage', label: 'Upstage', adapter: 'openai', base: 'https://api.upstage.ai/v1', env: 'UPSTAGE_API_KEY', docs: 'console.upstage.ai', kind: 'api' },
|
|
85
|
+
// — gateways / aggregators
|
|
86
|
+
{ id: 'github-models', label: 'GitHub Models', adapter: 'openai', base: 'https://models.inference.ai.azure.com', env: 'GITHUB_TOKEN', docs: 'github.com/settings/tokens', kind: 'api' },
|
|
87
|
+
{ id: 'azure-openai', label: 'Azure OpenAI', adapter: 'openai', base: '', env: 'AZURE_OPENAI_API_KEY', docs: 'portal.azure.com', kind: 'custom' },
|
|
88
|
+
{ id: 'cloudflare', label: 'Cloudflare Workers AI', adapter: 'openai', base: 'https://api.cloudflare.com/client/v4/accounts/<account>/ai/v1', env: 'CLOUDFLARE_API_TOKEN', docs: 'dash.cloudflare.com/profile/api-tokens', kind: 'custom' },
|
|
89
|
+
{ id: 'ollama-cloud', label: 'Ollama Cloud', adapter: 'openai', base: 'https://ollama.com/v1', env: 'OLLAMA_CLOUD_API_KEY', docs: 'ollama.com/settings/keys', kind: 'api' },
|
|
90
|
+
// — local runtimes (no key)
|
|
91
|
+
{ id: 'ollama', label: 'Ollama (local)', adapter: 'ollama', base: 'http://localhost:11434', env: 'OLLAMA_HOST', docs: 'ollama.com', kind: 'local' },
|
|
92
|
+
{ id: 'lmstudio', label: 'LM Studio', adapter: 'openai', base: 'http://localhost:1234/v1', env: 'LMSTUDIO_API_KEY', docs: 'lmstudio.ai', kind: 'local' },
|
|
93
|
+
{ id: 'llamacpp', label: 'llama.cpp server', adapter: 'openai', base: 'http://localhost:8080/v1', env: 'LLAMACPP_API_KEY', docs: 'github.com/ggml-org/llama.cpp', kind: 'local' },
|
|
94
|
+
{ id: 'vllm', label: 'vLLM', adapter: 'openai', base: 'http://localhost:8000/v1', env: 'VLLM_API_KEY', docs: 'docs.vllm.ai', kind: 'local' },
|
|
95
|
+
{ id: 'tabby', label: 'TabbyAPI', adapter: 'openai', base: 'http://localhost:5000/v1', env: 'TABBY_API_KEY', docs: 'github.com/theroyallab/tabbyAPI', kind: 'local' }
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Subscription sign-in sources. We import what the vendor's own CLI already
|
|
100
|
+
* stored — never passwords, never a fabricated OAuth client.
|
|
101
|
+
*/
|
|
102
|
+
const IMPORTS = [
|
|
103
|
+
{
|
|
104
|
+
id: 'claude-code', label: 'Claude Code (Claude Pro/Max)',
|
|
105
|
+
file: () => path.join(os.homedir(), '.claude', '.credentials.json'),
|
|
106
|
+
pick: (j) => {
|
|
107
|
+
const o = j.claudeAiOauth || j;
|
|
108
|
+
return { access_token: o.accessToken || o.access_token, refresh_token: o.refreshToken || o.refresh_token, expires_at: o.expiresAt || o.expires_at, plan: o.subscriptionType || null };
|
|
109
|
+
},
|
|
110
|
+
provider: 'anthropic'
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
id: 'gemini-cli', label: 'Gemini CLI (Google account)',
|
|
114
|
+
file: () => path.join(os.homedir(), '.gemini', 'oauth_creds.json'),
|
|
115
|
+
pick: (j) => ({ access_token: j.access_token, refresh_token: j.refresh_token, expires_at: j.expiry_date, id_token: j.id_token }),
|
|
116
|
+
provider: 'google'
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
id: 'codex-cli', label: 'Codex CLI (ChatGPT plan)',
|
|
120
|
+
file: () => path.join(os.homedir(), '.codex', 'auth.json'),
|
|
121
|
+
pick: (j) => ({ access_token: j.tokens?.access_token || j.OPENAI_API_KEY, refresh_token: j.tokens?.refresh_token, account: j.tokens?.account_id || null }),
|
|
122
|
+
provider: 'openai'
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
id: 'qwen-code', label: 'Qwen Code CLI',
|
|
126
|
+
file: () => path.join(os.homedir(), '.qwen', 'oauth_creds.json'),
|
|
127
|
+
pick: (j) => ({ access_token: j.access_token, refresh_token: j.refresh_token, expires_at: j.expiry_date }),
|
|
128
|
+
provider: 'qwen'
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
id: 'github-copilot', label: 'GitHub CLI / Copilot',
|
|
132
|
+
file: () => path.join(os.homedir(), '.config', 'gh', 'hosts.yml'),
|
|
133
|
+
exec: () => {
|
|
134
|
+
try { return execFileSync('gh', ['auth', 'token'], { encoding: 'utf8', timeout: 4000, windowsHide: true }).trim(); } catch { return null; }
|
|
135
|
+
},
|
|
136
|
+
pick: () => ({}),
|
|
137
|
+
provider: 'github-models'
|
|
138
|
+
}
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
function readStore() {
|
|
142
|
+
try {
|
|
143
|
+
const raw = fs.readFileSync(STORE(), 'utf8');
|
|
144
|
+
const json = JSON.parse(raw);
|
|
145
|
+
return json && typeof json === 'object' ? json : { version: 1, providers: {} };
|
|
146
|
+
} catch {
|
|
147
|
+
return { version: 1, providers: {} };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function writeStore(store) {
|
|
152
|
+
const file = STORE();
|
|
153
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
154
|
+
const tmp = file + '.tmp';
|
|
155
|
+
fs.writeFileSync(tmp, JSON.stringify(store, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
156
|
+
fs.renameSync(tmp, file);
|
|
157
|
+
try { fs.chmodSync(file, 0o600); } catch { /* Windows ACLs */ }
|
|
158
|
+
return file;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function hint(secret) {
|
|
162
|
+
const s = String(secret || '');
|
|
163
|
+
if (!s) return null;
|
|
164
|
+
return s.length <= 8 ? '••••' : s.slice(0, 3) + '…' + s.slice(-4);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function entryFor(id) {
|
|
168
|
+
return CATALOG.find(p => p.id === id) || null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Store a manual API key (or OAuth token) for a provider or a custom endpoint. */
|
|
172
|
+
function setKey(id, key, extra = {}) {
|
|
173
|
+
const s = String(key || '').trim();
|
|
174
|
+
if (!s) return { ok: false, error: 'Empty key.' };
|
|
175
|
+
if (s.length < 8) return { ok: false, error: 'Key looks too short to be valid.' };
|
|
176
|
+
const store = readStore();
|
|
177
|
+
store.providers[id] = {
|
|
178
|
+
api_key: s,
|
|
179
|
+
source: 'manual',
|
|
180
|
+
updated_at: new Date().toISOString(),
|
|
181
|
+
...extra
|
|
182
|
+
};
|
|
183
|
+
writeStore(store);
|
|
184
|
+
return { ok: true, id, hint: hint(s) };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function setToken(id, token, meta = {}) {
|
|
188
|
+
const s = String(token || '').trim();
|
|
189
|
+
if (!s) return { ok: false, error: 'Empty token.' };
|
|
190
|
+
const store = readStore();
|
|
191
|
+
store.providers[id] = {
|
|
192
|
+
access_token: s,
|
|
193
|
+
refresh_token: meta.refresh_token || null,
|
|
194
|
+
expires_at: meta.expires_at || null,
|
|
195
|
+
plan: meta.plan || null,
|
|
196
|
+
source: meta.source || 'oauth',
|
|
197
|
+
updated_at: new Date().toISOString()
|
|
198
|
+
};
|
|
199
|
+
writeStore(store);
|
|
200
|
+
return { ok: true, id, hint: hint(s) };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function clear(id) {
|
|
204
|
+
const store = readStore();
|
|
205
|
+
if (!store.providers[id]) return { ok: false, error: 'Nothing stored for ' + id };
|
|
206
|
+
delete store.providers[id];
|
|
207
|
+
writeStore(store);
|
|
208
|
+
return { ok: true, id };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function setCustom({ label, base, api_key, adapter }) {
|
|
212
|
+
if (!label || !base) return { ok: false, error: 'label and base are required.' };
|
|
213
|
+
if (!/^https?:\/\/\S+$/.test(base)) return { ok: false, error: 'base must be an http(s) URL.' };
|
|
214
|
+
const id = 'custom:' + String(label).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40);
|
|
215
|
+
const store = readStore();
|
|
216
|
+
store.providers[id] = {
|
|
217
|
+
label, base,
|
|
218
|
+
adapter: ['openai', 'anthropic', 'gemini', 'ollama'].includes(adapter) ? adapter : 'openai',
|
|
219
|
+
api_key: api_key ? String(api_key).trim() : null,
|
|
220
|
+
source: 'custom',
|
|
221
|
+
updated_at: new Date().toISOString()
|
|
222
|
+
};
|
|
223
|
+
writeStore(store);
|
|
224
|
+
return { ok: true, id };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Store-only resolution (no environment): what config-loader trusts first. */
|
|
228
|
+
function resolveStored(providerId, endpoint) {
|
|
229
|
+
const store = readStore();
|
|
230
|
+
const direct = store.providers[providerId];
|
|
231
|
+
if (direct?.api_key) return vault.resolveRef(direct.api_key);
|
|
232
|
+
if (direct?.access_token) return vault.resolveRef(direct.access_token);
|
|
233
|
+
const ep = String(endpoint || '').toLowerCase();
|
|
234
|
+
if (ep) {
|
|
235
|
+
for (const [id, p] of Object.entries(store.providers)) {
|
|
236
|
+
const base = String(p.base || (entryFor(id) || {}).base || '').toLowerCase();
|
|
237
|
+
if (base && ep.startsWith(base.replace(/\/$/, ''))) {
|
|
238
|
+
if (p.api_key) return vault.resolveRef(p.api_key);
|
|
239
|
+
if (p.access_token) return vault.resolveRef(p.access_token);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Resolution order: stored credential → endpoint-matched store → provider env. */
|
|
247
|
+
function resolve(providerId, endpoint) {
|
|
248
|
+
const store = readStore();
|
|
249
|
+
const direct = store.providers[providerId];
|
|
250
|
+
if (direct?.api_key) return vault.resolveRef(direct.api_key);
|
|
251
|
+
if (direct?.access_token) return vault.resolveRef(direct.access_token);
|
|
252
|
+
|
|
253
|
+
// endpoint match (custom endpoints and shared bases)
|
|
254
|
+
const ep = String(endpoint || '').toLowerCase();
|
|
255
|
+
if (ep) {
|
|
256
|
+
for (const [id, p] of Object.entries(store.providers)) {
|
|
257
|
+
const base = String(p.base || (entryFor(id) || {}).base || '').toLowerCase();
|
|
258
|
+
if (base && ep.startsWith(base.replace(/\/$/, ''))) {
|
|
259
|
+
if (p.api_key) return vault.resolveRef(p.api_key);
|
|
260
|
+
if (p.access_token) return vault.resolveRef(p.access_token);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// registry entry whose base matches the endpoint (Groq/DeepSeek/… env)
|
|
264
|
+
const byBase = CATALOG.find(p => p.base && ep.startsWith(p.base.toLowerCase().replace(/\/$/, '')));
|
|
265
|
+
if (byBase?.env && envValue(byBase.env)) return envValue(byBase.env);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const meta = entryFor(providerId);
|
|
269
|
+
if (meta?.env && envValue(meta.env)) return envValue(meta.env);
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Public status: never the secret itself. */
|
|
274
|
+
function status() {
|
|
275
|
+
const store = readStore();
|
|
276
|
+
const rows = CATALOG.map(p => {
|
|
277
|
+
const rec = store.providers[p.id] || {};
|
|
278
|
+
const envVal = p.env ? envValue(p.env) : null;
|
|
279
|
+
const has = !!(rec.api_key || rec.access_token || envVal);
|
|
280
|
+
return {
|
|
281
|
+
id: p.id, label: p.label, adapter: p.adapter, base: rec.base || p.base,
|
|
282
|
+
kind: p.kind, env: p.env, docs: p.docs,
|
|
283
|
+
configured: has,
|
|
284
|
+
source: rec.api_key ? (rec.source || 'manual') : rec.access_token ? (rec.source || 'oauth') : envVal ? 'env' : null,
|
|
285
|
+
hint: hint(rec.api_key || rec.access_token || envVal),
|
|
286
|
+
expires_at: rec.expires_at || null,
|
|
287
|
+
plan: rec.plan || null,
|
|
288
|
+
updated_at: rec.updated_at || null
|
|
289
|
+
};
|
|
290
|
+
});
|
|
291
|
+
const customs = Object.entries(store.providers)
|
|
292
|
+
.filter(([id]) => id.startsWith('custom:'))
|
|
293
|
+
.map(([id, p]) => ({ id, label: p.label || id, base: p.base, adapter: p.adapter, configured: !!p.api_key, hint: hint(p.api_key), kind: 'custom' }));
|
|
294
|
+
return { providers: rows, custom: customs };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function imports() {
|
|
298
|
+
return IMPORTS.map(i => {
|
|
299
|
+
let present = false, when = null;
|
|
300
|
+
try {
|
|
301
|
+
const f = i.file();
|
|
302
|
+
if (f && fs.existsSync(f)) { present = true; when = fs.statSync(f).mtime.toISOString(); }
|
|
303
|
+
} catch { /* unreadable */ }
|
|
304
|
+
if (!present && i.exec) {
|
|
305
|
+
try { present = !!i.exec(); } catch { present = false; }
|
|
306
|
+
}
|
|
307
|
+
return { id: i.id, label: i.label, provider: i.provider, available: present, updated_at: when };
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function importFrom(id) {
|
|
312
|
+
const spec = IMPORTS.find(i => i.id === id);
|
|
313
|
+
if (!spec) return { ok: false, error: 'Unknown import source.' };
|
|
314
|
+
let payload = null;
|
|
315
|
+
try {
|
|
316
|
+
if (spec.exec) {
|
|
317
|
+
const tok = spec.exec();
|
|
318
|
+
payload = tok ? { access_token: tok } : null;
|
|
319
|
+
} else {
|
|
320
|
+
const file = spec.file();
|
|
321
|
+
if (!file || !fs.existsSync(file)) return { ok: false, error: 'No credentials file found for ' + spec.label + '.' };
|
|
322
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
323
|
+
payload = spec.pick(parsed);
|
|
324
|
+
}
|
|
325
|
+
} catch (e) {
|
|
326
|
+
return { ok: false, error: 'Could not read credentials: ' + e.message };
|
|
327
|
+
}
|
|
328
|
+
const token = payload?.access_token || payload?.api_key;
|
|
329
|
+
if (!token) {
|
|
330
|
+
return {
|
|
331
|
+
ok: false,
|
|
332
|
+
error: payload
|
|
333
|
+
? spec.label + ' stored an empty token (the CLI needs to refresh). Run that CLI once, or paste a token in the Providers page.'
|
|
334
|
+
: 'Credentials file had no usable token.'
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
const r = setToken(spec.provider, token, {
|
|
338
|
+
refresh_token: payload.refresh_token,
|
|
339
|
+
expires_at: payload.expires_at,
|
|
340
|
+
plan: payload.plan,
|
|
341
|
+
source: 'import:' + spec.id
|
|
342
|
+
});
|
|
343
|
+
return { ...r, via: spec.id, expires_at: payload.expires_at || null };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Live probe: ask the provider for its model list with the resolved credential.
|
|
347
|
+
* opts.key tests an ad-hoc key before it is saved. */
|
|
348
|
+
async function test(id, opts = {}) {
|
|
349
|
+
const store = readStore();
|
|
350
|
+
const custom = id.startsWith('custom:') ? store.providers[id] : null;
|
|
351
|
+
const meta = entryFor(id);
|
|
352
|
+
if (!meta && !custom) return { ok: false, error: 'Unknown provider.' };
|
|
353
|
+
|
|
354
|
+
const base = String(custom?.base || meta?.base || '').replace(/\/$/, '');
|
|
355
|
+
const adapter = custom?.adapter || meta?.adapter || 'openai';
|
|
356
|
+
const typedKey = typeof opts.key === 'string' && opts.key.trim() ? opts.key.trim() : null;
|
|
357
|
+
const key = typedKey || resolve(id, base);
|
|
358
|
+
const rec = store.providers[id];
|
|
359
|
+
const isOauth = !!(rec && rec.access_token && !rec.api_key) && !typedKey;
|
|
360
|
+
if (!base) return { ok: false, error: 'This provider needs an explicit base URL (set it in Custom Endpoints).' };
|
|
361
|
+
if (!key && meta?.kind !== 'local') {
|
|
362
|
+
return {
|
|
363
|
+
ok: false,
|
|
364
|
+
error: 'No credential for ' + (meta?.label || id) + ': nothing saved, and ' + (meta?.env || 'its env var') + ' is not set in the environment or .env.'
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const controller = new AbortController();
|
|
369
|
+
const timer = setTimeout(() => controller.abort(), 12000);
|
|
370
|
+
const started = Date.now();
|
|
371
|
+
try {
|
|
372
|
+
let url, headers = {};
|
|
373
|
+
if (adapter === 'anthropic') {
|
|
374
|
+
url = base + '/v1/models?limit=20';
|
|
375
|
+
headers = isOauth
|
|
376
|
+
? { Authorization: 'Bearer ' + key, 'anthropic-version': '2023-06-01' }
|
|
377
|
+
: { 'x-api-key': key, 'anthropic-version': '2023-06-01' };
|
|
378
|
+
} else if (adapter === 'gemini') {
|
|
379
|
+
// OAuth access tokens go in the Authorization header; API keys as ?key=
|
|
380
|
+
url = isOauth
|
|
381
|
+
? base + '/v1beta/models'
|
|
382
|
+
: base + '/v1beta/models?key=' + encodeURIComponent(key || '');
|
|
383
|
+
if (isOauth) headers = { Authorization: 'Bearer ' + key };
|
|
384
|
+
} else if (adapter === 'ollama') {
|
|
385
|
+
url = base + '/api/tags';
|
|
386
|
+
if (key) headers = { Authorization: 'Bearer ' + key };
|
|
387
|
+
} else {
|
|
388
|
+
url = base + '/models';
|
|
389
|
+
if (key) headers = { Authorization: 'Bearer ' + key };
|
|
390
|
+
}
|
|
391
|
+
const res = await fetch(url, { headers, signal: controller.signal });
|
|
392
|
+
const text = await res.text();
|
|
393
|
+
let models = [];
|
|
394
|
+
try {
|
|
395
|
+
const json = JSON.parse(text);
|
|
396
|
+
models = json.data || json.models || json.anchors || [];
|
|
397
|
+
} catch { /* non-json */ }
|
|
398
|
+
|
|
399
|
+
// Some providers serve their model list publicly. If the same URL answers
|
|
400
|
+
// without credentials, a 200 says nothing about the key — say so instead of
|
|
401
|
+
// claiming the credential was verified.
|
|
402
|
+
let authChecked = true;
|
|
403
|
+
if (res.ok && key && adapter !== 'ollama') {
|
|
404
|
+
try {
|
|
405
|
+
const pub = await fetch(url, { signal: controller.signal });
|
|
406
|
+
if (pub.ok) authChecked = false;
|
|
407
|
+
} catch { /* ignore */ }
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return {
|
|
411
|
+
ok: res.ok,
|
|
412
|
+
status: res.status,
|
|
413
|
+
latency_ms: Date.now() - started,
|
|
414
|
+
model_count: Array.isArray(models) ? models.length : 0,
|
|
415
|
+
sample: (models || []).slice(0, 5).map(m => m.id || m.name || m.model).filter(Boolean),
|
|
416
|
+
auth_checked: authChecked,
|
|
417
|
+
note: authChecked ? null : 'this provider lists models without credentials, so the key itself was not verified',
|
|
418
|
+
error: res.ok ? null : String(text).slice(0, 200)
|
|
419
|
+
};
|
|
420
|
+
} catch (e) {
|
|
421
|
+
return { ok: false, error: 'Request failed: ' + e.message, latency_ms: Date.now() - started };
|
|
422
|
+
} finally {
|
|
423
|
+
clearTimeout(timer);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Generic OAuth device flow. The caller supplies the client id and endpoints of
|
|
429
|
+
* an app they control; we never invent one on the user's behalf.
|
|
430
|
+
*/
|
|
431
|
+
const devices = new Map();
|
|
432
|
+
|
|
433
|
+
async function deviceStart({ provider, client_id, device_code_url, token_url, scope, audience }) {
|
|
434
|
+
if (!client_id || !device_code_url || !token_url) {
|
|
435
|
+
return { ok: false, error: 'client_id, device_code_url and token_url are required.' };
|
|
436
|
+
}
|
|
437
|
+
const body = new URLSearchParams({ client_id, scope: scope || 'openid offline_access' });
|
|
438
|
+
if (audience) body.set('audience', audience);
|
|
439
|
+
const res = await fetch(device_code_url, {
|
|
440
|
+
method: 'POST',
|
|
441
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
442
|
+
body
|
|
443
|
+
});
|
|
444
|
+
const json = await res.json().catch(() => ({}));
|
|
445
|
+
if (!res.ok || !json.device_code) {
|
|
446
|
+
return { ok: false, error: json.error_description || json.error || ('HTTP ' + res.status) };
|
|
447
|
+
}
|
|
448
|
+
const state = {
|
|
449
|
+
provider, client_id, token_url,
|
|
450
|
+
device_code: json.device_code,
|
|
451
|
+
interval: Number(json.interval) || 5,
|
|
452
|
+
expires_at: Date.now() + (Number(json.expires_in) || 900) * 1000
|
|
453
|
+
};
|
|
454
|
+
devices.set(provider, state);
|
|
455
|
+
return {
|
|
456
|
+
ok: true,
|
|
457
|
+
verification_uri: json.verification_uri || json.verification_url || null,
|
|
458
|
+
verification_uri_complete: json.verification_uri_complete || null,
|
|
459
|
+
user_code: json.user_code || null,
|
|
460
|
+
interval: state.interval,
|
|
461
|
+
expires_in: Math.round((state.expires_at - Date.now()) / 1000)
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async function devicePoll({ provider }) {
|
|
466
|
+
const st = devices.get(provider);
|
|
467
|
+
if (!st) return { ok: false, error: 'No pending sign-in for ' + provider + '.' };
|
|
468
|
+
if (Date.now() > st.expires_at) { devices.delete(provider); return { ok: false, error: 'Device code expired — start again.' }; }
|
|
469
|
+
const body = new URLSearchParams({
|
|
470
|
+
client_id: st.client_id,
|
|
471
|
+
device_code: st.device_code,
|
|
472
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code'
|
|
473
|
+
});
|
|
474
|
+
const res = await fetch(st.token_url, {
|
|
475
|
+
method: 'POST',
|
|
476
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
477
|
+
body
|
|
478
|
+
});
|
|
479
|
+
const json = await res.json().catch(() => ({}));
|
|
480
|
+
if (json.error === 'authorization_pending' || json.error === 'slow_down') {
|
|
481
|
+
return { ok: false, pending: true, error: json.error };
|
|
482
|
+
}
|
|
483
|
+
if (!res.ok || !json.access_token) {
|
|
484
|
+
devices.delete(provider);
|
|
485
|
+
return { ok: false, error: json.error_description || json.error || ('HTTP ' + res.status) };
|
|
486
|
+
}
|
|
487
|
+
devices.delete(provider);
|
|
488
|
+
const stored = setToken(provider, json.access_token, {
|
|
489
|
+
refresh_token: json.refresh_token,
|
|
490
|
+
expires_at: json.expires_in ? new Date(Date.now() + json.expires_in * 1000).toISOString() : null,
|
|
491
|
+
source: 'oauth-device'
|
|
492
|
+
});
|
|
493
|
+
return { ...stored, ok: true, token_type: json.token_type || 'Bearer' };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
module.exports = {
|
|
497
|
+
CATALOG, IMPORTS,
|
|
498
|
+
list: () => CATALOG.slice(),
|
|
499
|
+
status, imports, importFrom,
|
|
500
|
+
setKey, setToken, clear, setCustom,
|
|
501
|
+
resolve, resolveStored, test, deviceStart, devicePoll,
|
|
502
|
+
storePath: () => STORE()
|
|
503
|
+
};
|