mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-14 17:02:19 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2247540b4f |
+42
-12
@@ -161,7 +161,7 @@ interface ResolveAIOptionsArgs {
|
||||
nonInteractive: boolean; // --non-interactive (forces D3 fail-loud, no picker)
|
||||
}
|
||||
|
||||
interface ResolvedAIOptions {
|
||||
export interface ResolvedAIOptions {
|
||||
embedding_model?: string;
|
||||
embedding_dimensions?: number;
|
||||
expansion_model?: string;
|
||||
@@ -170,6 +170,41 @@ interface ResolvedAIOptions {
|
||||
noEmbedding?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed init's AI options from persisted config, falling back to the raw env
|
||||
* vars when loadConfig() returned null (#1058). On a cold install (no
|
||||
* config.json AND no DATABASE_URL) loadConfig short-circuits BEFORE its env
|
||||
* merge, so GBRAIN_EMBEDDING_MODEL / GBRAIN_EMBEDDING_DIMENSIONS /
|
||||
* GBRAIN_EXPANSION_MODEL / GBRAIN_CHAT_MODEL were silently ignored by init
|
||||
* and Tier-3 detection auto-picked by API key instead. Exported for unit
|
||||
* tests (env injectable).
|
||||
*/
|
||||
export function seedAIOptionsFromConfig(
|
||||
cfg: GBrainConfig | null,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ResolvedAIOptions {
|
||||
const envDims = env.GBRAIN_EMBEDDING_DIMENSIONS
|
||||
? parseInt(env.GBRAIN_EMBEDDING_DIMENSIONS, 10)
|
||||
: NaN;
|
||||
const seed = cfg ?? {
|
||||
embedding_disabled: undefined,
|
||||
embedding_model: env.GBRAIN_EMBEDDING_MODEL,
|
||||
embedding_dimensions: Number.isFinite(envDims) ? envDims : undefined,
|
||||
expansion_model: env.GBRAIN_EXPANSION_MODEL,
|
||||
chat_model: env.GBRAIN_CHAT_MODEL,
|
||||
};
|
||||
const out: ResolvedAIOptions = {};
|
||||
if (seed.embedding_disabled) {
|
||||
out.noEmbedding = true;
|
||||
} else if (seed.embedding_model) {
|
||||
out.embedding_model = seed.embedding_model;
|
||||
if (seed.embedding_dimensions) out.embedding_dimensions = seed.embedding_dimensions;
|
||||
}
|
||||
if (seed.expansion_model) out.expansion_model = seed.expansion_model;
|
||||
if (seed.chat_model) out.chat_model = seed.chat_model;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve AI provider options for `gbrain init`.
|
||||
*
|
||||
@@ -203,18 +238,13 @@ async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIO
|
||||
// user already opted into deferred mode.
|
||||
try {
|
||||
const { loadConfig } = await import('../core/config.ts');
|
||||
const cfg = loadConfig();
|
||||
if (cfg?.embedding_disabled) {
|
||||
out.noEmbedding = true;
|
||||
} else if (cfg?.embedding_model) {
|
||||
out.embedding_model = cfg.embedding_model;
|
||||
if (cfg.embedding_dimensions) out.embedding_dimensions = cfg.embedding_dimensions;
|
||||
}
|
||||
if (cfg?.expansion_model) out.expansion_model = cfg.expansion_model;
|
||||
if (cfg?.chat_model) out.chat_model = cfg.chat_model;
|
||||
// #1058: loadConfig() returns null on a cold install (no config.json AND
|
||||
// no DATABASE_URL) — before it ever reaches its env merge. The seed helper
|
||||
// falls back to the same GBRAIN_* env vars directly in that case.
|
||||
Object.assign(out, seedAIOptionsFromConfig(loadConfig()));
|
||||
} catch {
|
||||
// loadConfig throws when no brain configured — first-time install, fall
|
||||
// through to env detection.
|
||||
// loadConfig threw — treat as first-time install, fall through to env
|
||||
// detection.
|
||||
}
|
||||
|
||||
// --- Tier 1+2: explicit flags ---------------------------------------------
|
||||
|
||||
@@ -56,36 +56,6 @@ export const litellmProxy: Recipe = {
|
||||
cost_per_1m_output_usd: undefined,
|
||||
price_last_verified: '2026-06-14',
|
||||
},
|
||||
// LiteLLM normalizes Cohere / Voyage / Jina / etc. rerank backends to the
|
||||
// same wire shape gbrain's gateway.rerank() already speaks (the
|
||||
// ZeroEntropy/llama.cpp contract):
|
||||
// { model, query, documents, top_n } → { results: [{ index, relevance_score }] }
|
||||
// So any rerank model the user registers in their LiteLLM config is
|
||||
// reachable via `gbrain config set search.reranker.model litellm:<model>`
|
||||
// with no request/response adapter — same as embeddings ride the proxy.
|
||||
reranker: {
|
||||
models: [], // user-provided; whatever rerank models the proxy serves
|
||||
// No canonical default — the proxy defines its own model ids. The user
|
||||
// sets search.reranker.model explicitly (mirrors the embedding
|
||||
// touchpoint's user_provided_models contract).
|
||||
default_model: '',
|
||||
// The proxied backend bills (Cohere/Voyage/…); pricing-unknown is the
|
||||
// honest state — same stance as this recipe's embedding/chat
|
||||
// touchpoints and budget-tracker's deliberate litellm exclusion from
|
||||
// the free-provider sets.
|
||||
cost_per_1m_tokens_usd: undefined,
|
||||
price_last_verified: '2026-06-27',
|
||||
max_payload_bytes: 5_000_000,
|
||||
// LEAF path only (matches llama-server-reranker's convention). LiteLLM
|
||||
// serves both `/rerank` and `/v1/rerank`, and LITELLM_BASE_URL may be
|
||||
// set with or without the `/v1` suffix (the setup_hint allows both), so
|
||||
// the leaf form yields a valid route either way:
|
||||
// http://localhost:4000 + /rerank → /rerank ✓
|
||||
// http://localhost:4000/v1 + /rerank → /v1/rerank ✓
|
||||
// Pinning '/v1/rerank' here would double to /v1/v1/rerank → 404 on
|
||||
// /v1-suffixed bases.
|
||||
path: '/rerank',
|
||||
},
|
||||
},
|
||||
setup_hint: 'Run LiteLLM (https://docs.litellm.ai) in front of any provider; set LITELLM_BASE_URL (include the /v1 suffix if your proxy serves the OpenAI route there, e.g. http://localhost:4000/v1) + pass --embedding-model litellm:<model> and --embedding-dimensions <N>. For rerank: register a rerank model in LiteLLM and set search.reranker.model litellm:<model-name>.',
|
||||
setup_hint: 'Run LiteLLM (https://docs.litellm.ai) in front of any provider; set LITELLM_BASE_URL (include the /v1 suffix if your proxy serves the OpenAI route there, e.g. http://localhost:4000/v1) + pass --embedding-model litellm:<model> and --embedding-dimensions <N>.',
|
||||
};
|
||||
|
||||
+19
-3
@@ -332,6 +332,15 @@ export interface OperationContext {
|
||||
* remote/untrusted (defense in depth in case the type is bypassed via cast).
|
||||
*/
|
||||
remote: boolean;
|
||||
/**
|
||||
* Transport marker for auth-less remote surfaces (#1061). The stdio MCP
|
||||
* dispatch sets 'stdio' — it is deliberately `remote: true` (agent-facing,
|
||||
* untrusted) but has no per-token auth (local pipe), so identity ops like
|
||||
* whoami need a way to distinguish "known auth-less transport" from "a
|
||||
* transport bug forgot to thread ctx.auth". Trust decisions MUST NOT key
|
||||
* off this field — only `ctx.remote === false` grants trust.
|
||||
*/
|
||||
transport?: 'stdio';
|
||||
/**
|
||||
* Subagent runtime context (v0.16+). Set by the subagent tool dispatcher when
|
||||
* dispatching an op as a tool call from an LLM loop. Used to enforce per-op
|
||||
@@ -3713,9 +3722,10 @@ const whoami: Operation = {
|
||||
'Introspect the calling identity. Returns one of three transport shapes: ' +
|
||||
'{transport: "oauth", client_id, client_name, scopes, expires_at}, ' +
|
||||
'{transport: "legacy", token_name, scopes, expires_at: null}, or ' +
|
||||
'{transport: "local", scopes: []}. Throws unknown_transport when the ' +
|
||||
'context is ambiguous (remote=true without auth) — fail-closed posture ' +
|
||||
'mirroring the v0.26.9 trust-boundary contract.',
|
||||
'{transport: "local", scopes: []}, or {transport: "stdio", scopes: []} ' +
|
||||
'for the auth-less stdio MCP pipe. Throws unknown_transport when the ' +
|
||||
'context is ambiguous (remote=true without auth and no transport marker) ' +
|
||||
'— fail-closed posture mirroring the v0.26.9 trust-boundary contract.',
|
||||
params: {},
|
||||
scope: 'read',
|
||||
handler: async (ctx) => {
|
||||
@@ -3727,6 +3737,12 @@ const whoami: Operation = {
|
||||
if (ctx.remote === false) {
|
||||
return { transport: 'local', scopes: [] };
|
||||
}
|
||||
// #1061: stdio MCP is remote/untrusted by design but has no per-token
|
||||
// auth (local pipe) — a known transport, not a bug. Report it instead of
|
||||
// throwing. Empty scopes: nothing here may be used to gate anything.
|
||||
if (!ctx.auth && ctx.transport === 'stdio') {
|
||||
return { transport: 'stdio', scopes: [] };
|
||||
}
|
||||
if (!ctx.auth) {
|
||||
throw new OperationError(
|
||||
'unknown_transport',
|
||||
|
||||
@@ -32,6 +32,12 @@ export interface DispatchOpts {
|
||||
remote?: boolean;
|
||||
/** Override the default stderr logger (e.g. CLI uses console.* directly). */
|
||||
logger?: OperationContext['logger'];
|
||||
/**
|
||||
* #1061: transport marker for auth-less remote surfaces. The stdio MCP
|
||||
* server passes 'stdio' so identity ops (whoami) can report the transport
|
||||
* instead of throwing unknown_transport. Never used for trust decisions.
|
||||
*/
|
||||
transport?: OperationContext['transport'];
|
||||
/**
|
||||
* v0.28: per-token allow-list for the takes.holder field. Threaded by
|
||||
* the HTTP/stdio transport from `access_tokens.permissions.takes_holders`.
|
||||
@@ -203,6 +209,7 @@ export function buildOperationContext(
|
||||
logger: opts.logger || stderrLogger,
|
||||
dryRun: !!params.dry_run,
|
||||
remote: opts.remote ?? true,
|
||||
transport: opts.transport,
|
||||
takesHoldersAllowList: opts.takesHoldersAllowList,
|
||||
// v0.34 D4: sourceId is REQUIRED at the type level. Auto-fill 'default'
|
||||
// for single-source brains and any caller who didn't resolve a sourceId.
|
||||
|
||||
@@ -42,6 +42,10 @@ export async function startMcpServer(engine: BrainEngine) {
|
||||
// `gbrain call <op>` (sets remote=false in src/cli.ts).
|
||||
return dispatchToolCall(engine, name, params, {
|
||||
remote: true,
|
||||
// #1061: mark the transport so whoami can report {transport: 'stdio'}
|
||||
// instead of throwing unknown_transport. Trust posture unchanged —
|
||||
// stdio stays remote/untrusted.
|
||||
transport: 'stdio',
|
||||
takesHoldersAllowList: ['world'],
|
||||
// v0.31: source defaults to 'default' for stdio (no per-token scope).
|
||||
// Operators who want a different source on stdio MCP should set
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* litellm-proxy reranker touchpoint smoke.
|
||||
*
|
||||
* Sibling of recipe-llama-server-reranker.test.ts. Pins the reranker
|
||||
* touchpoint on the LiteLLM proxy recipe so:
|
||||
* - the touchpoint exists with the LEAF '/rerank' path (LiteLLM serves both
|
||||
* /rerank and /v1/rerank, so the leaf form is valid whether or not the
|
||||
* user's LITELLM_BASE_URL carries the /v1 suffix the setup_hint allows)
|
||||
* - a /v1-suffixed base URL does NOT produce /v1/v1/rerank (the original
|
||||
* community PR pinned '/v1/rerank' which 404s on /v1-suffixed bases)
|
||||
* - models: [] (user-provided; proxy defines the model ids)
|
||||
* - pricing stays undefined (proxy can front a paid provider — same honest
|
||||
* pricing-unknown stance as the embedding/chat touchpoints)
|
||||
*
|
||||
* The gateway.rerank() URL tests drive the real URL builder via the stubbed
|
||||
* transport (same seam as test/ai/rerank.test.ts).
|
||||
*/
|
||||
|
||||
import { describe, expect, test, afterEach } from 'bun:test';
|
||||
import { getRecipe } from '../../src/core/ai/recipes/index.ts';
|
||||
import {
|
||||
configureGateway,
|
||||
resetGateway,
|
||||
rerank,
|
||||
__setRerankTransportForTests,
|
||||
} from '../../src/core/ai/gateway.ts';
|
||||
|
||||
afterEach(() => {
|
||||
__setRerankTransportForTests(null);
|
||||
resetGateway();
|
||||
});
|
||||
|
||||
describe('recipe: litellm reranker touchpoint', () => {
|
||||
test('declares reranker touchpoint with leaf /rerank path', () => {
|
||||
const r = getRecipe('litellm')!;
|
||||
const tp = r.touchpoints.reranker;
|
||||
expect(tp).toBeDefined();
|
||||
expect(tp!.path).toBe('/rerank');
|
||||
expect(tp!.max_payload_bytes).toBe(5_000_000);
|
||||
});
|
||||
|
||||
test('reranker touchpoint uses empty models[] for user-provided model ids', () => {
|
||||
const r = getRecipe('litellm')!;
|
||||
expect(r.touchpoints.reranker!.models).toEqual([]);
|
||||
});
|
||||
|
||||
test('pricing stays undefined — proxy can front a paid provider', () => {
|
||||
const r = getRecipe('litellm')!;
|
||||
expect(r.touchpoints.reranker!.cost_per_1m_tokens_usd).toBeUndefined();
|
||||
});
|
||||
|
||||
test('setup_hint keeps the /v1-suffix guidance AND mentions rerank', () => {
|
||||
const r = getRecipe('litellm')!;
|
||||
expect(r.setup_hint).toMatch(/\/v1 suffix/);
|
||||
expect(r.setup_hint).toMatch(/search\.reranker\.model litellm:/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gateway.rerank() URL via litellm recipe', () => {
|
||||
async function capturedRerankUrl(baseUrl?: string): Promise<string> {
|
||||
configureGateway({
|
||||
reranker_model: 'litellm:my-reranker',
|
||||
env: {},
|
||||
...(baseUrl ? { base_urls: { litellm: baseUrl } } : {}),
|
||||
});
|
||||
let capturedUrl = '';
|
||||
__setRerankTransportForTests(async (url) => {
|
||||
capturedUrl = url;
|
||||
return new Response(
|
||||
JSON.stringify({ results: [{ index: 0, relevance_score: 0.9 }] }),
|
||||
{ status: 200, headers: { 'content-type': 'application/json' } },
|
||||
);
|
||||
});
|
||||
await rerank({ query: 'q', documents: ['d'] });
|
||||
return capturedUrl;
|
||||
}
|
||||
|
||||
test('default base (no /v1 suffix) → /rerank', async () => {
|
||||
const url = await capturedRerankUrl();
|
||||
expect(url).toBe('http://localhost:4000/rerank');
|
||||
});
|
||||
|
||||
test('/v1-suffixed base → /v1/rerank, NOT /v1/v1/rerank', async () => {
|
||||
const url = await capturedRerankUrl('http://localhost:4000/v1');
|
||||
expect(url).toBe('http://localhost:4000/v1/rerank');
|
||||
expect(url).not.toContain('/v1/v1/');
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@
|
||||
*/
|
||||
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { groupReadyByProvider, findEnvKeyTypos } from '../src/commands/init.ts';
|
||||
import { groupReadyByProvider, findEnvKeyTypos, seedAIOptionsFromConfig } from '../src/commands/init.ts';
|
||||
|
||||
describe('groupReadyByProvider — embedding touchpoint', () => {
|
||||
test('OPENAI_API_KEY alone → openai is ready', async () => {
|
||||
@@ -149,3 +149,47 @@ describe('findEnvKeyTypos', () => {
|
||||
expect(got.find(t => t.userSet === 'COMPLETELY_UNRELATED_KEY')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('seedAIOptionsFromConfig — #1058 cold-install env fallback', () => {
|
||||
test('null config (no config.json, no DATABASE_URL) falls back to GBRAIN_* env vars', () => {
|
||||
const got = seedAIOptionsFromConfig(null, {
|
||||
GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-3-large',
|
||||
GBRAIN_EMBEDDING_DIMENSIONS: '1024',
|
||||
GBRAIN_EXPANSION_MODEL: 'openai:gpt-5-mini',
|
||||
GBRAIN_CHAT_MODEL: 'anthropic:claude-sonnet-4-6',
|
||||
});
|
||||
expect(got.embedding_model).toBe('voyage:voyage-3-large');
|
||||
expect(got.embedding_dimensions).toBe(1024);
|
||||
expect(got.expansion_model).toBe('openai:gpt-5-mini');
|
||||
expect(got.chat_model).toBe('anthropic:claude-sonnet-4-6');
|
||||
});
|
||||
|
||||
test('null config + no env vars → empty seed (Tier-3 detection takes over)', () => {
|
||||
const got = seedAIOptionsFromConfig(null, {});
|
||||
expect(got).toEqual({});
|
||||
});
|
||||
|
||||
test('persisted config wins (loadConfig already merged env when non-null)', () => {
|
||||
const got = seedAIOptionsFromConfig(
|
||||
{ engine: 'pglite', embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 } as any,
|
||||
{ GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-3-large' },
|
||||
);
|
||||
expect(got.embedding_model).toBe('openai:text-embedding-3-small');
|
||||
expect(got.embedding_dimensions).toBe(1536);
|
||||
});
|
||||
|
||||
test('embedding_disabled sentinel honored on re-init', () => {
|
||||
const got = seedAIOptionsFromConfig({ engine: 'pglite', embedding_disabled: true } as any, {});
|
||||
expect(got.noEmbedding).toBe(true);
|
||||
expect(got.embedding_model).toBeUndefined();
|
||||
});
|
||||
|
||||
test('non-numeric GBRAIN_EMBEDDING_DIMENSIONS ignored, model still seeds', () => {
|
||||
const got = seedAIOptionsFromConfig(null, {
|
||||
GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-3-large',
|
||||
GBRAIN_EMBEDDING_DIMENSIONS: 'not-a-number',
|
||||
});
|
||||
expect(got.embedding_model).toBe('voyage:voyage-3-large');
|
||||
expect(got.embedding_dimensions).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -94,6 +94,35 @@ describe('whoami op contract', () => {
|
||||
expect(result.expires_at).toBeNull();
|
||||
});
|
||||
|
||||
// #1061: stdio MCP is remote/untrusted by design but has no per-token auth
|
||||
// (local pipe). The stdio dispatch marks ctx.transport='stdio'; whoami
|
||||
// reports it instead of throwing unknown_transport.
|
||||
test('stdio transport (remote=true, no auth, transport marker) reports stdio', async () => {
|
||||
const result = (await whoami.handler(
|
||||
ctxWith({ remote: true, auth: undefined, transport: 'stdio' }),
|
||||
{},
|
||||
)) as any;
|
||||
expect(result.transport).toBe('stdio');
|
||||
expect(result.scopes).toEqual([]);
|
||||
});
|
||||
|
||||
test('stdio marker does not mask real auth (auth still wins)', async () => {
|
||||
const result = (await whoami.handler(
|
||||
ctxWith({
|
||||
remote: true,
|
||||
transport: 'stdio',
|
||||
auth: {
|
||||
token: 'gbrain_at_xxx',
|
||||
clientId: 'gbrain_cl_abc',
|
||||
scopes: ['read'],
|
||||
expiresAt: 1,
|
||||
} as AuthInfo,
|
||||
}),
|
||||
{},
|
||||
)) as any;
|
||||
expect(result.transport).toBe('oauth');
|
||||
});
|
||||
|
||||
// Q3: ambiguous transport — fail-closed. The footgun this guards against
|
||||
// is a future transport that lands without threading auth, where a buggy
|
||||
// caller might trust whoami's output to gate sensitive ops.
|
||||
|
||||
Reference in New Issue
Block a user