Coach: Anthropic, OpenAI, Gemini und jeder OpenAI-kompatible Endpunkt per API-Key
Vier Provider, die nur HTTPS sprechen — kein Agent-SDK, keine CLI, kein coach-User:
sie laufen auf dem Default-Image. Eine Factory (core/adapters/http.js) bildet jede
Antwort auf den bestehenden {code,text,stderr}-Vertrag ab, damit die Pipeline nichts
Neues lernen muss: 401/403 werden 'auth', ein abgeschnittenes JSON 'provider' statt
die einzige Reparaturrunde zu verbrennen. Ollama/LM Studio/vLLM/OpenRouter laufen
ueber dieselbe Chat-Completions-Form mit eigener Basis-URL und optionalem Key.
coach.json haelt Key, Modell und Bindung jetzt PRO Provider — Wechseln wirft nichts
mehr weg; die flache v1.2.11-Datei wird einmalig hochgehoben. Das Privilege-Gate
fragt den Adapter, ob er ueberhaupt einen Prozess startet. Die Admin-Karte zeigt
endlich den API-Key-Knopf auch bei Anthropic, listet Modelle vom Endpunkt und
nimmt eine Basis-URL entgegen.
This commit is contained in:
1 parent
697f1b1269
commit
7047346da1
18 files changed
+957
-68
No files matched your search
@@ -78,6 +78,7 @@ function spawnAsCoach({ command, args, cwd, env, signal }) {
|
||||
|
||||
export default {
|
||||
id: 'claude',
|
||||
spawns: true,
|
||||
runtime: 'Claude Agent SDK',
|
||||
|
||||
/* Importing the package is the check: it is exactly what a job will do, and it is the one
|
||||
|
||||
@@ -28,6 +28,7 @@ export function argvFor(model) {
|
||||
|
||||
export default {
|
||||
id: 'codex',
|
||||
spawns: true,
|
||||
cli: CLI,
|
||||
|
||||
async check(cfg, env) {
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
*
|
||||
* check(cfg, env) → { ok, version?, error? }
|
||||
* invoke({ prompt, jobDir, env, model, timeoutMs }) → { code, text, stderr, timedOut, spawnError }
|
||||
* spawns true when a job runs a child process
|
||||
*
|
||||
* `spawns` decides whether the privilege drop is required before a job may run. The three
|
||||
* runtime-backed adapters say true; the HTTPS ones in ../core/adapters say false, because a
|
||||
* fetch has no process to drop privileges on and must not be refused for lacking one.
|
||||
*
|
||||
* Adding a provider is a file here plus a row in config.PROVIDERS. Nothing else in the
|
||||
* codebase — routes, jobs, payload, validation, UI — knows which one is configured.
|
||||
@@ -9,6 +14,10 @@
|
||||
import { run } from './spawn.js';
|
||||
import claude from './claude.js';
|
||||
import codex from './codex.js';
|
||||
import anthropic from '../core/adapters/anthropic.js';
|
||||
import openai from '../core/adapters/openai.js';
|
||||
import gemini from '../core/adapters/gemini.js';
|
||||
import compatible from '../core/adapters/compatible.js';
|
||||
|
||||
/**
|
||||
* The in-repo fake provider. Ships with the image on purpose: it is what CI drives, and it
|
||||
@@ -18,6 +27,7 @@ import codex from './codex.js';
|
||||
const FIXTURE = new URL('../fixture-cli.mjs', import.meta.url).pathname;
|
||||
const fixture = {
|
||||
id: 'fixture',
|
||||
spawns: true,
|
||||
cli: process.execPath,
|
||||
async check() { return { ok: true, version: 'fixture' }; },
|
||||
async invoke({ prompt, jobDir, env, timeoutMs }) {
|
||||
@@ -35,6 +45,6 @@ const fixture = {
|
||||
lazily: on the default image the module loads, check() reports the runtime as absent, and
|
||||
isConnected() keeps the Coach out of /api/config entirely. Codex is here too, and unlike
|
||||
the SDK its runtime is a CLI binary, so its absence shows up as a spawn error from check(). */
|
||||
const ADAPTERS = { fixture, claude, codex };
|
||||
const ADAPTERS = { fixture, claude, codex, anthropic, openai, gemini, compatible };
|
||||
export const adapterFor = provider => ADAPTERS[provider] || null;
|
||||
export default ADAPTERS;
|
||||
+77
-16
@@ -24,6 +24,7 @@
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { HTTP_PROVIDERS, baseUrlFor } from './core/providers.js';
|
||||
|
||||
const DATA = process.env.DATA_DIR || '/data';
|
||||
const FILE = path.join(DATA, 'coach.json');
|
||||
@@ -60,19 +61,28 @@ export const PROVIDERS = {
|
||||
codex: {
|
||||
label: 'Codex (OpenAI)', runtime: 'Codex CLI',
|
||||
apiKeyEnv: 'CODEX_API_KEY', oauthEnv: null, credentialHomeEnv: 'CODEX_HOME'
|
||||
}
|
||||
},
|
||||
// The plain-HTTPS providers — Anthropic, OpenAI, Gemini and any OpenAI-compatible endpoint.
|
||||
// Described once in core/providers.js so the phone's picker and this table cannot disagree.
|
||||
// They spawn nothing and need no runtime in the image: the default api image runs them.
|
||||
...HTTP_PROVIDERS
|
||||
};
|
||||
|
||||
const DEFAULTS = {
|
||||
enabled: false,
|
||||
provider: 'fixture',
|
||||
model: null,
|
||||
authMode: 'instance', // 'instance' | 'profile'
|
||||
auth: null, // instance mode: { type, account, data:<encrypted> }
|
||||
boundUid: null, // instance mode: the profile the credential bound to
|
||||
// Everything a provider owns is keyed by provider, so switching between them never throws
|
||||
// a key away — the one that was pasted for Anthropic is still there when you come back.
|
||||
auth: {}, // instance mode: { [provider]: { type, account, data:<encrypted>, connectedAt } }
|
||||
models: {}, // { [provider]: model id }
|
||||
providerOptions: {}, // { [provider]: { baseUrl } }
|
||||
boundUid: {}, // instance mode: { [provider]: the profile its credential bound to }
|
||||
caps: { perProfileDaily: 10, instanceDaily: 0 }, // 0 = unlimited
|
||||
log: []
|
||||
};
|
||||
const PER_PROVIDER = ['auth', 'models', 'providerOptions', 'boundUid'];
|
||||
const isPlainObj = v => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const LOG_MAX = 100;
|
||||
|
||||
/* ---------- at-rest encryption ---------- */
|
||||
@@ -113,13 +123,28 @@ export function load() {
|
||||
let stored = {};
|
||||
try { stored = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch { /* absent = feature off */ }
|
||||
cache = { ...DEFAULTS, ...stored, caps: { ...DEFAULTS.caps, ...(stored.caps || {}) } };
|
||||
// A retired provider must not leave the admin page with no chip selected, or keep using its
|
||||
// old credential. The next normal save also drops its legacy fields.
|
||||
if (!PROVIDERS[cache.provider]) {
|
||||
cache.provider = DEFAULTS.provider;
|
||||
cache.auth = null;
|
||||
cache.boundUid = null;
|
||||
|
||||
// Until v1.2.11 this file held ONE credential, ONE model and ONE binding — for whichever
|
||||
// provider was selected at the time. Lift each onto that provider. One-way on purpose: a
|
||||
// downgrade will not read the maps back, which costs the owner one paste of the key.
|
||||
const legacy = PROVIDERS[stored.provider] ? stored.provider : null;
|
||||
if (stored.auth && stored.auth.data) cache.auth = legacy ? { [legacy]: stored.auth } : {};
|
||||
if (typeof stored.model === 'string' && stored.model) {
|
||||
cache.models = { ...(legacy ? { [legacy]: stored.model } : {}), ...(isPlainObj(stored.models) ? stored.models : {}) };
|
||||
}
|
||||
if (typeof stored.boundUid === 'string') cache.boundUid = legacy ? { [legacy]: stored.boundUid } : {};
|
||||
delete cache.model;
|
||||
// Every per-provider map holds only providers this build knows. That drops a retired
|
||||
// provider's leftovers and, because the keys are checked against the table, anything a
|
||||
// hand-edited file might smuggle in as a key.
|
||||
for (const k of PER_PROVIDER) {
|
||||
const src = isPlainObj(cache[k]) ? cache[k] : {};
|
||||
const clean = {};
|
||||
for (const p of Object.keys(src)) if (Object.prototype.hasOwnProperty.call(PROVIDERS, p)) clean[p] = src[p];
|
||||
cache[k] = clean;
|
||||
}
|
||||
// A retired provider must not leave the admin page with no chip selected.
|
||||
if (!PROVIDERS[cache.provider]) cache.provider = DEFAULTS.provider;
|
||||
if (cache.authMode !== 'profile') cache.authMode = 'instance';
|
||||
return cache;
|
||||
}
|
||||
@@ -132,6 +157,31 @@ export function save(patch) {
|
||||
// Test seam: forget the in-memory copy so the next load() re-reads from disk.
|
||||
export function reset() { cache = null; keyCache = null; }
|
||||
|
||||
/* ---------- what one provider owns ----------
|
||||
The only way the rest of the code reads the per-provider maps, so the shape stays here. */
|
||||
export const authFor = (cfg = load(), p = cfg.provider) => (cfg.auth && cfg.auth[p]) || null;
|
||||
export const modelFor = (cfg = load(), p = cfg.provider) => (cfg.models && cfg.models[p]) || (PROVIDERS[p] && PROVIDERS[p].defaultModel) || null;
|
||||
export const optionsFor = (cfg = load(), p = cfg.provider) => (cfg.providerOptions && cfg.providerOptions[p]) || {};
|
||||
export const boundUidFor = (cfg = load(), p = cfg.provider) => (cfg.boundUid && cfg.boundUid[p]) || null;
|
||||
export function saveAuth(provider, auth) {
|
||||
const cfg = load();
|
||||
const next = { ...cfg.auth };
|
||||
if (auth) next[provider] = auth; else delete next[provider];
|
||||
// boundUid resets with the credential: a new account has not been spent by anyone yet.
|
||||
const bound = { ...cfg.boundUid }; delete bound[provider];
|
||||
return save({ auth: next, boundUid: bound });
|
||||
}
|
||||
export function saveModel(provider, model) {
|
||||
const next = { ...load().models };
|
||||
if (model) next[provider] = model; else delete next[provider];
|
||||
return save({ models: next });
|
||||
}
|
||||
export function saveOptions(provider, patch) {
|
||||
const all = { ...load().providerOptions };
|
||||
all[provider] = { ...(all[provider] || {}), ...patch };
|
||||
return save({ providerOptions: all });
|
||||
}
|
||||
|
||||
/* ---------- per-profile credentials ---------- */
|
||||
|
||||
/* Deliberately its own file rather than a field on state-<uid>.json. Profile state syncs across
|
||||
@@ -178,18 +228,27 @@ export function credentialFor(uid) {
|
||||
}
|
||||
|
||||
// instance mode
|
||||
if (cfg.boundUid && cfg.boundUid !== uid) {
|
||||
const bound = boundUidFor(cfg);
|
||||
if (bound && bound !== uid) {
|
||||
return { ok: false, reason: 'shared-account', message: SHARED_ACCOUNT_REFUSAL, mode: 'instance' };
|
||||
}
|
||||
const auth = cfg.auth && cfg.auth.data ? decrypt(cfg.auth.data) : null;
|
||||
if (!auth || !auth.token) return { ok: false, reason: 'no-credential', mode: 'instance' };
|
||||
return { ok: true, auth, type: cfg.auth.type, account: cfg.auth.account || null, mode: 'instance' };
|
||||
const rec = authFor(cfg);
|
||||
const auth = rec && rec.data ? decrypt(rec.data) : null;
|
||||
if (!auth || !auth.token) {
|
||||
// An endpoint that takes no key (a model on the LAN) is connected without one. Only when
|
||||
// nothing was ever filed — a filed key that fails to decrypt is still a failure.
|
||||
if (providerMeta(cfg).keyOptional && !rec) return { ok: true, auth: null, type: null, account: null, mode: 'instance' };
|
||||
return { ok: false, reason: 'no-credential', mode: 'instance' };
|
||||
}
|
||||
return { ok: true, auth, type: rec.type, account: rec.account || null, mode: 'instance' };
|
||||
}
|
||||
|
||||
/** First profile to actually spend the instance credential binds it. */
|
||||
export function bindInstanceCredential(uid) {
|
||||
const cfg = load();
|
||||
if (cfg.authMode === 'instance' && !cfg.boundUid && cfg.provider !== 'fixture') save({ boundUid: uid });
|
||||
if (cfg.authMode === 'instance' && !boundUidFor(cfg) && cfg.provider !== 'fixture' && authFor(cfg)) {
|
||||
save({ boundUid: { ...cfg.boundUid, [cfg.provider]: uid } });
|
||||
}
|
||||
}
|
||||
|
||||
/** Whose account a profile is about to spend — rendered in the UI, never a secret. */
|
||||
@@ -225,7 +284,9 @@ export function isConnected() {
|
||||
if (!isEnabled()) return false;
|
||||
if (cfg.provider === 'fixture') return true;
|
||||
if (cfg.authMode === 'profile') return true;
|
||||
return !!(cfg.auth && decrypt(cfg.auth.data));
|
||||
const rec = authFor(cfg);
|
||||
if (!rec) return !!providerMeta(cfg).keyOptional && !!baseUrlFor(cfg.provider, cfg);
|
||||
return !!decrypt(rec.data);
|
||||
}
|
||||
|
||||
/** What /api/config tells every client. Absent ⇒ no Coach UI exists anywhere (FR-55/56). */
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/* Anthropic Messages API. */
|
||||
import { httpAdapter } from './http.js';
|
||||
import { SYSTEM_PROMPT } from '../system-prompt.js';
|
||||
|
||||
export const ANTHROPIC_VERSION = '2023-06-01';
|
||||
|
||||
export const anthropicSpec = {
|
||||
id: 'anthropic',
|
||||
path: () => '/v1/messages',
|
||||
modelsPath: '/v1/models',
|
||||
headers: key => ({
|
||||
'x-api-key': key,
|
||||
'anthropic-version': ANTHROPIC_VERSION,
|
||||
// Required for a call made from a browser context. Harmless from a server, and the phone's
|
||||
// native HTTP path does not need it either — it is here so a plain-browser dev run works.
|
||||
'anthropic-dangerous-direct-browser-access': 'true'
|
||||
}),
|
||||
body: ({ model, prompt, maxTokens }) => ({
|
||||
model,
|
||||
max_tokens: maxTokens,
|
||||
system: SYSTEM_PROMPT,
|
||||
messages: [{ role: 'user', content: prompt }]
|
||||
}),
|
||||
errorMessage: data => data && data.error && data.error.message,
|
||||
readText: data => {
|
||||
if (data.stop_reason === 'refusal') return { error: 'the model declined this request' + (data.stop_details && data.stop_details.explanation ? ': ' + data.stop_details.explanation : '') };
|
||||
const text = (data.content || []).filter(b => b && b.type === 'text').map(b => b.text).join('');
|
||||
return { text, truncated: data.stop_reason === 'max_tokens' };
|
||||
},
|
||||
readModels: data => (data.data || []).map(m => m.id)
|
||||
};
|
||||
|
||||
export default httpAdapter(anthropicSpec);
|
||||
@@ -0,0 +1,9 @@
|
||||
/* Any OpenAI-compatible endpoint: Ollama, LM Studio, vLLM, OpenRouter, a gateway of your own.
|
||||
* Same wire shape as openai.js; the base URL comes from configuration and the key is optional.
|
||||
* `max_tokens` rather than `max_completion_tokens` because that is the field every one of
|
||||
* those servers understands. */
|
||||
import { httpAdapter } from './http.js';
|
||||
import { chatCompletionsSpec } from './openai.js';
|
||||
|
||||
export const compatibleSpec = chatCompletionsSpec('compatible', { maxTokensField: 'max_tokens' });
|
||||
export default httpAdapter(compatibleSpec);
|
||||
@@ -0,0 +1,33 @@
|
||||
/* Google Gemini (Generative Language API). The key travels as a header, never as `?key=` —
|
||||
* a query string ends up in proxy logs, error messages and browser history. */
|
||||
import { httpAdapter } from './http.js';
|
||||
import { SYSTEM_PROMPT } from '../system-prompt.js';
|
||||
|
||||
export const geminiSpec = {
|
||||
id: 'gemini',
|
||||
path: model => `/v1beta/models/${encodeURIComponent(model)}:generateContent`,
|
||||
modelsPath: '/v1beta/models?pageSize=200',
|
||||
headers: key => ({ 'x-goog-api-key': key }),
|
||||
body: ({ prompt, maxTokens }) => ({
|
||||
systemInstruction: { parts: [{ text: SYSTEM_PROMPT }] },
|
||||
contents: [{ role: 'user', parts: [{ text: prompt }] }],
|
||||
generationConfig: { responseMimeType: 'application/json', maxOutputTokens: maxTokens }
|
||||
}),
|
||||
errorMessage: data => data && data.error && data.error.message,
|
||||
readText: data => {
|
||||
const cand = (data.candidates || [])[0];
|
||||
if (!cand) {
|
||||
const block = data.promptFeedback && data.promptFeedback.blockReason;
|
||||
return { error: block ? `the request was blocked: ${block}` : 'the answer had no candidates' };
|
||||
}
|
||||
if (cand.finishReason === 'MAX_TOKENS') return { text: '', truncated: true };
|
||||
if (cand.finishReason && cand.finishReason !== 'STOP') return { error: `the model stopped early: ${cand.finishReason}` };
|
||||
const text = ((cand.content && cand.content.parts) || []).map(p => p.text || '').join('');
|
||||
return { text, truncated: false };
|
||||
},
|
||||
readModels: data => (data.models || [])
|
||||
.filter(m => !m.supportedGenerationMethods || m.supportedGenerationMethods.includes('generateContent'))
|
||||
.map(m => String(m.name || '').replace(/^models\//, ''))
|
||||
};
|
||||
|
||||
export default httpAdapter(geminiSpec);
|
||||
@@ -0,0 +1,147 @@
|
||||
/* One adapter shape for every provider that is just an HTTPS endpoint.
|
||||
*
|
||||
* Runs unchanged on the server (node's fetch) and on the phone (an injected fetch that goes
|
||||
* through the native HTTP layer, so the WebView's CORS rules never apply). It spawns nothing,
|
||||
* so it needs no unprivileged user, no job directory and no AI runtime in the image — the
|
||||
* default api image has everything it needs.
|
||||
*
|
||||
* The return shape is the one the pipeline already classifies for the runtime-backed
|
||||
* adapters — { code, text, stderr, timedOut, spawnError } — and the mapping is deliberate:
|
||||
*
|
||||
* 2xx with text → code 0, text
|
||||
* non-2xx → code 1, stderr "<status> <message>" the leading 401/403 is what
|
||||
* the pipeline's auth regex
|
||||
* keys on
|
||||
* cut off at max tokens → code 1 a half JSON object would
|
||||
* burn the single repair round
|
||||
* fetch threw / aborted → code 1 with the host / timedOut
|
||||
* no key and one required → spawnError "missing", like an absent CLI
|
||||
*
|
||||
* A provider is described by a spec (see anthropic.js etc.); this file owns the transport.
|
||||
*/
|
||||
import { HTTP_PROVIDERS, baseUrlFor } from '../providers.js';
|
||||
|
||||
export const MAX_OUTPUT_TOKENS = 16000;
|
||||
const DEFAULT_TIMEOUT_MS = 5 * 60000;
|
||||
|
||||
const hostOf = url => { try { return new URL(url).host; } catch { return url; } };
|
||||
const trim = (s, n = 300) => String(s == null ? '' : s).slice(0, n);
|
||||
|
||||
/** A fetch, bounded by AbortController. Never throws for HTTP status; throws for transport. */
|
||||
async function call(fetchImpl, url, init, timeoutMs, signal) {
|
||||
const ctl = new AbortController();
|
||||
const onOuter = () => ctl.abort();
|
||||
if (signal) signal.addEventListener('abort', onOuter, { once: true });
|
||||
const timer = setTimeout(() => ctl.abort(), timeoutMs);
|
||||
try {
|
||||
return await fetchImpl(url, { ...init, signal: ctl.signal });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (signal) signal.removeEventListener('abort', onOuter);
|
||||
}
|
||||
}
|
||||
|
||||
async function readJson(res) {
|
||||
const text = await res.text();
|
||||
try { return { data: JSON.parse(text), text }; } catch { return { data: null, text }; }
|
||||
}
|
||||
|
||||
export function httpAdapter(spec) {
|
||||
const id = spec.id;
|
||||
const meta = HTTP_PROVIDERS[id];
|
||||
if (!meta) throw new Error(`httpAdapter: unknown provider "${id}"`);
|
||||
|
||||
const keyOf = env => (env && env[meta.apiKeyEnv]) || null;
|
||||
|
||||
const adapter = {
|
||||
id,
|
||||
runtime: meta.runtime,
|
||||
// The two facts the server's job runner branches on. Stated, not inferred from absence.
|
||||
spawns: false,
|
||||
needsRuntime: false,
|
||||
|
||||
baseUrl: cfg => baseUrlFor(id, cfg),
|
||||
|
||||
/**
|
||||
* Can this provider be reached? Without a key there is nothing to ask the provider, and
|
||||
* fetch itself is never absent — so the runtime is "ready" and the credential tile says
|
||||
* what is missing. With a key, listing the models is the cheapest real round trip and
|
||||
* doubles as the auth check the admin card renders.
|
||||
*/
|
||||
async check(cfg, env, opts = {}) {
|
||||
const base = adapter.baseUrl(cfg);
|
||||
if (!base) return { ok: false, error: 'no endpoint configured' };
|
||||
if (!keyOf(env) && !meta.keyOptional) return { ok: true, version: `HTTPS · ${hostOf(base)}`, needsKey: true };
|
||||
const r = await adapter.models(cfg, env, opts);
|
||||
if (!r.ok) return { ok: false, error: r.error };
|
||||
return { ok: true, version: `HTTPS · ${hostOf(base)} · ${r.models.length} models`, models: r.models };
|
||||
},
|
||||
|
||||
/** The models this endpoint serves, so a UI can offer a list instead of a text field. */
|
||||
async models(cfg, env, { fetch: fetchImpl = globalThis.fetch, timeoutMs = 20000, signal } = {}) {
|
||||
const base = adapter.baseUrl(cfg);
|
||||
if (!base) return { ok: false, error: 'no endpoint configured', models: [] };
|
||||
const key = keyOf(env);
|
||||
if (!key && !meta.keyOptional) return { ok: false, error: 'no API key configured', models: [] };
|
||||
let res;
|
||||
try {
|
||||
res = await call(fetchImpl, base + spec.modelsPath, { method: 'GET', headers: spec.headers(key) }, timeoutMs, signal);
|
||||
} catch (e) {
|
||||
return { ok: false, error: e.name === 'AbortError' ? 'timed out' : `could not reach ${hostOf(base)}: ${trim(e.message, 120)}`, models: [] };
|
||||
}
|
||||
const { data, text } = await readJson(res);
|
||||
if (!res.ok) return { ok: false, error: `${res.status} ${trim(spec.errorMessage(data) || text, 200)}`, models: [] };
|
||||
let models;
|
||||
try { models = spec.readModels(data); } catch { models = null; }
|
||||
if (!Array.isArray(models)) return { ok: false, error: 'unexpected model list shape', models: [] };
|
||||
return { ok: true, models: models.filter(m => typeof m === 'string' && m).sort() };
|
||||
},
|
||||
|
||||
/**
|
||||
* One question, one answer. `env` carries the key under the provider's declared variable
|
||||
* and nothing else is read from it; `fetch` is injectable so the phone can route through
|
||||
* native HTTP and a test can hand in a fake.
|
||||
*/
|
||||
async invoke({ cfg, prompt, env, model, timeoutMs = DEFAULT_TIMEOUT_MS, fetch: fetchImpl = globalThis.fetch, signal } = {}) {
|
||||
const base = adapter.baseUrl(cfg);
|
||||
if (!base) return { code: -1, text: '', stderr: `no endpoint configured for ${id}`, spawnError: true };
|
||||
const key = keyOf(env);
|
||||
if (!key && !meta.keyOptional) return { code: -1, text: '', stderr: `no API key configured for ${id}`, spawnError: true };
|
||||
const chosen = model || meta.defaultModel;
|
||||
if (!chosen) return { code: 1, text: '', stderr: `no model chosen for ${id} — pick one from the list the endpoint serves` };
|
||||
|
||||
let body = spec.body({ model: chosen, prompt, maxTokens: MAX_OUTPUT_TOKENS });
|
||||
let retriedWithoutJsonMode = false;
|
||||
for (;;) {
|
||||
let res;
|
||||
try {
|
||||
res = await call(fetchImpl, base + spec.path(chosen), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...spec.headers(key) },
|
||||
body: JSON.stringify(body)
|
||||
}, timeoutMs, signal);
|
||||
} catch (e) {
|
||||
if (e.name === 'AbortError') return { code: -1, text: '', stderr: 'timed out', timedOut: true };
|
||||
return { code: 1, text: '', stderr: `could not reach ${hostOf(base)}: ${trim(e.message, 200)}` };
|
||||
}
|
||||
const { data, text } = await readJson(res);
|
||||
if (!res.ok) {
|
||||
const msg = spec.errorMessage(data) || trim(text, 200);
|
||||
// Some OpenAI-compatible servers reject the JSON-mode flag outright. Once, without it.
|
||||
if (res.status === 400 && spec.withoutJsonMode && !retriedWithoutJsonMode && /response_format|json_object|json mode/i.test(msg)) {
|
||||
body = spec.withoutJsonMode(body);
|
||||
retriedWithoutJsonMode = true;
|
||||
continue;
|
||||
}
|
||||
return { code: 1, text: '', stderr: `${res.status} ${trim(msg, 280)}` };
|
||||
}
|
||||
let out;
|
||||
try { out = spec.readText(data); } catch (e) { out = { error: `unexpected response shape: ${trim(e.message, 100)}` }; }
|
||||
if (out.error) return { code: 1, text: '', stderr: out.error };
|
||||
if (out.truncated) return { code: 1, text: '', stderr: 'the answer was cut off at the output limit — try a smaller plan or a bigger model' };
|
||||
return { code: 0, text: String(out.text || '').trim(), stderr: '' };
|
||||
}
|
||||
}
|
||||
};
|
||||
return adapter;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/* OpenAI — and, through compatible.js, everything that speaks its Chat Completions shape.
|
||||
*
|
||||
* Chat Completions rather than the newer Responses API on purpose: it is the one request shape
|
||||
* Ollama, LM Studio, vLLM, OpenRouter and OpenAI itself all serve, so one implementation covers
|
||||
* two providers. `compatible` reuses this spec with a different base URL and an optional key.
|
||||
*/
|
||||
import { httpAdapter } from './http.js';
|
||||
import { SYSTEM_PROMPT } from '../system-prompt.js';
|
||||
|
||||
export function chatCompletionsSpec(id, { maxTokensField = 'max_completion_tokens' } = {}) {
|
||||
return {
|
||||
id,
|
||||
path: () => '/v1/chat/completions',
|
||||
modelsPath: '/v1/models',
|
||||
headers: key => (key ? { authorization: 'Bearer ' + key } : {}),
|
||||
body: ({ model, prompt, maxTokens }) => ({
|
||||
model,
|
||||
messages: [{ role: 'system', content: SYSTEM_PROMPT }, { role: 'user', content: prompt }],
|
||||
response_format: { type: 'json_object' },
|
||||
[maxTokensField]: maxTokens
|
||||
}),
|
||||
// A server that rejects JSON mode gets the same request once more without it; the parser
|
||||
// copes with a fenced or prefaced answer, and the validator is the gate either way.
|
||||
withoutJsonMode: body => { const { response_format: _rf, ...rest } = body; return rest; },
|
||||
errorMessage: data => data && data.error && (typeof data.error === 'string' ? data.error : data.error.message),
|
||||
readText: data => {
|
||||
const choice = (data.choices || [])[0];
|
||||
if (!choice) return { error: 'the answer had no choices' };
|
||||
const content = choice.message && choice.message.content;
|
||||
const text = typeof content === 'string' ? content : Array.isArray(content) ? content.map(p => p.text || '').join('') : '';
|
||||
return { text, truncated: choice.finish_reason === 'length' };
|
||||
},
|
||||
readModels: data => (data.data || data.models || []).map(m => (typeof m === 'string' ? m : m.id || m.name)).filter(Boolean)
|
||||
};
|
||||
}
|
||||
|
||||
export const openaiSpec = chatCompletionsSpec('openai');
|
||||
export default httpAdapter(openaiSpec);
|
||||
@@ -0,0 +1,70 @@
|
||||
/* The providers that speak plain HTTPS, described once for both runtimes.
|
||||
*
|
||||
* The server's config.PROVIDERS spreads these rows in next to the runtime-backed providers
|
||||
* (Claude Agent SDK, Codex CLI); the phone reads them directly for its own picker. Keeping the
|
||||
* facts in one place is what stops the two ever offering different endpoints or defaults.
|
||||
*
|
||||
* `defaultModel` is a starting point, not a pin. Every one of these providers lists its models
|
||||
* over the same API, and the UI offers that list — a name typed here goes stale, a list does
|
||||
* not. `compatible` has no default at all: an OpenAI-compatible endpoint is whatever the owner
|
||||
* pointed it at, so the model has to come from what that endpoint actually serves.
|
||||
*/
|
||||
export const HTTP_PROVIDERS = Object.freeze({
|
||||
anthropic: Object.freeze({
|
||||
label: 'Anthropic API', runtime: 'HTTPS', http: true,
|
||||
apiKeyEnv: 'ANTHROPIC_API_KEY', oauthEnv: null,
|
||||
defaultBase: 'https://api.anthropic.com',
|
||||
defaultModel: 'claude-opus-5',
|
||||
keyPlaceholder: 'sk-ant-…'
|
||||
}),
|
||||
openai: Object.freeze({
|
||||
label: 'OpenAI API', runtime: 'HTTPS', http: true,
|
||||
apiKeyEnv: 'OPENAI_API_KEY', oauthEnv: null,
|
||||
defaultBase: 'https://api.openai.com',
|
||||
defaultModel: 'gpt-5.6',
|
||||
keyPlaceholder: 'sk-…'
|
||||
}),
|
||||
gemini: Object.freeze({
|
||||
label: 'Google Gemini', runtime: 'HTTPS', http: true,
|
||||
apiKeyEnv: 'GEMINI_API_KEY', oauthEnv: null,
|
||||
defaultBase: 'https://generativelanguage.googleapis.com',
|
||||
defaultModel: 'gemini-2.5-pro',
|
||||
keyPlaceholder: 'AIza…'
|
||||
}),
|
||||
// Ollama, LM Studio, vLLM, OpenRouter, a corporate gateway: anything that serves the
|
||||
// Chat Completions shape. The base URL is the whole configuration; a key is optional
|
||||
// because a model on your own LAN usually has none.
|
||||
compatible: Object.freeze({
|
||||
label: 'OpenAI-compatible endpoint', runtime: 'HTTPS', http: true,
|
||||
apiKeyEnv: 'OPENAI_COMPAT_API_KEY', oauthEnv: null,
|
||||
defaultBase: null, baseUrl: true, keyOptional: true,
|
||||
defaultModel: null,
|
||||
keyPlaceholder: '(optional)'
|
||||
})
|
||||
});
|
||||
|
||||
export const HTTP_PROVIDER_IDS = Object.freeze(Object.keys(HTTP_PROVIDERS));
|
||||
|
||||
/** The base URL a provider will actually be called at: the configured override, else the default. */
|
||||
export function baseUrlFor(id, cfg) {
|
||||
const meta = HTTP_PROVIDERS[id];
|
||||
const set = cfg && cfg.providerOptions && cfg.providerOptions[id] && cfg.providerOptions[id].baseUrl;
|
||||
const raw = (typeof set === 'string' && set.trim()) || (meta && meta.defaultBase) || '';
|
||||
return raw.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Only http(s), only a parseable URL, and never credentials in it — a base URL is admin
|
||||
* configuration, but "admin-configured" and "safe to log" are different properties, and the
|
||||
* host is written into the job log so an operator can see where jobs went.
|
||||
*/
|
||||
export function validateBaseUrl(raw) {
|
||||
const s = String(raw || '').trim();
|
||||
if (!s) return { ok: true, value: null };
|
||||
let u;
|
||||
try { u = new URL(s); } catch { return { ok: false, error: 'not a valid URL' }; }
|
||||
if (u.protocol !== 'http:' && u.protocol !== 'https:') return { ok: false, error: 'only http:// and https:// endpoints are supported' };
|
||||
if (u.username || u.password) return { ok: false, error: 'put the key in the credential field, not in the URL' };
|
||||
if (u.search || u.hash) return { ok: false, error: 'a base URL has no query string' };
|
||||
return { ok: true, value: u.toString().replace(/\/+$/, '') };
|
||||
}
|
||||
+16
-12
@@ -150,8 +150,11 @@ export function enqueue(uid, opts) {
|
||||
|
||||
// The privilege drop is what keeps a provider runtime out of ./data. If it cannot be
|
||||
// performed, there is no job — see canDropPrivileges for why this is not a warning either.
|
||||
const priv = canDropPrivileges();
|
||||
if (!priv.ok) throw new CoachError('unprivileged', `Coach jobs are disabled: ${priv.why}`);
|
||||
// A provider that spawns nothing has no process to drop, and is not refused for it.
|
||||
if (adapterFor(cfgStore.load().provider)?.spawns !== false) {
|
||||
const priv = canDropPrivileges();
|
||||
if (!priv.ok) throw new CoachError('unprivileged', `Coach jobs are disabled: ${priv.why}`);
|
||||
}
|
||||
|
||||
const caps = cfgStore.load().caps || {};
|
||||
const { used, limit } = capState(uid);
|
||||
@@ -245,14 +248,15 @@ async function execute(job) {
|
||||
previous: pendingCreate?.bundle || null
|
||||
});
|
||||
|
||||
const jobDir = fs.mkdtempSync(path.join(os.tmpdir(), 'coach-'));
|
||||
const env = cfgStore.jobEnv(jobDir, cfgStore.credentialFor(job.uid));
|
||||
// An HTTPS provider has no child process, so no directory for one to live in either.
|
||||
const jobDir = adapter.spawns === false ? null : fs.mkdtempSync(path.join(os.tmpdir(), 'coach-'));
|
||||
const env = cfgStore.jobEnv(jobDir || os.tmpdir(), cfgStore.credentialFor(job.uid));
|
||||
try {
|
||||
const ids = unprivilegedIds();
|
||||
const ids = jobDir && unprivilegedIds();
|
||||
if (ids) fs.chownSync(jobDir, ids.uid, ids.gid);
|
||||
|
||||
const attempt = await runPipeline({
|
||||
adapter, cfg, kind: job.kind, payload, model: cfg.model || null, timeoutMs: TIMEOUT_MS,
|
||||
adapter, cfg, kind: job.kind, payload, model: cfgStore.modelFor(cfg), timeoutMs: TIMEOUT_MS,
|
||||
invokeOpts: { jobDir, env }
|
||||
});
|
||||
if (!attempt.ok) {
|
||||
@@ -272,7 +276,7 @@ async function execute(job) {
|
||||
};
|
||||
return finish(job, { outcome: 'ready', pending });
|
||||
} finally {
|
||||
fs.rmSync(jobDir, { recursive: true, force: true });
|
||||
if (jobDir) fs.rmSync(jobDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,19 +302,19 @@ export async function testRun() {
|
||||
const cfg = cfgStore.load();
|
||||
const adapter = adapterFor(cfg.provider);
|
||||
if (!adapter) return { ok: false, error: 'no provider configured' };
|
||||
const jobDir = fs.mkdtempSync(path.join(os.tmpdir(), 'coach-test-'));
|
||||
const jobDir = adapter.spawns === false ? null : fs.mkdtempSync(path.join(os.tmpdir(), 'coach-test-'));
|
||||
try {
|
||||
// No user asked for this, so there is no profile whose account is being spent. In instance
|
||||
// mode that is the bound profile's credential — the one the round-trip is meant to prove —
|
||||
// and in per-profile mode it is nobody's, which is the honest answer: an admin cannot test
|
||||
// a credential that belongs to a profile.
|
||||
const env = cfgStore.jobEnv(jobDir, cfgStore.credentialFor(cfg.boundUid));
|
||||
const ids = unprivilegedIds();
|
||||
const env = cfgStore.jobEnv(jobDir || os.tmpdir(), cfgStore.credentialFor(cfgStore.boundUidFor(cfg)));
|
||||
const ids = jobDir && unprivilegedIds();
|
||||
if (ids) fs.chownSync(jobDir, ids.uid, ids.gid);
|
||||
const check = await adapter.check(cfg, env);
|
||||
if (!check.ok) return { ok: false, error: check.error || 'the provider runtime could not be run' };
|
||||
const r = await adapter.invoke({
|
||||
cfg, jobDir, env, model: cfg.model || null, timeoutMs: 90000,
|
||||
cfg, jobDir, env, model: cfgStore.modelFor(cfg), timeoutMs: 90000,
|
||||
prompt: 'Reply with exactly this JSON object and nothing else: {"coach_contract":1,"ok":true}'
|
||||
});
|
||||
if (r.timedOut) return { ok: false, version: check.version, error: 'the provider did not answer in time' };
|
||||
@@ -324,7 +328,7 @@ export async function testRun() {
|
||||
}
|
||||
return { ok: true, version: check.version };
|
||||
} finally {
|
||||
fs.rmSync(jobDir, { recursive: true, force: true });
|
||||
if (jobDir) fs.rmSync(jobDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+67
-23
@@ -9,6 +9,7 @@ import * as jobs from './jobs.js';
|
||||
import { adapterFor } from './adapters/index.js';
|
||||
import { canDropPrivileges } from './adapters/spawn.js';
|
||||
import { DATA_CATEGORIES } from './core/payload.js';
|
||||
import { validateBaseUrl, baseUrlFor } from './core/providers.js';
|
||||
|
||||
// Job failures the user sees, in the app's own voice. The raw provider detail never reaches
|
||||
// them — it goes to the admin card, which is where someone can act on it (FR-47).
|
||||
@@ -107,35 +108,51 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const cfg = cfgStore.load();
|
||||
const adapter = adapterFor(cfg.provider);
|
||||
const check = adapter ? await adapter.check(cfg, cfgStore.jobEnv(process.env.TMPDIR || '/tmp')) : { ok: false, error: 'unknown provider' };
|
||||
// For the runtime-backed providers this asks "is the runtime there"; for an HTTPS one it
|
||||
// lists the models with the stored key, which is the round trip the card wants anyway.
|
||||
const cred = adapter?.spawns === false ? cfgStore.credentialFor(cfgStore.boundUidFor(cfg)) : undefined;
|
||||
const check = adapter ? await adapter.check(cfg, cfgStore.jobEnv(process.env.TMPDIR || '/tmp', cred?.ok ? cred : undefined)) : { ok: false, error: 'unknown provider' };
|
||||
const log = cfg.log || [];
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
json(res, 200, {
|
||||
disabledByEnv: cfgStore.COACH_DISABLED,
|
||||
enabled: !!cfg.enabled,
|
||||
provider: cfg.provider,
|
||||
providers: Object.entries(cfgStore.PROVIDERS).map(([id, p]) => ({ id, label: p.label, runtime: p.runtime, setupToken: !!p.setupToken, deviceLogin: !!p.deviceLogin, apiKey: !!p.apiKeyEnv })),
|
||||
model: cfg.model,
|
||||
providers: Object.entries(cfgStore.PROVIDERS).map(([id, p]) => ({
|
||||
id, label: p.label, runtime: p.runtime,
|
||||
setupToken: !!p.setupToken, deviceLogin: !!p.deviceLogin, apiKey: !!p.apiKeyEnv,
|
||||
http: !!p.http, baseUrl: !!p.baseUrl, keyOptional: !!p.keyOptional, keyPlaceholder: p.keyPlaceholder || null,
|
||||
defaultModel: p.defaultModel || null,
|
||||
// Which providers already hold a key — so switching chips is visibly not a reset.
|
||||
connected: !!(cfgStore.authFor(cfg, id) && cfgStore.authFor(cfg, id).data)
|
||||
})),
|
||||
model: cfgStore.modelFor(cfg),
|
||||
models: cfg.models,
|
||||
baseUrl: cfgStore.providerMeta(cfg).http ? baseUrlFor(cfg.provider, cfg) : null,
|
||||
knownModels: check.models || null,
|
||||
caps: cfg.caps,
|
||||
runtime: { ok: !!check.ok, version: check.version || null, error: check.error || null },
|
||||
runtime: { ok: !!check.ok, version: check.version || null, error: check.error || null, needsKey: !!check.needsKey },
|
||||
authMode: cfg.authMode,
|
||||
boundUid: cfg.boundUid || null,
|
||||
boundUid: cfgStore.boundUidFor(cfg),
|
||||
/* Whether a credential is filed, and whose — never the credential. `unreadable` is its
|
||||
own state rather than "not connected" because it has a specific cause and a specific
|
||||
fix: ./data was restored without its `secret`, so the blob is intact and undecryptable,
|
||||
and connecting again is the way out. */
|
||||
auth: (() => {
|
||||
if (!cfgStore.providerMeta(cfg).oauthEnv && !cfgStore.providerMeta(cfg).apiKeyEnv) {
|
||||
return { state: 'not-required' };
|
||||
}
|
||||
if (!cfg.auth || !cfg.auth.data) return { state: 'none' };
|
||||
if (!cfgStore.decrypt(cfg.auth.data)) return { state: 'unreadable' };
|
||||
return { state: 'connected', type: cfg.auth.type || null, account: cfg.auth.account || null };
|
||||
const meta = cfgStore.providerMeta(cfg);
|
||||
const rec = cfgStore.authFor(cfg);
|
||||
if (!meta.oauthEnv && !meta.apiKeyEnv) return { state: 'not-required' };
|
||||
if (!rec || !rec.data) return { state: meta.keyOptional ? 'optional' : 'none' };
|
||||
if (!cfgStore.decrypt(rec.data)) return { state: 'unreadable' };
|
||||
return { state: 'connected', type: rec.type || null, account: rec.account || null, connectedAt: rec.connectedAt || null };
|
||||
})(),
|
||||
// Whether the privilege drop can actually be performed. Surfaced because the control
|
||||
// now fails closed: if this reads false, no job runs, and the admin needs to know that
|
||||
// from the card rather than from a user reporting that nothing happens.
|
||||
unprivileged: canDropPrivileges(),
|
||||
// from the card rather than from a user reporting that nothing happens. An HTTPS
|
||||
// provider has no process to drop, and the card must not show a red banner for it.
|
||||
unprivileged: adapter?.spawns === false
|
||||
? { ok: true, dropped: false, why: 'this provider runs no child process' }
|
||||
: canDropPrivileges(),
|
||||
// Counts and outcomes only — never intake answers, payloads or proposals (FR-12/A4).
|
||||
jobsToday: log.filter(e => (e.at || '').slice(0, 10) === today).length,
|
||||
lastSuccess: cfgStore.lastSuccess(),
|
||||
@@ -149,13 +166,23 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
|
||||
const body = await readBody(req);
|
||||
const patch = {};
|
||||
if (body.enabled !== undefined) patch.enabled = !!body.enabled;
|
||||
const current = cfgStore.load();
|
||||
if (body.provider !== undefined) {
|
||||
if (!cfgStore.PROVIDERS[body.provider]) return json(res, 400, { error: 'unknown provider' });
|
||||
// Credentials belong to the provider that issued them.
|
||||
if (body.provider !== cfgStore.load().provider) patch.auth = null;
|
||||
// Credentials, model and endpoint are all keyed by provider — switching never drops them.
|
||||
patch.provider = body.provider;
|
||||
}
|
||||
if (body.model !== undefined) patch.model = body.model ? String(body.model).slice(0, 80) : null;
|
||||
const target = patch.provider || current.provider;
|
||||
if (body.model !== undefined) {
|
||||
patch.models = { ...current.models };
|
||||
if (body.model) patch.models[target] = String(body.model).slice(0, 80); else delete patch.models[target];
|
||||
}
|
||||
if (body.baseUrl !== undefined) {
|
||||
if (!cfgStore.PROVIDERS[target].baseUrl) return json(res, 400, { error: `${target} has a fixed endpoint` });
|
||||
const v = validateBaseUrl(body.baseUrl);
|
||||
if (!v.ok) return json(res, 400, { error: v.error });
|
||||
patch.providerOptions = { ...current.providerOptions, [target]: { ...(current.providerOptions[target] || {}), baseUrl: v.value } };
|
||||
}
|
||||
if (body.caps) {
|
||||
patch.caps = {
|
||||
perProfileDaily: Math.max(0, Math.min(200, +body.caps.perProfileDaily || 0)),
|
||||
@@ -172,6 +199,18 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
|
||||
json(res, 200, r);
|
||||
},
|
||||
|
||||
/* The models the configured endpoint serves, so the card can offer a list rather than a
|
||||
text field that goes stale with every model release. HTTPS providers only. */
|
||||
'POST /api/admin/coach/models': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const cfg = cfgStore.load();
|
||||
const adapter = adapterFor(cfg.provider);
|
||||
if (!adapter || typeof adapter.models !== 'function') return json(res, 200, { ok: false, error: 'this provider does not list models', models: [] });
|
||||
const cred = cfgStore.credentialFor(cfgStore.boundUidFor(cfg));
|
||||
const env = cfgStore.jobEnv(process.env.TMPDIR || '/tmp', cred.ok ? cred : undefined);
|
||||
json(res, 200, await adapter.models(cfg, env));
|
||||
},
|
||||
|
||||
/* Connect the instance credential. Deferred while the fixture was the only provider — it
|
||||
has none, so there was nothing to connect. The real providers give it something to hold,
|
||||
which is the condition this route was waiting on.
|
||||
@@ -184,26 +223,31 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const body = await readBody(req);
|
||||
const cfg = cfgStore.load();
|
||||
const meta = cfgStore.providerMeta(cfg);
|
||||
// A key may be filed for a provider that is not the active one, so the chips can be
|
||||
// prepared ahead of switching; by default it is the active provider's.
|
||||
const provider = body.provider !== undefined ? String(body.provider) : cfg.provider;
|
||||
if (!cfgStore.PROVIDERS[provider]) return json(res, 400, { error: 'unknown provider' });
|
||||
const meta = cfgStore.PROVIDERS[provider];
|
||||
const type = String(body.type || '');
|
||||
const envVar = (type === 'cli-token' || type === 'oauth') ? meta.oauthEnv
|
||||
: type === 'apikey' ? meta.apiKeyEnv : null;
|
||||
if (!envVar) {
|
||||
return json(res, 400, { error: `${cfg.provider} does not take a credential of type "${type}"` });
|
||||
return json(res, 400, { error: `${provider} does not take a credential of type "${type}"` });
|
||||
}
|
||||
const token = String(body.token || '').trim();
|
||||
if (!token) return json(res, 400, { error: 'no token supplied' });
|
||||
// boundUid resets with the credential: a new account has not been spent by anyone yet.
|
||||
cfgStore.save({
|
||||
auth: { type, account: String(body.account || '').slice(0, 120), data: cfgStore.encrypt({ token }) },
|
||||
boundUid: null
|
||||
cfgStore.saveAuth(provider, {
|
||||
type, account: String(body.account || '').slice(0, 120), data: cfgStore.encrypt({ token }), connectedAt: new Date().toISOString()
|
||||
});
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
'POST /api/admin/coach/disconnect': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
cfgStore.save({ auth: null, boundUid: null });
|
||||
const body = await readBody(req);
|
||||
const provider = body.provider !== undefined ? String(body.provider) : cfgStore.load().provider;
|
||||
if (!cfgStore.PROVIDERS[provider]) return json(res, 400, { error: 'unknown provider' });
|
||||
cfgStore.saveAuth(provider, null);
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
/* The four HTTPS providers, driven with a fake fetch.
|
||||
*
|
||||
* What is asserted is the request each one puts on the wire — URL, headers, body — and how
|
||||
* every way a call can go wrong lands in the { code, text, stderr } contract the pipeline
|
||||
* classifies. The classification itself is asserted through the real pipeline, so a change
|
||||
* to its regex and a change to an adapter's stderr cannot drift apart without a red build.
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { tempData } from './helpers.mjs';
|
||||
|
||||
tempData();
|
||||
const anthropic = (await import('../coach/core/adapters/anthropic.js')).default;
|
||||
const openai = (await import('../coach/core/adapters/openai.js')).default;
|
||||
const gemini = (await import('../coach/core/adapters/gemini.js')).default;
|
||||
const compatible = (await import('../coach/core/adapters/compatible.js')).default;
|
||||
const { attemptOnce } = await import('../coach/core/pipeline.js');
|
||||
const { HTTP_PROVIDERS, validateBaseUrl } = await import('../coach/core/providers.js');
|
||||
const { SYSTEM_PROMPT } = await import('../coach/core/system-prompt.js');
|
||||
|
||||
/** A fetch that records what it was asked and answers from a script. */
|
||||
function fakeFetch(answers) {
|
||||
const calls = [];
|
||||
const f = async (url, init) => {
|
||||
calls.push({ url, method: init.method, headers: init.headers || {}, body: init.body ? JSON.parse(init.body) : null });
|
||||
const a = typeof answers === 'function' ? answers(calls.length, url, init) : answers[Math.min(calls.length, answers.length) - 1];
|
||||
if (a instanceof Error) throw a;
|
||||
return { ok: a.status >= 200 && a.status < 300, status: a.status, text: async () => (typeof a.body === 'string' ? a.body : JSON.stringify(a.body)) };
|
||||
};
|
||||
f.calls = calls;
|
||||
return f;
|
||||
}
|
||||
const ok = body => ({ status: 200, body });
|
||||
const env = { ANTHROPIC_API_KEY: 'sk-ant-1', OPENAI_API_KEY: 'sk-oa-1', GEMINI_API_KEY: 'AIza-1', OPENAI_COMPAT_API_KEY: 'compat-1' };
|
||||
const cfgCompat = { provider: 'compatible', providerOptions: { compatible: { baseUrl: 'http://ollama.lan:11434/' } } };
|
||||
const ANSWER = '{"coach_contract":1,"nochange":true,"reading":"fine"}';
|
||||
|
||||
test('the four HTTP adapters spawn nothing and need no runtime', () => {
|
||||
for (const a of [anthropic, openai, gemini, compatible]) {
|
||||
assert.equal(a.spawns, false, a.id);
|
||||
assert.equal(a.needsRuntime, false, a.id);
|
||||
assert.ok(HTTP_PROVIDERS[a.id], `${a.id} is described in core/providers.js`);
|
||||
}
|
||||
});
|
||||
|
||||
test('Anthropic: /v1/messages with the key in a header, the shared system prompt, and the text joined back', async () => {
|
||||
const f = fakeFetch([ok({ content: [{ type: 'text', text: '{"a":' }, { type: 'text', text: '1}' }], stop_reason: 'end_turn' })]);
|
||||
const r = await anthropic.invoke({ cfg: {}, prompt: 'P', env, model: null, fetch: f });
|
||||
assert.equal(r.code, 0);
|
||||
assert.equal(r.text, '{"a":1}');
|
||||
const c = f.calls[0];
|
||||
assert.equal(c.url, 'https://api.anthropic.com/v1/messages');
|
||||
assert.equal(c.headers['x-api-key'], 'sk-ant-1');
|
||||
assert.equal(c.headers['anthropic-version'], '2023-06-01');
|
||||
assert.equal(c.headers['anthropic-dangerous-direct-browser-access'], 'true');
|
||||
assert.equal(c.body.model, HTTP_PROVIDERS.anthropic.defaultModel);
|
||||
assert.equal(c.body.system, SYSTEM_PROMPT);
|
||||
assert.deepEqual(c.body.messages, [{ role: 'user', content: 'P' }]);
|
||||
assert.ok(c.body.max_tokens >= 8000);
|
||||
assert.ok(!c.url.includes('sk-ant'), 'the key is never in the URL');
|
||||
});
|
||||
|
||||
test('OpenAI: chat completions in JSON mode, bearer auth, max_completion_tokens', async () => {
|
||||
const f = fakeFetch([ok({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] })]);
|
||||
const r = await openai.invoke({ cfg: {}, prompt: 'P', env, model: 'gpt-x', fetch: f });
|
||||
assert.equal(r.code, 0);
|
||||
assert.equal(r.text, ANSWER);
|
||||
const c = f.calls[0];
|
||||
assert.equal(c.url, 'https://api.openai.com/v1/chat/completions');
|
||||
assert.equal(c.headers.authorization, 'Bearer sk-oa-1');
|
||||
assert.equal(c.body.model, 'gpt-x');
|
||||
assert.deepEqual(c.body.response_format, { type: 'json_object' });
|
||||
assert.equal(c.body.messages[0].role, 'system');
|
||||
assert.equal(c.body.messages[0].content, SYSTEM_PROMPT);
|
||||
assert.equal(c.body.messages[1].content, 'P');
|
||||
assert.ok('max_completion_tokens' in c.body && !('max_tokens' in c.body));
|
||||
});
|
||||
|
||||
test('Gemini: generateContent with the key as a header — never ?key= — and JSON output requested', async () => {
|
||||
const f = fakeFetch([ok({ candidates: [{ content: { parts: [{ text: ANSWER }] }, finishReason: 'STOP' }] })]);
|
||||
const r = await gemini.invoke({ cfg: {}, prompt: 'P', env, model: 'gemini-z', fetch: f });
|
||||
assert.equal(r.code, 0);
|
||||
assert.equal(r.text, ANSWER);
|
||||
const c = f.calls[0];
|
||||
assert.equal(c.url, 'https://generativelanguage.googleapis.com/v1beta/models/gemini-z:generateContent');
|
||||
assert.equal(c.headers['x-goog-api-key'], 'AIza-1');
|
||||
assert.ok(!c.url.includes('key='), 'the key is never a query parameter');
|
||||
assert.equal(c.body.generationConfig.responseMimeType, 'application/json');
|
||||
assert.equal(c.body.systemInstruction.parts[0].text, SYSTEM_PROMPT);
|
||||
assert.equal(c.body.contents[0].parts[0].text, 'P');
|
||||
});
|
||||
|
||||
test('compatible: the configured base URL, max_tokens, and no Authorization header when there is no key', async () => {
|
||||
const f = fakeFetch([ok({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] })]);
|
||||
const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env: {}, model: 'llama3', fetch: f });
|
||||
assert.equal(r.code, 0);
|
||||
const c = f.calls[0];
|
||||
assert.equal(c.url, 'http://ollama.lan:11434/v1/chat/completions');
|
||||
assert.equal(c.headers.authorization, undefined);
|
||||
assert.ok('max_tokens' in c.body && !('max_completion_tokens' in c.body));
|
||||
|
||||
// …and with a key, it is sent.
|
||||
const g = fakeFetch([ok({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] })]);
|
||||
await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env, model: 'llama3', fetch: g });
|
||||
assert.equal(g.calls[0].headers.authorization, 'Bearer compat-1');
|
||||
});
|
||||
|
||||
test('compatible: no endpoint configured, or no model chosen, is a clean failure rather than a request', async () => {
|
||||
const f = fakeFetch([]);
|
||||
const none = await compatible.invoke({ cfg: {}, prompt: 'P', env: {}, model: 'x', fetch: f });
|
||||
assert.equal(none.spawnError, true);
|
||||
const noModel = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env: {}, model: null, fetch: f });
|
||||
assert.equal(noModel.code, 1);
|
||||
assert.match(noModel.stderr, /no model/);
|
||||
assert.equal(f.calls.length, 0);
|
||||
});
|
||||
|
||||
test('compatible: a server that rejects JSON mode gets the same request once more without it', async () => {
|
||||
const f = fakeFetch(n => n === 1
|
||||
? { status: 400, body: { error: { message: 'response_format is not supported' } } }
|
||||
: ok({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] }));
|
||||
const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env: {}, model: 'llama3', fetch: f });
|
||||
assert.equal(r.code, 0);
|
||||
assert.equal(f.calls.length, 2);
|
||||
assert.ok('response_format' in f.calls[0].body);
|
||||
assert.ok(!('response_format' in f.calls[1].body));
|
||||
});
|
||||
|
||||
test('a missing key is "missing", like an absent CLI — no request is made', async () => {
|
||||
const f = fakeFetch([]);
|
||||
const r = await anthropic.invoke({ cfg: {}, prompt: 'P', env: {}, fetch: f });
|
||||
assert.equal(r.spawnError, true);
|
||||
assert.equal(f.calls.length, 0);
|
||||
const cls = await attemptOnce({ adapter: anthropic, cfg: {}, kind: 'review', payload: { plan: { routines: [], week: {} } }, invokeOpts: { env: {}, fetch: f } }, null);
|
||||
assert.equal(cls.errorClass, 'missing');
|
||||
});
|
||||
|
||||
test('401 and 403 reach the pipeline as "auth"; other statuses as "provider"', async () => {
|
||||
const payload = { plan: { routines: [], week: {} } };
|
||||
for (const [status, expect] of [[401, 'auth'], [403, 'auth'], [429, 'provider'], [500, 'provider']]) {
|
||||
const f = fakeFetch([{ status, body: { error: { message: 'nope' } } }]);
|
||||
const r = await openai.invoke({ cfg: {}, prompt: 'P', env, fetch: f });
|
||||
assert.equal(r.code, 1);
|
||||
assert.ok(r.stderr.startsWith(String(status)), `stderr starts with the status: ${r.stderr}`);
|
||||
const cls = await attemptOnce({ adapter: openai, cfg: {}, kind: 'review', payload, invokeOpts: { env, fetch: f } }, null);
|
||||
assert.equal(cls.errorClass, expect, `${status} → ${expect}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('a body that is not JSON on an error still yields a readable stderr', async () => {
|
||||
const f = fakeFetch([{ status: 502, body: '<html>bad gateway</html>' }]);
|
||||
const r = await gemini.invoke({ cfg: {}, prompt: 'P', env, fetch: f });
|
||||
assert.equal(r.code, 1);
|
||||
assert.match(r.stderr, /^502 .*bad gateway/);
|
||||
});
|
||||
|
||||
test('an answer cut off at the output limit fails as "provider", not as a half-parsed proposal', async () => {
|
||||
const cases = [
|
||||
[anthropic, ok({ content: [{ type: 'text', text: '{"coach_contract":1,"changes":[' }], stop_reason: 'max_tokens' })],
|
||||
[openai, ok({ choices: [{ message: { content: '{"coach_contract":1,"changes":[' }, finish_reason: 'length' }] })],
|
||||
[gemini, ok({ candidates: [{ content: { parts: [{ text: '{"coach_contract":1,' }] }, finishReason: 'MAX_TOKENS' }] })]
|
||||
];
|
||||
for (const [adapter, answer] of cases) {
|
||||
const f = fakeFetch([answer]);
|
||||
const r = await adapter.invoke({ cfg: {}, prompt: 'P', env, model: 'm', fetch: f });
|
||||
assert.equal(r.code, 1, adapter.id);
|
||||
assert.match(r.stderr, /cut off/, adapter.id);
|
||||
const cls = await attemptOnce({ adapter, cfg: {}, kind: 'review', payload: { plan: { routines: [], week: {} } }, invokeOpts: { env, fetch: f } }, null);
|
||||
assert.equal(cls.errorClass, 'provider', adapter.id);
|
||||
assert.equal(cls.repairable, undefined, 'the repair round is not spent on a truncated answer');
|
||||
}
|
||||
});
|
||||
|
||||
test('a refusal, and a Gemini safety stop, are provider errors with the reason in stderr', async () => {
|
||||
const a = fakeFetch([ok({ content: [], stop_reason: 'refusal', stop_details: { explanation: 'policy' } })]);
|
||||
const ra = await anthropic.invoke({ cfg: {}, prompt: 'P', env, fetch: a });
|
||||
assert.equal(ra.code, 1); assert.match(ra.stderr, /declined.*policy/);
|
||||
const g = fakeFetch([ok({ candidates: [{ content: { parts: [] }, finishReason: 'SAFETY' }] })]);
|
||||
const rg = await gemini.invoke({ cfg: {}, prompt: 'P', env, fetch: g });
|
||||
assert.equal(rg.code, 1); assert.match(rg.stderr, /SAFETY/);
|
||||
const b = fakeFetch([ok({ promptFeedback: { blockReason: 'OTHER' } })]);
|
||||
const rb = await gemini.invoke({ cfg: {}, prompt: 'P', env, fetch: b });
|
||||
assert.equal(rb.code, 1); assert.match(rb.stderr, /blocked: OTHER/);
|
||||
});
|
||||
|
||||
test('a fetch that throws names the host; an abort is a timeout', async () => {
|
||||
const boom = fakeFetch([Object.assign(new Error('ECONNREFUSED'), { name: 'TypeError' })]);
|
||||
const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env: {}, model: 'm', fetch: boom });
|
||||
assert.equal(r.code, 1);
|
||||
assert.match(r.stderr, /could not reach ollama\.lan:11434/);
|
||||
|
||||
// A fetch that only settles when the signal aborts — what a hung server looks like.
|
||||
const hang = (url, init) => new Promise((_, reject) => init.signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))));
|
||||
const t = await openai.invoke({ cfg: {}, prompt: 'P', env, timeoutMs: 20, fetch: hang });
|
||||
assert.equal(t.timedOut, true);
|
||||
const cls = await attemptOnce({ adapter: openai, cfg: {}, kind: 'review', payload: { plan: { routines: [], week: {} } }, timeoutMs: 20, invokeOpts: { env, fetch: hang } }, null);
|
||||
assert.equal(cls.errorClass, 'timeout');
|
||||
});
|
||||
|
||||
test('models(): each list shape is read, sorted, and Gemini is filtered to generateContent', async () => {
|
||||
const oa = fakeFetch([ok({ data: [{ id: 'gpt-b' }, { id: 'gpt-a' }] })]);
|
||||
assert.deepEqual((await openai.models({}, env, { fetch: oa })).models, ['gpt-a', 'gpt-b']);
|
||||
assert.equal(oa.calls[0].url, 'https://api.openai.com/v1/models');
|
||||
assert.equal(oa.calls[0].method, 'GET');
|
||||
|
||||
const an = fakeFetch([ok({ data: [{ id: 'claude-z' }, { id: 'claude-a' }] })]);
|
||||
assert.deepEqual((await anthropic.models({}, env, { fetch: an })).models, ['claude-a', 'claude-z']);
|
||||
assert.equal(an.calls[0].headers['anthropic-version'], '2023-06-01');
|
||||
|
||||
const ge = fakeFetch([ok({ models: [
|
||||
{ name: 'models/gemini-b', supportedGenerationMethods: ['generateContent'] },
|
||||
{ name: 'models/embedding-1', supportedGenerationMethods: ['embedContent'] },
|
||||
{ name: 'models/gemini-a', supportedGenerationMethods: ['generateContent'] }
|
||||
] })]);
|
||||
assert.deepEqual((await gemini.models({}, env, { fetch: ge })).models, ['gemini-a', 'gemini-b']);
|
||||
assert.ok(ge.calls[0].url.startsWith('https://generativelanguage.googleapis.com/v1beta/models'));
|
||||
|
||||
const bad = fakeFetch([{ status: 401, body: { error: { message: 'bad key' } } }]);
|
||||
const r = await openai.models({}, env, { fetch: bad });
|
||||
assert.equal(r.ok, false);
|
||||
assert.match(r.error, /^401 bad key/);
|
||||
});
|
||||
|
||||
test('check(): without a key the runtime is ready and the key is what is missing; with one it lists models', async () => {
|
||||
const none = await anthropic.check({}, {}, { fetch: fakeFetch([]) });
|
||||
assert.equal(none.ok, true);
|
||||
assert.equal(none.needsKey, true);
|
||||
const f = fakeFetch([ok({ data: [{ id: 'claude-a' }] })]);
|
||||
const some = await anthropic.check({}, env, { fetch: f });
|
||||
assert.equal(some.ok, true);
|
||||
assert.match(some.version, /api\.anthropic\.com · 1 models/);
|
||||
const noBase = await compatible.check({}, {}, { fetch: fakeFetch([]) });
|
||||
assert.equal(noBase.ok, false);
|
||||
});
|
||||
|
||||
test('validateBaseUrl: http(s) only, no credentials, no query, trailing slash dropped', () => {
|
||||
assert.deepEqual(validateBaseUrl('http://ollama.lan:11434/'), { ok: true, value: 'http://ollama.lan:11434' });
|
||||
assert.deepEqual(validateBaseUrl(' '), { ok: true, value: null });
|
||||
assert.equal(validateBaseUrl('ftp://x').ok, false);
|
||||
assert.equal(validateBaseUrl('http://user:pw@x').ok, false);
|
||||
assert.equal(validateBaseUrl('http://x/?key=1').ok, false);
|
||||
assert.equal(validateBaseUrl('not a url').ok, false);
|
||||
});
|
||||
@@ -84,3 +84,14 @@ test('a configured model is appended, and nothing else is', () => {
|
||||
assert.deepEqual(argvFor('o4-mini').slice(-2), ['--model', 'o4-mini']);
|
||||
assert.equal(argvFor('o4-mini').length, argvFor(null).length + 2);
|
||||
});
|
||||
|
||||
test('every adapter states whether it spawns a process — the privilege gate reads that, not an absence', () => {
|
||||
for (const [id, a] of Object.entries(ADAPTERS)) assert.equal(typeof a.spawns, 'boolean', `${id}.spawns`);
|
||||
for (const id of ['fixture', 'claude', 'codex']) assert.equal(ADAPTERS[id].spawns, true, id);
|
||||
for (const id of ['anthropic', 'openai', 'gemini', 'compatible']) {
|
||||
assert.equal(ADAPTERS[id].spawns, false, id);
|
||||
assert.equal(cfg.PROVIDERS[id].http, true, id);
|
||||
assert.equal(cfg.PROVIDERS[id].credentialHomeEnv, undefined, `${id} keeps no credential cache`);
|
||||
assert.equal(typeof ADAPTERS[id].models, 'function', `${id} can list models`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/* coach.json grew per-provider maps. The file a v1.2.11 instance already has on disk holds one
|
||||
* flat credential, one model and one binding; this pins that it is lifted onto the provider it
|
||||
* belonged to, once, and that switching providers afterwards never throws a key away. */
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { tempData } from './helpers.mjs';
|
||||
|
||||
const dir = tempData();
|
||||
const cfg = await import('../coach/config.js');
|
||||
const FILE = path.join(dir, 'coach.json');
|
||||
|
||||
function onDisk(obj) {
|
||||
fs.writeFileSync(FILE, JSON.stringify(obj));
|
||||
cfg.reset();
|
||||
return cfg.load();
|
||||
}
|
||||
|
||||
test('a flat v1.2.11 file is lifted onto its provider', () => {
|
||||
const blob = cfg.encrypt({ token: 'tok' });
|
||||
const c = onDisk({ enabled: true, provider: 'claude', model: 'claude-x', boundUid: 'alice',
|
||||
auth: { type: 'cli-token', account: 'me', data: blob } });
|
||||
assert.deepEqual(c.auth, { claude: { type: 'cli-token', account: 'me', data: blob } });
|
||||
assert.deepEqual(c.models, { claude: 'claude-x' });
|
||||
assert.deepEqual(c.boundUid, { claude: 'alice' });
|
||||
assert.equal(c.model, undefined, 'the flat field is gone');
|
||||
assert.equal(cfg.authFor(c).type, 'cli-token');
|
||||
assert.equal(cfg.modelFor(c), 'claude-x');
|
||||
assert.equal(cfg.boundUidFor(c), 'alice');
|
||||
assert.equal(cfg.credentialFor('alice').auth.token, 'tok');
|
||||
});
|
||||
|
||||
test('a flat file whose provider was retired keeps nothing from it', () => {
|
||||
const c = onDisk({ provider: 'gemini-cli', model: 'x', boundUid: 'alice', auth: { type: 'apikey', data: cfg.encrypt({ token: 't' }) } });
|
||||
assert.equal(c.provider, 'fixture');
|
||||
assert.deepEqual(c.auth, {});
|
||||
assert.deepEqual(c.models, {});
|
||||
assert.deepEqual(c.boundUid, {});
|
||||
});
|
||||
|
||||
test('the new shape loads as-is, and unknown or hostile keys in the maps are dropped', () => {
|
||||
const c = onDisk({ provider: 'openai',
|
||||
auth: { openai: { type: 'apikey', data: 'x' }, 'not-a-provider': { data: 'y' }, __proto__: { data: 'z' } },
|
||||
models: { openai: 'gpt-a', gemini: 'g-b', constructor: 'c' },
|
||||
providerOptions: { compatible: { baseUrl: 'http://x' } },
|
||||
boundUid: 'legacy-string-with-new-maps' });
|
||||
assert.deepEqual(Object.keys(c.auth), ['openai']);
|
||||
assert.deepEqual(c.models, { openai: 'gpt-a', gemini: 'g-b' });
|
||||
assert.deepEqual(c.providerOptions, { compatible: { baseUrl: 'http://x' } });
|
||||
assert.deepEqual(c.boundUid, { openai: 'legacy-string-with-new-maps' });
|
||||
assert.equal(Object.getPrototypeOf(c.auth), Object.prototype, 'a __proto__ key never became a prototype');
|
||||
});
|
||||
|
||||
test('switching provider keeps every key; each provider has its own model and binding', () => {
|
||||
onDisk({ enabled: true, provider: 'anthropic' });
|
||||
cfg.saveAuth('anthropic', { type: 'apikey', data: cfg.encrypt({ token: 'a' }) });
|
||||
cfg.saveModel('anthropic', 'claude-a');
|
||||
cfg.bindInstanceCredential('alice');
|
||||
assert.equal(cfg.boundUidFor(), 'alice');
|
||||
|
||||
cfg.save({ provider: 'openai' });
|
||||
assert.equal(cfg.authFor(), null, 'openai has no key yet');
|
||||
assert.equal(cfg.modelFor(), 'gpt-5.6', 'openai falls back to its default model');
|
||||
assert.equal(cfg.boundUidFor(), null, 'the binding belongs to the anthropic key');
|
||||
cfg.saveAuth('openai', { type: 'apikey', data: cfg.encrypt({ token: 'o' }) });
|
||||
|
||||
cfg.save({ provider: 'anthropic' });
|
||||
assert.equal(cfg.credentialFor('alice').auth.token, 'a', 'the anthropic key survived the round trip');
|
||||
assert.equal(cfg.modelFor(), 'claude-a');
|
||||
assert.equal(cfg.boundUidFor(), 'alice');
|
||||
assert.equal(cfg.authFor(cfg.load(), 'openai').type, 'apikey');
|
||||
|
||||
// Disconnecting one provider leaves the other alone, and clears only its own binding.
|
||||
cfg.saveAuth('openai', null);
|
||||
assert.equal(cfg.authFor(cfg.load(), 'openai'), null);
|
||||
assert.equal(cfg.credentialFor('alice').ok, true);
|
||||
});
|
||||
|
||||
test('an OpenAI-compatible endpoint with no key is connected once it has a base URL', () => {
|
||||
onDisk({ enabled: true, provider: 'compatible' });
|
||||
assert.equal(cfg.isConnected(), false, 'no endpoint yet');
|
||||
cfg.saveOptions('compatible', { baseUrl: 'http://ollama.lan:11434' });
|
||||
assert.equal(cfg.isConnected(), true);
|
||||
const c = cfg.credentialFor('anyone');
|
||||
assert.equal(c.ok, true);
|
||||
assert.equal(c.auth, null);
|
||||
assert.equal(cfg.publicConfig().provider, 'compatible');
|
||||
// …and a key that was filed but cannot be read is still a failure, not "optional".
|
||||
cfg.saveAuth('compatible', { type: 'apikey', data: 'garbage' });
|
||||
assert.equal(cfg.isConnected(), false);
|
||||
assert.equal(cfg.credentialFor('anyone').ok, false);
|
||||
});
|
||||
|
||||
test('jobEnv carries only the active provider\'s key under its own variable', () => {
|
||||
onDisk({ enabled: true, provider: 'gemini' });
|
||||
cfg.saveAuth('gemini', { type: 'apikey', data: cfg.encrypt({ token: 'g' }) });
|
||||
cfg.saveAuth('openai', { type: 'apikey', data: cfg.encrypt({ token: 'o' }) });
|
||||
const env = cfg.jobEnv('/tmp/x', cfg.credentialFor('alice'));
|
||||
assert.equal(env.GEMINI_API_KEY, 'g');
|
||||
assert.equal(env.OPENAI_API_KEY, undefined);
|
||||
assert.deepEqual(Object.keys(env).sort(), ['GEMINI_API_KEY', 'HOME', 'PATH', 'TMPDIR']);
|
||||
});
|
||||
@@ -16,8 +16,8 @@ const cfg = await import('../coach/config.js');
|
||||
function connectInstance(token = 'tok-instance') {
|
||||
cfg.reset();
|
||||
cfg.save({
|
||||
enabled: true, provider: 'claude', authMode: 'instance', boundUid: null,
|
||||
auth: { type: 'cli-token', account: 'owner@example.test', data: cfg.encrypt({ token }) }
|
||||
enabled: true, provider: 'claude', authMode: 'instance', boundUid: {},
|
||||
auth: { claude: { type: 'cli-token', account: 'owner@example.test', data: cfg.encrypt({ token }) } }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -26,10 +26,10 @@ test('instance mode: the first profile to spend the credential binds it', () =>
|
||||
const first = cfg.credentialFor('alice');
|
||||
assert.equal(first.ok, true);
|
||||
assert.equal(first.auth.token, 'tok-instance');
|
||||
assert.equal(cfg.load().boundUid, null, 'resolving alone must not bind — only spending does');
|
||||
assert.equal(cfg.boundUidFor(), null, 'resolving alone must not bind — only spending does');
|
||||
|
||||
cfg.bindInstanceCredential('alice');
|
||||
assert.equal(cfg.load().boundUid, 'alice');
|
||||
assert.equal(cfg.boundUidFor(), 'alice');
|
||||
});
|
||||
|
||||
test('instance mode: a second profile is refused, not warned', () => {
|
||||
|
||||
@@ -261,3 +261,49 @@ test('a job is refused outright when the privilege drop cannot be performed', ()
|
||||
forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' });
|
||||
}
|
||||
});
|
||||
|
||||
test('an HTTPS provider is not refused for lacking a privilege drop, and runs end to end through the queue', async () => {
|
||||
// A local server speaking OpenAI's Chat Completions shape, answering a valid "no change"
|
||||
// review. This is the whole reason the HTTP adapters exist: no runtime, no child process,
|
||||
// nothing to drop privileges on — so the gate that refuses everything on a host without a
|
||||
// `coach` user must let this one through, and the job must still run the real pipeline.
|
||||
const http = await import('node:http');
|
||||
const seen = [];
|
||||
const server = http.createServer((req, res) => {
|
||||
let body = '';
|
||||
req.on('data', c => { body += c; });
|
||||
req.on('end', () => {
|
||||
seen.push({ url: req.url, auth: req.headers.authorization, body: JSON.parse(body || '{}') });
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({ choices: [{ finish_reason: 'stop', message: { content: '{"coach_contract":1,"nochange":true,"reading":"Steady as she goes."}' } }] }));
|
||||
});
|
||||
});
|
||||
await new Promise(r => server.listen(0, '127.0.0.1', r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
|
||||
const uid = 'u-https';
|
||||
writeState(DIR, uid, sampleState());
|
||||
cfg.save({ enabled: true, provider: 'compatible', providerOptions: { compatible: { baseUrl: base } }, models: { compatible: 'local-model' } });
|
||||
forcePrivilegeVerdict({ ok: false, dropped: false, why: 'no `coach` user exists in this image' });
|
||||
try {
|
||||
jobs.enqueue(uid, { kind: 'review' });
|
||||
const s = await settle(uid);
|
||||
assert.equal(s.job, null);
|
||||
assert.equal(lastOutcome(uid).outcome, 'nochange');
|
||||
assert.equal(lastOutcome(uid).reading, 'Steady as she goes.');
|
||||
assert.equal(seen.length, 1);
|
||||
assert.equal(seen[0].url, '/v1/chat/completions');
|
||||
assert.equal(seen[0].auth, undefined, 'no key configured, so no Authorization header');
|
||||
assert.equal(seen[0].body.model, 'local-model');
|
||||
assert.ok(seen[0].body.messages[1].content.includes('"coach_contract": 1'), 'the payload rode in the user turn');
|
||||
|
||||
// And the same host refuses a runtime-backed provider, so the gate itself is intact.
|
||||
cfg.save({ provider: 'fixture' });
|
||||
writeState(DIR, 'u-https-2', sampleState());
|
||||
assert.throws(() => jobs.enqueue('u-https-2', { kind: 'review' }), e => e.code === 'unprivileged');
|
||||
} finally {
|
||||
forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' });
|
||||
cfg.save({ provider: 'fixture' });
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
@@ -25,8 +25,19 @@ export default function AdminCoach() {
|
||||
const openSheet = useUI(s => s.openSheet)
|
||||
const [d, setD] = useState(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
// The models the endpoint serves, fetched on demand. Seeded from the status call when the
|
||||
// stored key already let it list them.
|
||||
const [models, setModels] = useState(null)
|
||||
|
||||
const load = () => api('/api/admin/coach').then(setD).catch(e => toast(e.message || 'Failed to load'))
|
||||
const load = () => api('/api/admin/coach').then(r => { setD(r); setModels(r.knownModels || null) }).catch(e => toast(e.message || 'Failed to load'))
|
||||
const loadModels = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const r = await api('/api/admin/coach/models', { method: 'POST', body: '{}' })
|
||||
if (r.ok) { setModels(r.models); toast(r.models.length + ' models') } else toast(r.error || 'Could not list models')
|
||||
} catch (e) { toast(e.message) }
|
||||
setBusy(false)
|
||||
}
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
const patch = async body => {
|
||||
@@ -59,7 +70,7 @@ export default function AdminCoach() {
|
||||
</div>
|
||||
|
||||
const meta = d.providers.find(p => p.id === d.provider) || {}
|
||||
const authed = d.auth?.state === 'connected' || d.auth?.state === 'not-required'
|
||||
const authed = d.auth?.state === 'connected' || d.auth?.state === 'not-required' || d.auth?.state === 'optional'
|
||||
const live = d.enabled && d.runtime.ok && authed
|
||||
|
||||
return <div className="card" style={{ borderColor: live ? 'var(--acc)' : undefined }}>
|
||||
@@ -109,9 +120,20 @@ export default function AdminCoach() {
|
||||
{/* provider */}
|
||||
<h4 className="sec" style={{ marginTop: 4 }}>Provider</h4>
|
||||
<div className="row" style={{ flexWrap: 'wrap', gap: 7, marginBottom: 10 }}>
|
||||
{d.providers.map(p => <button key={p.id} className={'chip' + (p.id === d.provider ? ' on' : '')}
|
||||
disabled={busy} onClick={() => patch({ provider: p.id })}>{p.label}</button>)}
|
||||
{d.providers.map(p => <button key={p.id} className={'chip' + (p.id === d.provider ? ' on' : '')} title={p.connected ? 'a key is stored for this provider' : undefined}
|
||||
disabled={busy} onClick={() => patch({ provider: p.id })}>{p.label}{p.connected ? ' ·' : ''}</button>)}
|
||||
</div>
|
||||
{meta.http && <div className="dim small" style={{ marginTop: -4, marginBottom: 10 }}>
|
||||
Plain HTTPS to the provider — no AI runtime needed in the image, so this works on the default <code>api</code> image. Keys stay per provider when you switch.
|
||||
</div>}
|
||||
|
||||
{/* endpoint — only for the provider whose endpoint is the whole configuration */}
|
||||
{meta.baseUrl && <>
|
||||
<h4 className="sec">Endpoint</h4>
|
||||
<TextField defaultValue={d.baseUrl || ''} placeholder="http://ollama.lan:11434 or https://openrouter.ai/api"
|
||||
onBlur={e => e.target.value !== (d.baseUrl || '') && patch({ baseUrl: e.target.value })} />
|
||||
<div className="dim small" style={{ marginBottom: 10 }}>Anything that serves OpenAI's Chat Completions shape: Ollama, LM Studio, vLLM, OpenRouter, a gateway of your own. The host is written to the job log.</div>
|
||||
</>}
|
||||
|
||||
{/* credential */}
|
||||
{(meta.setupToken || meta.apiKey) && <>
|
||||
@@ -135,8 +157,10 @@ export default function AdminCoach() {
|
||||
<div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
|
||||
{meta.setupToken && <Button size="sm" variant="primary" icon="key" disabled={busy}
|
||||
onClick={() => openSheet(close => <SetupTokenSheet close={close} onDone={load} label={meta.label} />)}>Add CLI token</Button>}
|
||||
{meta.apiKey && !meta.setupToken && <Button size="sm" icon="lock" disabled={busy}
|
||||
onClick={() => openSheet(close => <ApiKeySheet close={close} onDone={load} label={meta.label} />)}>Use an API key</Button>}
|
||||
{meta.apiKey && <Button size="sm" variant={meta.setupToken ? undefined : 'primary'} icon="lock" disabled={busy}
|
||||
onClick={() => openSheet(close => <ApiKeySheet close={close} onDone={load} label={meta.label} placeholder={meta.keyPlaceholder} optional={meta.keyOptional} />)}>
|
||||
{meta.keyOptional ? 'Add an API key (optional)' : 'Use an API key'}</Button>}
|
||||
{meta.keyOptional && <Button size="sm" icon="check" disabled={busy} onClick={test}>Test the Coach</Button>}
|
||||
</div>
|
||||
</>}
|
||||
</>}
|
||||
@@ -154,8 +178,19 @@ export default function AdminCoach() {
|
||||
<div className="dim small" style={{ marginBottom: 10 }}>0 = no limit. Every job is one session on your provider account.</div>
|
||||
|
||||
<h4 className="sec">Model</h4>
|
||||
<TextField defaultValue={d.model || ''} placeholder="(the provider default)"
|
||||
onBlur={e => e.target.value !== (d.model || '') && patch({ model: e.target.value })} />
|
||||
{models && models.length ? <>
|
||||
<select className="sel" value={models.includes(d.model) ? d.model : ''} disabled={busy} style={{ width: '100%' }}
|
||||
onChange={e => patch({ model: e.target.value })}>
|
||||
<option value="">{meta.defaultModel ? `(default: ${meta.defaultModel})` : '(pick a model)'}</option>
|
||||
{!models.includes(d.model) && d.model && <option value={d.model}>{d.model} (not in the list)</option>}
|
||||
{models.map(m => <option key={m} value={m}>{m}</option>)}
|
||||
</select>
|
||||
</> : <TextField key={d.provider} defaultValue={d.models?.[d.provider] || ''} placeholder={meta.defaultModel ? `(default: ${meta.defaultModel})` : meta.baseUrl ? 'pick one from the endpoint' : '(the provider default)'}
|
||||
onBlur={e => e.target.value !== (d.models?.[d.provider] || '') && patch({ model: e.target.value })} />}
|
||||
{meta.http && <div className="row" style={{ gap: 8, marginTop: 6, marginBottom: 6 }}>
|
||||
<Button size="sm" disabled={busy} onClick={loadModels}>{models ? 'Refresh models' : 'List models'}</Button>
|
||||
{models && models.length ? <span className="dim small">{models.length} served by the endpoint</span> : null}
|
||||
</div>}
|
||||
|
||||
{d.lastError && <>
|
||||
<h4 className="sec">Last failure</h4>
|
||||
@@ -178,7 +213,7 @@ export default function AdminCoach() {
|
||||
}
|
||||
|
||||
const authLabel = a => ({
|
||||
connected: 'connected', 'not-required': 'n/a', disconnected: 'needed', expired: 'expired', unreadable: 'unreadable', 'replace-required': 'replace'
|
||||
connected: 'connected', 'not-required': 'n/a', none: 'needed', optional: 'none (optional)', disconnected: 'needed', expired: 'expired', unreadable: 'unreadable', 'replace-required': 'replace'
|
||||
}[a?.state] || '—')
|
||||
|
||||
const credentialLabel = type => ({
|
||||
@@ -219,7 +254,7 @@ function SetupTokenSheet({ close, onDone, label }) {
|
||||
</>
|
||||
}
|
||||
|
||||
function ApiKeySheet({ close, onDone, label }) {
|
||||
function ApiKeySheet({ close, onDone, label, placeholder, optional }) {
|
||||
const toast = useUI(s => s.toast)
|
||||
const [key, setKey] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
@@ -234,9 +269,9 @@ function ApiKeySheet({ close, onDone, label }) {
|
||||
return <>
|
||||
<h3>{label} API key</h3>
|
||||
<div className="muted small" style={{ lineHeight: 1.5, marginBottom: 12 }}>
|
||||
Stored encrypted on this server and passed to the provider runtime only while a job runs. It is never shown again and never leaves the server.
|
||||
Stored encrypted on this server and sent to the provider only while a job runs. It is never shown again and never leaves the server{optional ? ' — and for an endpoint that takes no key, leave this empty.' : '.'}
|
||||
</div>
|
||||
<TextField value={key} autoFocus type="password" placeholder="sk-…" onChange={e => setKey(e.target.value)} />
|
||||
<TextField value={key} autoFocus type="password" placeholder={placeholder || 'sk-…'} onChange={e => setKey(e.target.value)} />
|
||||
<div style={{ height: 12 }} />
|
||||
<Button variant="primary" disabled={busy || !key.trim()} onClick={save}>Save key</Button>
|
||||
<div style={{ height: 8 }} />
|
||||
|
||||
Reference in new issue
Block a user