Configure the Coach from the environment
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
An instance can now be pointed at a model entirely from its environment — so a
container is redeployed with the Coach already working, and nobody has to open
an admin screen:
COACH_PROVIDER=compatible
COACH_BASE_URL=https://ai.example.com # WITHOUT /v1 — the adapter adds it
COACH_MODEL=vendor/model-name
COACH_API_KEY=sk-... # or the provider's own variable
Naming a provider is the whole configuration, so it also turns the Coach on: an
instance started this way that then reported itself "off" would be a puzzle with
no clue in it.
Three decisions worth stating:
- The environment is the *base*, the way DEFAULTS is, and the saved file is
layered on top: an admin who picked a provider in the app meant it, and this
only fills what is absent.
- The key is deliberately NOT a field of the config. That object is cached,
written to data/coach.json by any admin action, and included in the backup the
docs tell people to make. envCredentialFor reads it from the process
environment instead, so it is written nowhere and never surfaced by any route
that reports configuration. A pasted credential still outranks it, and a filed
one that fails to decrypt stays a failure rather than quietly falling back to
a key nobody knows is being spent.
- What the environment supplies is stripped before the file is written. A saved
config used to be written back whole, which would have frozen this start-up's
values on disk — and since the file outranks the environment, a later change
to COACH_MODEL would have been silently ignored.
Verified through the server's own path (config → credentialFor → jobEnv →
adapter) against the OpenAI-compatible router this fork runs on: a chest+triceps
request came back as a six-exercise routine with the cardio row first and
correctly marked `mode: cardio`.
This commit is contained in:
1 parent
327aa5211b
commit
238eb635c5
3 files changed
+215
-6
No files matched your search
+94
-3
@@ -43,6 +43,52 @@ const FILE = path.join(DATA, 'coach.json');
|
||||
export const CREDENTIAL_HOME = process.env.COACH_CREDENTIAL_DIR || '/coach-auth';
|
||||
export const COACH_DISABLED = /^(1|true|yes|on)$/i.test(process.env.COACH_DISABLED || '');
|
||||
|
||||
/* ---------- configured from the environment ----------
|
||||
* An instance can be given its provider at start-up, so a container is redeployed with the Coach
|
||||
* already pointed at a model and nobody has to open an admin screen:
|
||||
*
|
||||
* COACH_PROVIDER=compatible
|
||||
* COACH_BASE_URL=https://ai.example.com (the endpoint WITHOUT /v1 — the adapter adds it)
|
||||
* COACH_MODEL=some/model
|
||||
* COACH_API_KEY=sk-… (or the provider's own variable, e.g. OPENAI_COMPAT_API_KEY)
|
||||
*
|
||||
* These are the *base* the saved file is layered on top of, exactly like DEFAULTS: an admin who
|
||||
* picked a provider in the app meant it, and their choice wins. The credential is the exception
|
||||
* and is not part of the config at all — see envCredentialFor, which reads it fresh and never
|
||||
* lets it reach the file on disk. */
|
||||
const envText = name => (process.env[name] || '').trim() || null;
|
||||
|
||||
function envPatch() {
|
||||
const provider = envText('COACH_PROVIDER');
|
||||
if (!provider || !PROVIDERS[provider]) return {};
|
||||
const baseUrl = envText('COACH_BASE_URL');
|
||||
const model = envText('COACH_MODEL');
|
||||
return {
|
||||
// Naming a provider in the environment is the whole configuration: an instance started this
|
||||
// way that then reported "the Coach is off" would be a puzzle with no clue in it.
|
||||
enabled: true,
|
||||
provider,
|
||||
...(baseUrl ? { providerOptions: { [provider]: { baseUrl } } } : {}),
|
||||
...(model ? { models: { [provider]: model } } : {})
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The credential this instance was started with, if any — `COACH_API_KEY`, or the variable the
|
||||
* provider itself declares (`OPENAI_COMPAT_API_KEY`, `OPENAI_API_KEY`, …).
|
||||
*
|
||||
* Read from the environment every time and held nowhere else. It is deliberately NOT a field of
|
||||
* the config: that object is cached, written to data/coach.json by any admin action, and included
|
||||
* in the backup the docs tell people to make. Encrypted credentials the admin pasted live there;
|
||||
* a key handed to the container does not belong in a file.
|
||||
*/
|
||||
export function envCredentialFor(provider) {
|
||||
const meta = PROVIDERS[provider];
|
||||
if (!meta) return null;
|
||||
const token = envText('COACH_API_KEY') || (meta.apiKeyEnv ? envText(meta.apiKeyEnv) : null);
|
||||
return token ? { type: 'apikey', account: null, token } : null;
|
||||
}
|
||||
|
||||
// Providers this build can drive. `runtime` is what the adapter runs. Adding one is an adapter
|
||||
// file plus a row here — nothing else in the codebase branches on provider identity. The real
|
||||
// providers arrive with their adapters; this PR ships only the in-repo fixture, so an instance
|
||||
@@ -128,7 +174,19 @@ export function load() {
|
||||
if (cache) return cache;
|
||||
let stored = {};
|
||||
try { stored = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch { /* absent = feature off */ }
|
||||
cache = { ...DEFAULTS, ...stored, caps: { ...DEFAULTS.caps, ...(stored.caps || {}) } };
|
||||
// The environment sits between the built-in defaults and the file: it configures an instance
|
||||
// that was never set up in the UI, and it never overrides a choice someone made in one.
|
||||
const env = envPatch();
|
||||
cache = {
|
||||
...DEFAULTS,
|
||||
...env,
|
||||
...stored,
|
||||
caps: { ...DEFAULTS.caps, ...(stored.caps || {}) },
|
||||
// The per-provider maps merge rather than replace: a file that holds a key for one provider
|
||||
// must not wipe the endpoint the environment configured for another.
|
||||
models: { ...(env.models || {}), ...(stored.models || {}) },
|
||||
providerOptions: { ...(env.providerOptions || {}), ...(stored.providerOptions || {}) },
|
||||
};
|
||||
|
||||
// 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
|
||||
@@ -154,10 +212,32 @@ export function load() {
|
||||
if (cache.authMode !== 'profile') cache.authMode = 'instance';
|
||||
return cache;
|
||||
}
|
||||
/**
|
||||
* What actually goes to disk: the whole config, minus whatever the environment supplies.
|
||||
*
|
||||
* Writing those back would freeze this start-up's values into the file, and since the file
|
||||
* outranks the environment, the operator's next change to `COACH_MODEL` would be silently
|
||||
* ignored — a redeploy that looks like it did nothing. The token never reaches here at all: it
|
||||
* is not a field of the config (see envCredentialFor).
|
||||
*/
|
||||
function persisted(config) {
|
||||
const env = envPatch();
|
||||
const out = { ...config };
|
||||
for (const k of ['enabled', 'provider']) if (env[k] !== undefined && out[k] === env[k]) delete out[k];
|
||||
for (const k of ['models', 'providerOptions']) {
|
||||
if (!env[k]) continue;
|
||||
const merged = { ...(out[k] || {}) };
|
||||
for (const p of Object.keys(env[k])) {
|
||||
if (JSON.stringify(merged[p]) === JSON.stringify(env[k][p])) delete merged[p];
|
||||
}
|
||||
out[k] = merged;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
export function save(patch) {
|
||||
const next = { ...load(), ...patch };
|
||||
cache = next;
|
||||
atomicWrite(FILE, JSON.stringify(next, null, 2), 0o600);
|
||||
atomicWrite(FILE, JSON.stringify(persisted(next), null, 2), 0o600);
|
||||
return next;
|
||||
}
|
||||
// Test seam: forget the in-memory copy so the next load() re-reads from disk.
|
||||
@@ -241,6 +321,12 @@ export function credentialFor(uid) {
|
||||
const rec = authFor(cfg);
|
||||
const auth = rec && rec.data ? decrypt(rec.data) : null;
|
||||
if (!auth || !auth.token) {
|
||||
// Nothing was ever filed for this provider, so the environment may be carrying the key.
|
||||
// Deliberately only in that case: a key that WAS filed and fails to decrypt stays a failure,
|
||||
// because quietly spending a different credential would hide a broken file behind a key
|
||||
// nobody knows is being used.
|
||||
const fromEnv = rec ? null : envCredentialFor(cfg.provider);
|
||||
if (fromEnv) return { ok: true, auth: { token: fromEnv.token }, type: 'apikey', account: null, mode: 'instance', fromEnv: true };
|
||||
// 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' };
|
||||
@@ -302,7 +388,12 @@ export function isConnected() {
|
||||
if (cfg.provider === 'fixture') return true;
|
||||
if (cfg.authMode === 'profile') return true;
|
||||
const rec = authFor(cfg);
|
||||
if (!rec) return !!providerMeta(cfg).keyOptional && !!baseUrlFor(cfg.provider, cfg);
|
||||
if (!rec) {
|
||||
// A key in the environment counts exactly like a pasted one for "can this instance reach a
|
||||
// model"; without this the Coach would report itself unconfigured while holding a key.
|
||||
if (envCredentialFor(cfg.provider)) return true;
|
||||
return !!providerMeta(cfg).keyOptional && !!baseUrlFor(cfg.provider, cfg);
|
||||
}
|
||||
return !!decrypt(rec.data);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/* An instance configured entirely from its environment.
|
||||
*
|
||||
* A container should be able to start with its provider already in place — endpoint, model, key —
|
||||
* with nobody opening an admin screen. What is asserted here is that the environment configures
|
||||
* the Coach, that a pasted key still wins over it, and that the key never lands in the file the
|
||||
* docs tell people to back up.
|
||||
*/
|
||||
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';
|
||||
|
||||
tempData();
|
||||
process.env.COACH_PROVIDER = 'compatible';
|
||||
process.env.COACH_BASE_URL = 'https://ai.example.com';
|
||||
process.env.COACH_MODEL = 'vendor/model-1';
|
||||
process.env.COACH_API_KEY = 'sk-from-the-environment';
|
||||
|
||||
const cfg = await import('../coach/config.js');
|
||||
const { baseUrlFor } = await import('../coach/core/providers.js');
|
||||
|
||||
const coachFile = () => path.join(process.env.DATA_DIR, 'coach.json');
|
||||
const onDisk = () => (fs.existsSync(coachFile()) ? fs.readFileSync(coachFile(), 'utf8') : '');
|
||||
|
||||
test('the environment alone configures the provider, the endpoint, the model and the key', () => {
|
||||
assert.equal(cfg.isEnabled(), true, 'naming a provider is the configuration');
|
||||
assert.equal(cfg.isConnected(), true);
|
||||
const c = cfg.load();
|
||||
assert.equal(c.provider, 'compatible');
|
||||
assert.equal(cfg.modelFor(c), 'vendor/model-1');
|
||||
assert.equal(baseUrlFor('compatible', c), 'https://ai.example.com');
|
||||
|
||||
const cred = cfg.credentialFor('u1');
|
||||
assert.equal(cred.ok, true);
|
||||
assert.equal(cred.auth.token, 'sk-from-the-environment');
|
||||
assert.equal(cred.fromEnv, true, 'a caller can tell a key it did not file');
|
||||
});
|
||||
|
||||
test('a credential pasted in the app still wins over the environment one', () => {
|
||||
cfg.saveAuth('compatible', { type: 'apikey', account: 'admin', data: cfg.encrypt({ token: 'sk-pasted' }) });
|
||||
const cred = cfg.credentialFor('u1');
|
||||
assert.equal(cred.auth.token, 'sk-pasted');
|
||||
assert.equal(cred.fromEnv, undefined);
|
||||
assert.equal(cfg.isConnected(), true);
|
||||
// …and once it is removed, the environment is what is left.
|
||||
cfg.saveAuth('compatible', null);
|
||||
assert.equal(cfg.credentialFor('u1').auth.token, 'sk-from-the-environment');
|
||||
});
|
||||
|
||||
test('the environment key is never written to the config file', () => {
|
||||
cfg.save({ caps: { perProfileDaily: 5, instanceDaily: 0 } });
|
||||
const written = onDisk();
|
||||
assert.ok(written.includes('perProfileDaily'), 'the patch itself is saved');
|
||||
assert.ok(!written.includes('sk-from-the-environment'), 'the key must not be in a file people back up');
|
||||
assert.ok(!written.includes('sk-pasted'), 'nor a pasted one in the clear — that is encrypted');
|
||||
assert.ok(!written.includes('COACH_API_KEY'));
|
||||
});
|
||||
|
||||
test('what the environment supplies is not frozen into the file', () => {
|
||||
// A saved config used to be written back whole, which would have pinned this start-up's values
|
||||
// into the file — and the file outranks the environment, so a later change to COACH_MODEL would
|
||||
// have been silently ignored.
|
||||
const written = JSON.parse(onDisk() || '{}');
|
||||
assert.equal(written.provider, undefined);
|
||||
assert.equal(written.enabled, undefined);
|
||||
const text = JSON.stringify(written);
|
||||
assert.ok(!text.includes('vendor/model-1'), 'the model the environment set is not pinned');
|
||||
assert.ok(!text.includes('ai.example.com'), 'nor the endpoint');
|
||||
});
|
||||
|
||||
test('the provider\'s own variable works too, and no provider at all turns nothing on', () => {
|
||||
delete process.env.COACH_API_KEY;
|
||||
process.env.OPENAI_COMPAT_API_KEY = 'sk-provider-variable';
|
||||
cfg.reset();
|
||||
assert.equal(cfg.credentialFor('u1').auth.token, 'sk-provider-variable');
|
||||
|
||||
delete process.env.COACH_PROVIDER;
|
||||
delete process.env.COACH_BASE_URL;
|
||||
delete process.env.COACH_MODEL;
|
||||
delete process.env.OPENAI_COMPAT_API_KEY;
|
||||
cfg.reset();
|
||||
// Back to the built-in default (the fixture), which is not a Coach anybody can use: the whole
|
||||
// point of naming a provider in the environment is that naming nothing leaves the feature off.
|
||||
assert.equal(cfg.load().provider, 'fixture');
|
||||
assert.equal(cfg.isEnabled(), false, 'no provider named, nothing turned on');
|
||||
assert.equal(cfg.isConnected(), false);
|
||||
});
|
||||
Reference in new issue
Block a user