Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(large-pages): dispatch egress backstop, thin-client marker on both HTTP transports
garrytane59f3405e74d
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 8d031edf6c..8e803fa92c 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -27,7 +27,7 @@ import { STATUS_TOOL_NAME, statusModeOf, statusToolResult } from '../mcp/status-import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import { scopeDeniedError } from '../core/ops/op-fix.ts';import { resolveStrictParamsMode } from '../mcp/validate-params.ts';-import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest, type ResultRowsMode } from '../mcp/result-rows.ts';+import { GBRAIN_CLIENT_HEADER, isGbrainThinClient, resolveResultRowsMode, resultRowsForRequest, type ResultRowsMode } from '../mcp/result-rows.ts';import { buildToolDefs } from '../mcp/tool-defs.ts';import {filterOpsForSurface,@@ -57,6 +57,8 @@ interface McpRequestState {surfaceAllowedOps: ReadonlySet<string> | undefined;/** C1: search/query row shape for this request (thin-client header, else host `mcp.result_rows`). */resultRows: ResultRowsMode;+ /** Large pages: the same header marks gbrain's thin client, whose default get_page mode stays whole. Never authority. */+ thinClient: boolean;}export function mountMcp(app: Express, ctx: ServeHttpContext): void {@@ -161,7 +163,8 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {authInfo.effectiveSurface = surface;const surfaceAllowedOps: ReadonlySet<string> | undefined =surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));- const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows };+ const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));+ const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient };const server = createMcpRequestServer(ctx, state, writeback);await serveMcpRequest(server, req, res);});@@ -288,7 +291,7 @@ async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, request: CallToolRequest): Promise<ToolResult> {const { engine, broadcastEvent, logFullParams } = ctx;- const { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows } = state;+ const { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient } = state;const { name, arguments: params } = request.params;// A server that recovered from status-only mode answers clients still holding the status tool list (never listed).const statusMode = name === STATUS_TOOL_NAME ? statusModeOf(engine) : null;@@ -404,6 +407,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques// D2: a callable tool the advertised surface leaves out of tools/list (same rule as listMcpTools).isListed: async op => !!authInfo.surface || advertisedOps([op], surface, await resolveAdvertisedSurface(engine, ctx.config)).length > 0,resultRows,+ thinClient,// v0.31 follow-up fix: thread auth so the whoami op (and any// future scope-aware handlers) can introspect the caller. The// original D12/eE1 refactor moved dispatch into dispatchToolCalldiff --git a/src/core/egress-budget.ts b/src/core/egress-budget.tsindex 7d64184547..dffe33ee75 100644--- a/src/core/egress-budget.ts+++ b/src/core/egress-budget.ts@@ -15,6 +15,7 @@*/import type { BrainEngine } from './engine.ts';import type { GBrainConfig } from './config.ts';+import { opError, type OperationError } from './ops/contract.ts';export type EgressTransport = 'stdio' | 'http';@@ -71,3 +72,32 @@ export async function resultByteCap(caller: EgressCaller): Promise<number> {export function encodedFrameBytes(result: unknown): number {return Buffer.byteLength(JSON.stringify({ jsonrpc: '2.0', id: 0, result }), 'utf8') + FRAME_RESERVE_BYTES;}++/** The measured frame and the cap it broke, or null when `result` fits this connection. */+export async function frameOverCap(result: unknown, caller: EgressCaller): Promise<{ bytes: number; cap: number; transport: EgressTransport } | null> {+ const transport = egressTransport(caller);+ if (transport === null) return null;+ const cap = await resultByteCap(caller);+ const bytes = encodedFrameBytes(result);+ return bytes > cap ? { bytes, cap, transport } : null;+}++/**+ * The dispatcher's backstop refusal: a read whose final frame is over the+ * connection's cap. Nothing is cut; the caller asks again for less. Reads+ * only: a write's result is its receipt and is never replaced.+ */+export function resultTooLargeError(op: string, params: Record<string, unknown>, over: { bytes: number; cap: number; transport: EgressTransport }): OperationError {+ const slug = typeof params.slug === 'string' ? params.slug : undefined;+ const sourceId = typeof params.source_id === 'string' ? params.source_id : undefined;+ return opError('result_too_large',+ `${op} produced a ${over.bytes}-byte response; this connection carries at most ${over.cap} bytes per result (${EGRESS_CAP_CONFIG_KEYS[over.transport]}).`,+ "Ask for less in one call: a window (get_page body: 'window'), a page of rows (limit / cursor), or metadata only. Nothing was returned or cut.",+ {+ legacy_error: 'invalid_params',+ detail: JSON.stringify({ op, result_bytes: over.bytes, max_result_bytes: over.cap, transport: over.transport, config_key: EGRESS_CAP_CONFIG_KEYS[over.transport] }),+ ...(slug ? { fix: { argv: ['gbrain', 'get', ...(sourceId ? ['--source', sourceId] : []), '--', slug],+ mcp: { tool: 'get_page', arguments: { slug, ...(sourceId ? { source_id: sourceId } : {}), body: 'outline' } },+ consent: [], actor: 'agent' as const, why: "Returns the page's size and outline, which name the windows to read.", requires_exclusive: false } } : {}),+ });+}diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 8fba212896..2ce02ad1d8 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -90,7 +90,7 @@ const get_page: Operation = {slug: { type: 'string', description: 'Page slug.', required: true },fuzzy: { type: 'boolean', description: 'Fuzzy slug match.' },include_content: { type: 'boolean', description: "Full markdown + revision (body: 'full')." },- content_only: { type: 'boolean', description: 'Round-trip fields only (implies include_content).' },+ content_only: { type: 'boolean', description: 'Round-trip fields only.' },...GET_PAGE_BODY_PARAMS,include_deleted: { type: 'boolean', description: 'Include soft-deleted pages.' },include_timeline_entries: { type: 'boolean', description: 'Also return timeline rows.' },@@ -106,7 +106,7 @@ const get_page: Operation = {// Large pages: resolve the body mode first, so a malformed selector fails before any read.const bodyRequest = parseBodyRequest(ctx, p);const contentOnly = p.content_only === true;- const includeContent = p.include_content === true || contentOnly;+ const includeContent = p.include_content === true;const includeTimelineEntries = (p.include_timeline_entries as boolean) === true;// #4329: honor a per-call source_id (pre-fix it was silently dropped).// resolveRequestedScope (inside federatedSearchScope) enforces the remotediff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex bff79d4f45..6d1d1999a6 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -47,6 +47,7 @@ import { enforceReadTrustFloor } from '../core/eligibility/registry.ts';import { invalidateHotMemoryForEngine } from '../core/facts/meta-hook.ts';import { admittedPendingReceipt, type WriteReceipt } from '../core/persistence/types.ts';import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';+import { frameOverCap, resultTooLargeError } from '../core/egress-budget.ts';// WP3: normalization + validation moved to validate-params.ts (direct unit// surface). Re-exported here so existing imports/tests keep working.@@ -279,6 +280,8 @@ export interface DispatchOpts {isListed?: (op: OperationMeta) => Promise<boolean>;/** #5232: commit wait for coordinated writes (OperationContext.writeWaitMs); unset = agent default. */writeWaitMs?: number;+ /** Large pages: the caller sent X-Gbrain-Client (OperationContext.thinClient). Shape only, never authority. */+ thinClient?: boolean;/** C1: search/query row shape chosen by the transport (OperationContext.resultRows); unset = lean for remote callers. */resultRows?: OperationContext['resultRows'];}@@ -841,6 +844,7 @@ export function buildOperationContext(...(opts.revealTools ? { revealTools: opts.revealTools } : {}),...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),...(opts.resultRows ? { resultRows: opts.resultRows } : {}),+ ...(opts.thinClient ? { thinClient: true } : {}),isCallable: (opName: string) => (render ??= dispatchRenderContext(opts)).isCallable(opName),auth: opts.auth,};@@ -1135,6 +1139,9 @@ export async function dispatchToolCall(ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${msg}; degrading to no hook keys`);}}+ // Large pages: the egress backstop measures the final frame; a read over the connection's cap is refused whole, never cut.+ const over = op.mutating ? null : await frameOverCap(out, { remote: ctx.remote, transport: ctx.transport, engine, config: ctx.config });+ if (over) return errorResult(resultTooLargeError(name, safeParams, over), opts, { op: name, mutating: false, idempotent: op.idempotent === true });return out;} catch (e: unknown) {logVerb(false);diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 0057903ad0..d365c8a8fd 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -41,7 +41,7 @@ import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import type { AuthInfo } from '../core/operations.ts';import { VERSION } from '../version.ts';import { dispatchToolCall, requestLogStatusForResult, errorResult } from './dispatch.ts';-import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest } from './result-rows.ts';+import { GBRAIN_CLIENT_HEADER, isGbrainThinClient, resolveResultRowsMode, resultRowsForRequest } from './result-rows.ts';import { parseStrictParamsMode } from './validate-params.ts';import { filterOpsForSurface, clampSurface, advertisedOps, resolveAdvertisedSurface, type McpSurface } from './surface.ts';import { disabledOpsForPublishGates } from './publish-gates.ts';@@ -551,6 +551,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// IS the ceiling request_tools bounds catalog + persist by.surfaceCeiling: surface,resultRows: resultRowsForRequest(req.headers.get(GBRAIN_CLIENT_HEADER), await resolveResultRowsMode(engine, fileConfig)), // C1; row shape only, never authority+ thinClient: isGbrainThinClient(req.headers.get(GBRAIN_CLIENT_HEADER)), // large pages: default body mode only, never authority});// Same status taxonomy as the OAuth transport (denied_after_list /// success_with_warnings feed the amendment-33 metric + E4 usage).diff --git a/test/egress-backstop.test.ts b/test/egress-backstop.test.tsnew file mode 100644index 0000000000..8d55830287--- /dev/null+++ b/test/egress-backstop.test.ts@@ -0,0 +1,83 @@+/**+ * Large pages (Wave A): the dispatcher's egress backstop. A read whose final+ * encoded JSON-RPC frame is over the connection's cap is replaced by a+ * structured result_too_large, never cut; writes are never replaced; the+ * trusted local CLI has no cap. Hermetic in-memory PGLite.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall, buildOperationContext } from '../src/mcp/dispatch.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { EGRESS_CAP_DEFAULTS, EGRESS_CAP_MAX, EGRESS_CAP_MIN, encodedFrameBytes, frameOverCap, resultByteCap } from '../src/core/egress-budget.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const body = Array.from({ length: 5000 }, (_, i) => `line ${i} "quoted" text about acme-example widgets\twith a tab`).join('\n');+ const r = await importFromContent(engine, 'logs/wide', serializeMarkdown({}, body, '', { type: 'note', title: 'wide', tags: [] }),+ { sourceId: 'default', noEmbed: true, forceRechunk: true });+ expect(r.status).toBe('imported');+}, 120_000);++afterAll(async () => { await engine.disconnect(); }, 60_000);++describe('caps', () => {+ test('defaults, clamping and the local CLI', async () => {+ expect(await resultByteCap({ remote: true, transport: 'stdio' })).toBe(EGRESS_CAP_DEFAULTS.stdio);+ expect(await resultByteCap({ remote: true, transport: 'http' })).toBe(EGRESS_CAP_DEFAULTS.http);+ expect(await resultByteCap({ remote: true })).toBe(EGRESS_CAP_DEFAULTS.http);+ expect(await resultByteCap({ remote: false, transport: 'stdio' })).toBe(Number.POSITIVE_INFINITY);+ expect(await resultByteCap({ remote: true, transport: 'http', config: { mcp: { max_result_bytes_http: 1 } } as any })).toBe(EGRESS_CAP_MIN);+ expect(await resultByteCap({ remote: true, transport: 'stdio', config: { mcp: { max_result_bytes_stdio: 1e12 } } as any })).toBe(EGRESS_CAP_MAX);+ });++ test('the DB plane wins over the file plane', async () => {+ await engine.setConfig('mcp.max_result_bytes_http', String(300 * 1024));+ try {+ expect(await resultByteCap({ remote: true, transport: 'http', engine, config: { mcp: { max_result_bytes_http: 2_000_000 } } as any })).toBe(300 * 1024);+ } finally {+ await engine.unsetConfig('mcp.max_result_bytes_http');+ }+ });++ test('the frame is measured encoded, escapes included', () => {+ const text = '"\n'.repeat(1000);+ expect(encodedFrameBytes({ content: [{ type: 'text', text: JSON.stringify({ text }) }] })).toBeGreaterThan(text.length * 3);+ });++ test('frameOverCap is null for the local CLI and under the cap', async () => {+ const big = { content: [{ type: 'text', text: 'x'.repeat(2 * 1024 * 1024) }] };+ expect(await frameOverCap(big, { remote: false })).toBeNull();+ expect(await frameOverCap(big, { remote: true, transport: 'stdio' })).toBeNull();+ expect((await frameOverCap(big, { remote: true, transport: 'http' }))?.cap).toBe(EGRESS_CAP_DEFAULTS.http);+ });+});++describe('dispatch backstop', () => {+ test('an oversized read is result_too_large with the measured size, nothing cut', async () => {+ const config = { engine: 'pglite', mcp: { max_result_bytes_stdio: EGRESS_CAP_MIN } } as any;+ const out = await dispatchToolCall(engine, 'get_chunks', { slug: 'logs/wide' }, { remote: true, transport: 'stdio', sourceId: 'default', config });+ expect(out.isError).toBe(true);+ const env = JSON.parse(out.content[0].text);+ expect(env.code ?? env.error).toBe('result_too_large');+ const detail = typeof env.detail === 'string' ? JSON.parse(env.detail) : env.detail;+ expect(detail.max_result_bytes).toBe(EGRESS_CAP_MIN);+ expect(detail.result_bytes).toBeGreaterThan(EGRESS_CAP_MIN);+ expect(out.content.map(c => c.text).join('')).not.toContain('line 4999');+ });++ test('the same read under the cap passes untouched', async () => {+ const out = await dispatchToolCall(engine, 'get_chunks', { slug: 'logs/wide' }, { remote: true, transport: 'stdio', sourceId: 'default', config: { engine: 'pglite' } as any });+ expect(out.isError).toBeFalsy();+ expect(encodedFrameBytes(out)).toBeLessThanOrEqual(EGRESS_CAP_DEFAULTS.stdio);+ });++ test('the thin-client marker reaches the operation context and nothing else', () => {+ expect(buildOperationContext(engine, {}, { remote: true, transport: 'http', thinClient: true }).thinClient).toBe(true);+ expect(buildOperationContext(engine, {}, { remote: true, transport: 'http' }).thinClient).toBeUndefined();+ });+});diff --git a/test/get-page-body-modes.test.ts b/test/get-page-body-modes.test.tsindex b50d0caf3a..f6005eeb2f 100644--- a/test/get-page-body-modes.test.ts+++ b/test/get-page-body-modes.test.ts@@ -98,7 +98,7 @@ describe('mode resolution', () => {expect(typeof r.compiled_truth).toBe('string');const c = await get(ctx(), { slug: 'logs/big', include_content: true });expect(typeof c.content).toBe('string');- const only = await get(ctx(), { slug: 'logs/big', content_only: true });+ const only = await get(ctx(), { slug: 'logs/big', include_content: true, content_only: true });expect(typeof only.content).toBe('string');expect(only.compiled_truth).toBeUndefined();});