mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 18:02:30 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb1812cbc5 |
@@ -223,16 +223,14 @@ export GBRAIN_REMOTE_CLIENT_ID=<Alice's client_id>
|
||||
export GBRAIN_REMOTE_CLIENT_SECRET=<Alice's client_secret>
|
||||
export GBRAIN_REMOTE_MCP_URL=https://brain.acme-co.com/mcp
|
||||
|
||||
gbrain search "performance review"
|
||||
gbrain search "performance review" --remote
|
||||
```
|
||||
|
||||
(On a thin-client install every shared op routes through the remote MCP server automatically — no flag needed. The env vars select whose credentials the call uses.)
|
||||
|
||||
Alice should see results only from `customers` and `shared`. The performance-review notes live in `internal`, which she's not scoped to read. She shouldn't see them.
|
||||
|
||||
```bash
|
||||
# Terminal 2, as Bob (export his credentials similarly)
|
||||
gbrain search "performance review"
|
||||
gbrain search "performance review" --remote
|
||||
```
|
||||
|
||||
Bob should see the performance-review notes from `internal`, plus anything related from `shared`. He shouldn't see anything that lives only in `customers`.
|
||||
@@ -516,7 +514,7 @@ The first sync embeds every page, which takes time. Check `gbrain sources status
|
||||
|
||||
### "I see a page I shouldn't see"
|
||||
|
||||
This shouldn't happen, but if you suspect it, run `gbrain search <query> --json` as the constrained client (thin-client install, with the client's `GBRAIN_REMOTE_*` env exported) and inspect the `source_id` field on every returned result. Every row should be in the client's `--federated-read` set. If one isn't, file an issue with the exact slug and source IDs.
|
||||
This shouldn't happen, but if you suspect it, run `gbrain search <query> --remote --json` as the constrained client and inspect the `source_id` field on every returned result. Every row should be in the client's `--federated-read` set. If one isn't, file an issue with the exact slug and source IDs.
|
||||
|
||||
### "The synthesized answer is wrong"
|
||||
|
||||
|
||||
+5
-84
@@ -464,11 +464,7 @@ async function main() {
|
||||
// routed path. Date → ISO string; bigint → string (postgres.js shape);
|
||||
// Buffer → object. Microsecond-cost; eliminates a whole drift bug class.
|
||||
const result = JSON.parse(JSON.stringify(rawResult, bigintToStringReplacer));
|
||||
// #380 pass-through: `--json` (undeclared on most ops, promised by docs)
|
||||
// emits the raw op result instead of the human formatter.
|
||||
const output = params.json === true
|
||||
? JSON.stringify(result, null, 2) + '\n'
|
||||
: formatResult(op.name, result);
|
||||
const output = formatResult(op.name, result);
|
||||
if (output) process.stdout.write(output);
|
||||
} catch (e: unknown) {
|
||||
// v0.42.20.0 (codex D4): on error, set exitCode + return so the `finally`
|
||||
@@ -551,10 +547,7 @@ async function runThinClientRouted(
|
||||
signal: sigintController.signal,
|
||||
});
|
||||
const result = unpackToolResult(raw);
|
||||
// #380: same --json seam as the local-engine path (renderer parity).
|
||||
const output = params.json === true
|
||||
? JSON.stringify(result, null, 2) + '\n'
|
||||
: formatResult(op.name, result);
|
||||
const output = formatResult(op.name, result);
|
||||
if (output) process.stdout.write(output);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof RemoteMcpError) {
|
||||
@@ -764,28 +757,10 @@ export function resolveQueryImage(
|
||||
return { path: imagePath, base64, mime };
|
||||
}
|
||||
|
||||
/**
|
||||
* #380: undeclared flags that are honored DOWNSTREAM of parseOpArgs and must
|
||||
* keep passing through when unknown flags become hard errors:
|
||||
* - source → makeContext's resolveSourceId (the --source axis)
|
||||
* - brain → the mount/brain routing axis (docs promise the flag)
|
||||
* - dry_run → makeContext's ctx.dryRun (ops without a declared dry_run)
|
||||
* - json → raw-JSON output seam (local + thin-client paths)
|
||||
*/
|
||||
const PASSTHROUGH_VALUE_FLAGS = new Set(['source', 'brain']);
|
||||
const PASSTHROUGH_BOOL_FLAGS = new Set(['dry_run', 'json']);
|
||||
|
||||
export function parseOpArgs(op: Operation, args: string[]): Record<string, unknown> {
|
||||
const params: Record<string, unknown> = {};
|
||||
const positional = op.cliHints?.positional || [];
|
||||
let posIdx = 0;
|
||||
const cliName = op.cliHints?.name || op.name;
|
||||
const MAX_STDIN = 5_000_000; // 5MB cap, shared by stdin and --file
|
||||
// #380: `--file <path>` fills the op's declared stdin param (put's `content`)
|
||||
// from a file. Driven by cliHints.stdin — no per-op hard-coding — and
|
||||
// disabled when the op declares a real `file` param of its own.
|
||||
const fileParam = op.cliHints?.stdin && !op.params.file ? op.cliHints.stdin : undefined;
|
||||
let filePath: string | undefined;
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
@@ -799,42 +774,12 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
}
|
||||
}
|
||||
const key = arg.slice(2).replace(/-/g, '_');
|
||||
if (fileParam && key === 'file') {
|
||||
if (i + 1 >= args.length) {
|
||||
console.error(`Error: ${arg} requires a value.`);
|
||||
process.exit(1);
|
||||
}
|
||||
filePath = args[++i];
|
||||
continue;
|
||||
}
|
||||
const paramDef = op.params[key];
|
||||
if (!paramDef) {
|
||||
if (PASSTHROUGH_BOOL_FLAGS.has(key)) {
|
||||
params[key] = true;
|
||||
continue;
|
||||
}
|
||||
if (PASSTHROUGH_VALUE_FLAGS.has(key)) {
|
||||
if (i + 1 >= args.length) {
|
||||
console.error(`Error: ${arg} requires a value.`);
|
||||
process.exit(1);
|
||||
}
|
||||
params[key] = args[++i];
|
||||
continue;
|
||||
}
|
||||
// #380: unknown flags were silently swallowed into params, so typos
|
||||
// like `put --file` created empty pages instead of erroring.
|
||||
console.error(`Unknown option for gbrain ${cliName}: ${arg}`);
|
||||
console.error(`Run 'gbrain ${cliName} --help' for valid flags.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (paramDef.type === 'boolean') {
|
||||
if (paramDef?.type === 'boolean') {
|
||||
params[key] = true;
|
||||
} else if (i + 1 < args.length) {
|
||||
params[key] = args[++i];
|
||||
if (paramDef.type === 'number') params[key] = Number(params[key]);
|
||||
} else {
|
||||
console.error(`Error: ${arg} requires a value.`);
|
||||
process.exit(1);
|
||||
if (paramDef?.type === 'number') params[key] = Number(params[key]);
|
||||
}
|
||||
} else if (posIdx < positional.length) {
|
||||
const key = positional[posIdx++];
|
||||
@@ -843,30 +788,10 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
}
|
||||
}
|
||||
|
||||
// #380: resolve --file AFTER the loop so --file/--content conflicts are
|
||||
// caught in either order.
|
||||
if (filePath !== undefined && fileParam) {
|
||||
if (params[fileParam] !== undefined) {
|
||||
console.error(`Error: use only one of --file, --${fileParam}, or stdin for gbrain ${cliName}.`);
|
||||
process.exit(1);
|
||||
}
|
||||
let fileContent: string;
|
||||
try {
|
||||
fileContent = readFileSync(filePath, 'utf-8');
|
||||
} catch (e) {
|
||||
console.error(`Error: cannot read --file ${filePath}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (Buffer.byteLength(fileContent, 'utf-8') > MAX_STDIN) {
|
||||
console.error(`Error: file content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
|
||||
process.exit(1);
|
||||
}
|
||||
params[fileParam] = fileContent;
|
||||
}
|
||||
|
||||
// Read stdin for content params
|
||||
if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
|
||||
const stdinContent = readFileSync(0, 'utf-8');
|
||||
const MAX_STDIN = 5_000_000; // 5MB
|
||||
if (Buffer.byteLength(stdinContent, 'utf-8') > MAX_STDIN) {
|
||||
console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
|
||||
process.exit(1);
|
||||
@@ -2328,10 +2253,6 @@ export function printOpHelp(op: Operation, invokedName?: string) {
|
||||
const prefix = isPos ? ` <${key}>` : ` --${key.replace(/_/g, '-')}`;
|
||||
console.log(`${prefix.padEnd(28)} ${def.description || ''}${req}`);
|
||||
}
|
||||
// #380: ops that read stdin also accept --file <path> (parseOpArgs).
|
||||
if (op.cliHints?.stdin && !op.params.file) {
|
||||
console.log(`${' --file <path>'.padEnd(28)} Read ${op.cliHints.stdin} from a file (alternative to --${op.cliHints.stdin} or stdin)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,100 @@
|
||||
import type { Recipe } from '../types.ts';
|
||||
|
||||
/**
|
||||
* MiniMax (海螺AI). OpenAI-compatible /embeddings endpoint at
|
||||
* api.minimax.chat. The flagship embedding model is `embo-01` (1536 dims).
|
||||
* MiniMax transport shim (#1977). MiniMax's `/v1/embeddings` endpoint is NOT
|
||||
* OpenAI-compatible at the wire level despite the recipe's
|
||||
* `implementation: 'openai-compatible'`:
|
||||
* - Request: requires `texts` (the AI SDK sends `input`) plus an optional
|
||||
* `type: 'db' | 'query'` asymmetric-retrieval field, and rejects OpenAI's
|
||||
* `encoding_format`.
|
||||
* - Response: returns `{vectors: number[][], total_tokens}` where the AI
|
||||
* SDK's Zod schema expects `{data: [{embedding, index}], usage}`.
|
||||
*
|
||||
* Chat (`/chat/completions`) IS OpenAI-compatible, and this same fetch is
|
||||
* applied to every openai-compatible touchpoint by `applyOpenAICompatConfig`,
|
||||
* so everything outside the embeddings path passes through untouched — and
|
||||
* the response rewrite parses via `resp.clone()` only (never consume the
|
||||
* body of a response we return as-is; the DeepSeek shim rule). Fail-open:
|
||||
* any rewrite error returns the original request/response.
|
||||
*
|
||||
* @internal exported for tests.
|
||||
*/
|
||||
// Cast through `unknown` because Bun's `typeof fetch` carries a `preconnect`
|
||||
// member the arrow function does not implement (matches deepseek.ts).
|
||||
export const minimaxCompatFetch = (async (
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit,
|
||||
): Promise<Response> => {
|
||||
const url =
|
||||
typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
const isEmbeddings = url.includes('/embeddings');
|
||||
|
||||
// OUTBOUND (embeddings only): `input` → `texts`, default `type: 'db'`
|
||||
// (the recipe's documented symmetric default — the AI SDK adapter strips
|
||||
// the `type` threaded via providerOptions before it reaches the wire,
|
||||
// same class as #1400), and drop `encoding_format` (not a MiniMax param).
|
||||
if (isEmbeddings && init?.body && typeof init.body === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(init.body);
|
||||
if (
|
||||
parsed && typeof parsed === 'object' &&
|
||||
parsed.input !== undefined && parsed.texts === undefined
|
||||
) {
|
||||
parsed.texts = Array.isArray(parsed.input) ? parsed.input : [parsed.input];
|
||||
delete parsed.input;
|
||||
delete parsed.encoding_format;
|
||||
if (parsed.type === undefined) parsed.type = 'db';
|
||||
// Drop Content-Length so fetch recomputes from the new body.
|
||||
const headers = new Headers(init.headers ?? {});
|
||||
headers.delete('content-length');
|
||||
init = { ...init, body: JSON.stringify(parsed), headers };
|
||||
}
|
||||
} catch {
|
||||
// Body wasn't JSON — pass through untouched.
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(input as any, init as any);
|
||||
|
||||
// INBOUND (embeddings only): `{vectors: [[...]]}` → `{data: [{embedding}]}`.
|
||||
// Anything else (chat completions, MiniMax base_resp errors, non-JSON)
|
||||
// returns the ORIGINAL response with its body unread.
|
||||
if (!isEmbeddings || !res.ok) return res;
|
||||
const ctype = res.headers.get('content-type') ?? '';
|
||||
if (!ctype.toLowerCase().includes('application/json')) return res;
|
||||
try {
|
||||
const json = await res.clone().json();
|
||||
if (!json || typeof json !== 'object' || !Array.isArray(json.vectors)) return res;
|
||||
const totalTokens = typeof json.total_tokens === 'number' ? json.total_tokens : 0;
|
||||
const rewritten = {
|
||||
object: 'list',
|
||||
data: (json.vectors as number[][]).map((embedding, index) => ({
|
||||
object: 'embedding',
|
||||
embedding,
|
||||
index,
|
||||
})),
|
||||
model: typeof json.model === 'string' ? json.model : 'embo-01',
|
||||
usage: { prompt_tokens: totalTokens, total_tokens: totalTokens },
|
||||
};
|
||||
// Fresh header set: the body changed, so upstream content-length /
|
||||
// content-encoding would now be wrong.
|
||||
const headers = new Headers(res.headers);
|
||||
headers.delete('content-length');
|
||||
headers.delete('content-encoding');
|
||||
return new Response(JSON.stringify(rewritten), {
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
headers,
|
||||
});
|
||||
} catch {
|
||||
return res;
|
||||
}
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
/**
|
||||
* MiniMax (海螺AI). `/embeddings` endpoint at api.minimaxi.com (wire shape
|
||||
* normalized by `minimaxCompatFetch` above); OpenAI-compatible
|
||||
* `/chat/completions`. The flagship embedding model is `embo-01` (1536 dims).
|
||||
*
|
||||
* MiniMax's API takes an extra `type: 'db' | 'query'` field for asymmetric
|
||||
* retrieval. gbrain currently has no notion of "this is a document vs a
|
||||
@@ -38,7 +130,25 @@ export const minimax: Recipe = {
|
||||
// halving in the gateway catches token-limit errors at runtime.
|
||||
max_batch_tokens: 4096,
|
||||
},
|
||||
chat: {
|
||||
// Model list from MiniMax's /v1/models (#1977). Chat is genuinely
|
||||
// OpenAI-compatible — no wire rewrite needed (minimaxCompatFetch
|
||||
// passes non-embedding requests through untouched).
|
||||
models: [
|
||||
'MiniMax-M3',
|
||||
'MiniMax-M2.7',
|
||||
'MiniMax-M2.7-highspeed',
|
||||
'MiniMax-M2.5',
|
||||
'MiniMax-M2.5-highspeed',
|
||||
'MiniMax-M2.1',
|
||||
'MiniMax-M2.1-highspeed',
|
||||
'MiniMax-M2',
|
||||
],
|
||||
supports_tools: false,
|
||||
supports_subagent_loop: false,
|
||||
},
|
||||
},
|
||||
setup_hint:
|
||||
'Get an API key at https://www.minimaxi.com, then `export MINIMAX_API_KEY=...`',
|
||||
compat: { fetch: minimaxCompatFetch },
|
||||
};
|
||||
|
||||
@@ -769,7 +769,7 @@ const get_page: Operation = {
|
||||
|
||||
const put_page: Operation = {
|
||||
name: 'put_page',
|
||||
description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. On the CLI, `gbrain put SLUG --file PATH` reads content from a file (also `--content` or stdin). For provenance write-through and a binary-NUL guard, prefer `gbrain capture --file PATH --slug SLUG` (v0.39.3.0).',
|
||||
description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',
|
||||
params: {
|
||||
slug: { type: 'string', required: true, description: 'Page slug' },
|
||||
content: { type: 'string', required: true, description: 'Full markdown content with YAML frontmatter' },
|
||||
@@ -1384,10 +1384,7 @@ const list_pages: Operation = {
|
||||
params: {
|
||||
type: { type: 'string', description: 'Filter by page type' },
|
||||
tag: { type: 'string', description: 'Filter by tag' },
|
||||
limit: { type: 'number', description: 'Max results (default 50, capped at 100 — use offset to paginate beyond)' },
|
||||
// #2876: the 100-row cap was silent and there was no way past it even
|
||||
// though both engines already support OFFSET on listPages.
|
||||
offset: { type: 'number', description: 'Skip first N results (pagination; pair with limit)' },
|
||||
limit: { type: 'number', description: 'Max results (default 50)' },
|
||||
// v0.29 — surface filter that already exists on PageFilters.
|
||||
updated_after: {
|
||||
type: 'string',
|
||||
@@ -1418,10 +1415,6 @@ const list_pages: Operation = {
|
||||
type: p.type as any,
|
||||
tag: p.tag as string,
|
||||
limit: clampSearchLimit(p.limit as number | undefined, 50, 100),
|
||||
// #2876: thread pagination through (engines already honor offset).
|
||||
offset: Number.isFinite(p.offset as number) && (p.offset as number) > 0
|
||||
? Math.floor(p.offset as number)
|
||||
: undefined,
|
||||
includeDeleted: (p.include_deleted as boolean) === true,
|
||||
updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,
|
||||
sort,
|
||||
|
||||
@@ -6,10 +6,14 @@
|
||||
* - default auth: MINIMAX_API_KEY → "Bearer <key>"; missing → AIConfigError
|
||||
* - dimsProviderOptions threads `type: 'db'` for embo-01 (the asymmetric
|
||||
* retrieval field default) — pins the v1 indexing-only behavior
|
||||
* - #1977: chat touchpoint declared; minimaxCompatFetch rewrites the
|
||||
* embedding wire shape both directions, passes chat through with the
|
||||
* response body UNREAD (the consumed-body regression), fail-open.
|
||||
*/
|
||||
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { getRecipe } from '../../src/core/ai/recipes/index.ts';
|
||||
import { minimaxCompatFetch } from '../../src/core/ai/recipes/minimax.ts';
|
||||
import { defaultResolveAuth } from '../../src/core/ai/gateway.ts';
|
||||
import { dimsProviderOptions } from '../../src/core/ai/dims.ts';
|
||||
import { AIConfigError } from '../../src/core/ai/errors.ts';
|
||||
@@ -56,4 +60,106 @@ describe('recipe: minimax', () => {
|
||||
expect(dimsProviderOptions('openai-compatible', 'voyage-3-lite', 512)).toBeUndefined();
|
||||
expect(dimsProviderOptions('openai-compatible', 'nomic-embed-text', 768)).toBeUndefined();
|
||||
});
|
||||
|
||||
test('chat touchpoint declared (#1977) so assertTouchpoint permits gbrain think', () => {
|
||||
const r = getRecipe('minimax')!;
|
||||
expect(r.touchpoints.chat).toBeDefined();
|
||||
expect(r.touchpoints.chat!.models).toContain('MiniMax-M3');
|
||||
expect(r.touchpoints.chat!.supports_tools).toBe(false);
|
||||
expect(r.touchpoints.chat!.supports_subagent_loop).toBe(false);
|
||||
});
|
||||
|
||||
test('recipe ships minimaxCompatFetch via compat.fetch (no env-templated base URL)', () => {
|
||||
const r = getRecipe('minimax')!;
|
||||
expect(r.compat?.fetch).toBe(minimaxCompatFetch);
|
||||
// base_urls config override must keep working: no resolveOpenAICompatConfig.
|
||||
expect(r.resolveOpenAICompatConfig).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('minimaxCompatFetch (#1977)', () => {
|
||||
const realFetch = globalThis.fetch;
|
||||
afterEach(() => { globalThis.fetch = realFetch; });
|
||||
|
||||
function stubFetch(body: unknown, init?: { status?: number; contentType?: string }) {
|
||||
const calls: { url: string; init?: RequestInit }[] = [];
|
||||
globalThis.fetch = (async (input: any, i?: RequestInit) => {
|
||||
calls.push({ url: String(input), init: i });
|
||||
return new Response(typeof body === 'string' ? body : JSON.stringify(body), {
|
||||
status: init?.status ?? 200,
|
||||
headers: { 'content-type': init?.contentType ?? 'application/json' },
|
||||
});
|
||||
}) as unknown as typeof fetch;
|
||||
return calls;
|
||||
}
|
||||
|
||||
const EMBED_URL = 'https://api.minimaxi.com/v1/embeddings';
|
||||
const CHAT_URL = 'https://api.minimaxi.com/v1/chat/completions';
|
||||
|
||||
test('embedding request: input → texts, type:db injected, encoding_format dropped', async () => {
|
||||
const calls = stubFetch({ vectors: [[0.1, 0.2]] });
|
||||
await minimaxCompatFetch(EMBED_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'content-length': '99' },
|
||||
body: JSON.stringify({ model: 'embo-01', input: ['hello', 'world'], encoding_format: 'float' }),
|
||||
});
|
||||
const wire = JSON.parse(calls[0]!.init!.body as string);
|
||||
expect(wire.texts).toEqual(['hello', 'world']);
|
||||
expect(wire.input).toBeUndefined();
|
||||
expect(wire.encoding_format).toBeUndefined();
|
||||
expect(wire.type).toBe('db');
|
||||
expect(new Headers(calls[0]!.init!.headers).get('content-length')).toBeNull();
|
||||
});
|
||||
|
||||
test('embedding response: {vectors} rewritten to OpenAI {data:[{embedding}]}', async () => {
|
||||
stubFetch({ vectors: [[0.1, 0.2], [0.3, 0.4]], total_tokens: 7 });
|
||||
const res = await minimaxCompatFetch(EMBED_URL, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ model: 'embo-01', input: ['a', 'b'] }),
|
||||
});
|
||||
const json = await res.json();
|
||||
expect(json.data).toEqual([
|
||||
{ object: 'embedding', embedding: [0.1, 0.2], index: 0 },
|
||||
{ object: 'embedding', embedding: [0.3, 0.4], index: 1 },
|
||||
]);
|
||||
expect(json.usage).toEqual({ prompt_tokens: 7, total_tokens: 7 });
|
||||
});
|
||||
|
||||
test('chat completion passes through with body UNREAD (consumed-body regression)', async () => {
|
||||
stubFetch({ choices: [{ message: { role: 'assistant', content: 'hi' } }] });
|
||||
const res = await minimaxCompatFetch(CHAT_URL, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ model: 'MiniMax-M3', messages: [{ role: 'user', content: 'say hi' }] }),
|
||||
});
|
||||
expect(res.bodyUsed).toBe(false); // the broken PR #2882 wrapper consumed this
|
||||
const json = await res.json(); // must NOT throw "Body already used"
|
||||
expect(json.choices[0].message.content).toBe('hi');
|
||||
});
|
||||
|
||||
test('chat request body is never rewritten (messages untouched, no type injected)', async () => {
|
||||
const calls = stubFetch({ choices: [] });
|
||||
const body = JSON.stringify({ model: 'MiniMax-M3', messages: [{ role: 'user', content: 'x' }] });
|
||||
await minimaxCompatFetch(CHAT_URL, { method: 'POST', body });
|
||||
expect(calls[0]!.init!.body).toBe(body);
|
||||
});
|
||||
|
||||
test('embedding error response ({vectors:null, base_resp}) passes through re-readable', async () => {
|
||||
stubFetch({ vectors: null, base_resp: { status_code: 2013, status_msg: 'invalid params' } });
|
||||
const res = await minimaxCompatFetch(EMBED_URL, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ model: 'embo-01', input: ['a'] }),
|
||||
});
|
||||
expect(res.bodyUsed).toBe(false);
|
||||
const json = await res.json();
|
||||
expect(json.base_resp.status_code).toBe(2013);
|
||||
});
|
||||
|
||||
test('fail-open: non-JSON response body passes through untouched', async () => {
|
||||
stubFetch('not json', { contentType: 'application/json' });
|
||||
const res = await minimaxCompatFetch(EMBED_URL, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ model: 'embo-01', input: ['a'] }),
|
||||
});
|
||||
expect(await res.text()).toBe('not json');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,41 +1,8 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { parseOpArgs } from '../src/cli.ts';
|
||||
import { operationsByName } from '../src/core/operations.ts';
|
||||
|
||||
describe('parseOpArgs', () => {
|
||||
// #380: `gbrain put SLUG --file PATH` reads content from the file instead
|
||||
// of silently swallowing the flag and creating an empty page.
|
||||
test('put --file reads the stdin param (content) from a file', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'gbrain-put-file-'));
|
||||
try {
|
||||
const pagePath = join(dir, 'page.md');
|
||||
writeFileSync(pagePath, '# From file\n\nBody loaded from --file.\n');
|
||||
const params = parseOpArgs(operationsByName.put_page, ['concepts/from-file', '--file', pagePath]);
|
||||
expect(params.slug).toBe('concepts/from-file');
|
||||
expect(params.content).toBe('# From file\n\nBody loaded from --file.\n');
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// #380 regression guard: undeclared-but-honored flags must keep passing
|
||||
// through when unknown flags become hard errors (--source is read by
|
||||
// makeContext; --json by the output seam; --dry-run by ctx.dryRun).
|
||||
test('pass-through allowlist flags survive on ops that do not declare them', () => {
|
||||
const params = parseOpArgs(operationsByName.get_page, [
|
||||
'people/alice-example', '--source', 'wiki', '--json', '--dry-run',
|
||||
]);
|
||||
expect(params).toEqual({
|
||||
slug: 'people/alice-example',
|
||||
source: 'wiki',
|
||||
json: true,
|
||||
dry_run: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('--no-<boolean> maps to false without consuming the next flag', () => {
|
||||
const params = parseOpArgs(operationsByName.query, [
|
||||
'freshEmbedSourceScope code source',
|
||||
|
||||
+1
-71
@@ -1,5 +1,5 @@
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
|
||||
@@ -120,76 +120,6 @@ describe('CLI dispatch integration', () => {
|
||||
expect(exitCode).toBe(0);
|
||||
});
|
||||
|
||||
// #380 / PR #856: put --help documents the --file input path.
|
||||
test('put --help documents --file input', async () => {
|
||||
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'put', '--help'], {
|
||||
cwd: repoRoot,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
});
|
||||
const stdout = await new Response(proc.stdout).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stdout).toContain('Usage: gbrain put');
|
||||
expect(stdout).toContain('--file <path>');
|
||||
expect(exitCode).toBe(0);
|
||||
});
|
||||
|
||||
// #380: unknown flags on shared ops are a hard error (previously silently
|
||||
// swallowed into params — `put --file` created empty pages). parseOpArgs
|
||||
// runs BEFORE engine connect, so the error must fire without a brain.
|
||||
test('unknown shared-op flags fail before DB connection', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-unknown-flag-'));
|
||||
try {
|
||||
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'get', 'people/alice', '--bogus'], {
|
||||
cwd: repoRoot,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
env: isolatedEnv(home),
|
||||
});
|
||||
const stderr = await new Response(proc.stderr).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stderr).toContain('Unknown option for gbrain get: --bogus');
|
||||
expect(stderr).not.toContain('No brain configured');
|
||||
expect(exitCode).toBe(1);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('put rejects combining --file and --content', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-put-conflict-'));
|
||||
try {
|
||||
const pagePath = join(home, 'page.md');
|
||||
writeFileSync(pagePath, 'file body\n');
|
||||
const proc = Bun.spawn(
|
||||
['bun', 'run', 'src/cli.ts', 'put', 'a/b', '--content', 'inline', '--file', pagePath],
|
||||
{ cwd: repoRoot, stdout: 'pipe', stderr: 'pipe', env: isolatedEnv(home) },
|
||||
);
|
||||
const stderr = await new Response(proc.stderr).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stderr).toContain('use only one of --file, --content, or stdin');
|
||||
expect(exitCode).toBe(1);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('put --file with a missing path errors instead of writing an empty page', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-put-missing-file-'));
|
||||
try {
|
||||
const proc = Bun.spawn(
|
||||
['bun', 'run', 'src/cli.ts', 'put', 'a/b', '--file', join(home, 'nope.md')],
|
||||
{ cwd: repoRoot, stdout: 'pipe', stderr: 'pipe', env: isolatedEnv(home) },
|
||||
);
|
||||
const stderr = await new Response(proc.stderr).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stderr).toContain('cannot read --file');
|
||||
expect(exitCode).toBe(1);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('upgrade --help prints usage without running upgrade', async () => {
|
||||
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'upgrade', '--help'], {
|
||||
cwd: repoRoot,
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { operationsByName } from '../src/core/operations.ts';
|
||||
|
||||
/**
|
||||
* #2876: `gbrain list --limit` silently clamped at 100 with no pagination.
|
||||
* list_pages now declares `offset` (both engines already supported it on
|
||||
* PageFilters) and the limit description discloses the 100-row cap.
|
||||
*/
|
||||
describe('list_pages pagination (#2876)', () => {
|
||||
const listPagesOp = operationsByName.list_pages;
|
||||
|
||||
function makeCtx(captured: unknown[]) {
|
||||
return {
|
||||
engine: {
|
||||
listPages: async (filters: unknown) => {
|
||||
captured.push(filters);
|
||||
return [];
|
||||
},
|
||||
},
|
||||
config: { engine: 'pglite' },
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
dryRun: false,
|
||||
remote: false,
|
||||
sourceId: 'default',
|
||||
} as any;
|
||||
}
|
||||
|
||||
test('declares offset param and discloses the 100-row cap on limit', () => {
|
||||
expect(listPagesOp.params.offset).toBeDefined();
|
||||
expect(listPagesOp.params.offset.type).toBe('number');
|
||||
expect(listPagesOp.params.limit.description).toContain('100');
|
||||
});
|
||||
|
||||
test('threads offset through to engine.listPages', async () => {
|
||||
const captured: any[] = [];
|
||||
await listPagesOp.handler(makeCtx(captured), { limit: 10, offset: 30 });
|
||||
expect(captured[0].offset).toBe(30);
|
||||
expect(captured[0].limit).toBe(10);
|
||||
});
|
||||
|
||||
test('drops negative, non-finite, and zero offsets', async () => {
|
||||
const captured: any[] = [];
|
||||
const ctx = makeCtx(captured);
|
||||
await listPagesOp.handler(ctx, { offset: -5 });
|
||||
await listPagesOp.handler(ctx, { offset: Infinity });
|
||||
await listPagesOp.handler(ctx, { offset: 0 });
|
||||
for (const f of captured) expect(f.offset).toBeUndefined();
|
||||
});
|
||||
|
||||
test('floors fractional offsets', async () => {
|
||||
const captured: any[] = [];
|
||||
await listPagesOp.handler(makeCtx(captured), { offset: 7.9 });
|
||||
expect(captured[0].offset).toBe(7);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user