Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
serve --http: status-only mode instead of exiting when the brain cannot open
garrytanc9923524b611
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 52731e3155..daf40a69ff 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1621,7 +1621,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable. | A capability this request needs is not configured or not reachable on this brain. | Call gbrain_status for the cause, the fix and what to tell the user. | agent | `gbrain doctor --json` | 1 | no |-Reasons: `lock_held`, `no_brain`, `config_unreadable`, `missing_brain`, `brain_unopenable`, `repair_failed`.+Reasons: `lock_held`, `no_brain`, `config_unreadable`, `missing_brain`, `brain_unopenable`, `repair_failed`, `unavailable`.### shared_skills_unavailablediff --git a/src/commands/serve-http-listen.ts b/src/commands/serve-http-listen.tsindex 82bfab24ce..92aacf8865 100644--- a/src/commands/serve-http-listen.ts+++ b/src/commands/serve-http-listen.ts@@ -4,11 +4,19 @@* server announcing itself and holding the brain lock while serving nothing* (Bun runs a listen callback with `listening: false` and then emits `error`* to no listener). Resolves only once the socket really listens.+ *+ * `adopt`: a listener the status-only serve already bound on this port+ * (serve-http-status.ts). Recovery hands the full app to it as the request+ * handler instead of binding again, so the port is never released.*/-import type { Server } from 'node:http';+import type { IncomingMessage, Server, ServerResponse } from 'node:http';import { opError } from '../core/ops/contract.ts';-export async function listenOrRefuse(app: { listen(port: number, host: string): Server }, port: number, bind: string): Promise<Server> {+export type HttpRequestHandler = (req: IncomingMessage, res: ServerResponse) => void;+export interface AdoptableServer { server: Server; adopt(handler: HttpRequestHandler): void }++export async function listenOrRefuse(app: HttpRequestHandler & { listen(port: number, host: string): Server }, port: number, bind: string, adopt?: AdoptableServer): Promise<Server> {+ if (adopt) { adopt.adopt(app); return adopt.server; }const server = app.listen(port, bind);const failure = await new Promise<Error | null>(resolve => {if (server.listening) return resolve(null);diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 3021ae5829..9e6faee606 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -23,6 +23,7 @@ import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writebackimport { hasScope, operationScopesAllowed } from '../core/scope.ts';import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, type ToolResult } from '../mcp/dispatch.ts';import { toAgentError } from '../core/agent-output.ts';+import { STATUS_TOOL_NAME, statusModeOf, statusToolResult } from '../mcp/status-mode.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import { scopeDeniedError } from '../core/ops/op-fix.ts';import { resolveStrictParamsMode } from '../mcp/validate-params.ts';@@ -284,6 +285,9 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requesconst { engine, broadcastEvent, logFullParams } = ctx;const { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows } = 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;+ if (statusMode && hasScope(authInfo.scopes, 'read')) return statusToolResult(statusMode, 'http');const op = mcpOperations.find(o => o.name === name);if (!op) {return rejectUnknownMcpOperation(ctx, state, name);diff --git a/src/commands/serve-http-status.ts b/src/commands/serve-http-status.tsnew file mode 100644index 0000000000..5c6050005f--- /dev/null+++ b/src/commands/serve-http-status.ts@@ -0,0 +1,231 @@+/**+ * Status-only `gbrain serve --http` (agent operator contract v1): a shared+ * HTTP server whose brain cannot be opened (lock held, no brain, a missing or+ * repair-failed brain, unreadable config) stays up on its `--bind`/`--port`+ * and explains itself instead of exiting into a supervisor crash loop.+ *+ * One `node:http` listener whose request handler is a mutable reference:+ * - `GET /health` → 503 with the allowlisted payload, `Retry-After: 5` and+ * `instance` (the marker's nonce);+ * - `POST /mcp` → a stateless MCP server with exactly `gbrain_status`;+ * any other tool gets one `serve_status_only` error block;+ * - everything else (OAuth discovery, `/token`, `/authorize`, `/register`,+ * `/admin*`) → a 503 `serve_status_only` envelope.+ * Every response is unauthenticated (the bearer tokens live in the brain it+ * cannot open), so each one states the collapsed reason only.+ *+ * Recovery: a single-flight 5 s tick runs the shared re-probe; on a connect+ * the full app is built by `runServe` while the status handler keeps+ * answering, then `listenOrRefuse` swaps the handler on the same listener (no+ * close and rebind, so no port race). A full-app build that fails disconnects+ * the engine (releasing the lock) and keeps the status handler with reason+ * `brain_unopenable`. Shutdown during a recovery waits for it, then closes+ * once; only this instance's marker is removed.+ */+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';+import type { Socket } from 'node:net';+import { randomBytes } from 'node:crypto';+import { Server as McpServer } from '@modelcontextprotocol/sdk/server/index.js';+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';+import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';+import type { BrainEngine } from '../core/engine.ts';+import { cliRenderContext, renderAction } from '../core/agent-output.ts';+import { registerCleanup } from '../core/process-cleanup.ts';+import { currentBrainId } from '../core/minions/worker-registry.ts';+import { removeStatusMarker, writeStatusMarker } from '../core/serve-http-status-marker.ts';+import {+ HTTP_STATUS_RETRY_AFTER_S, HTTP_STATUS_TOOL_DEF, STATUS_TOOL_NAME, httpStatusEnvelope, httpStatusPayload, initialStatusState,+ markStatusModeEngine, statusFix, statusHeadline, statusInstructionLine, statusModeErrorResult, statusToolResult, type StatusModeState,+} from '../mcp/status-mode.ts';+import { VERSION } from '../version.ts';+import { listenOrRefuse, type AdoptableServer, type HttpRequestHandler } from './serve-http-listen.ts';+import { logStatusTransition, statusReasonForError } from './serve-status.ts';++export const HTTP_STATUS_TICK_MS = HTTP_STATUS_RETRY_AFTER_S * 1000;++export interface HttpStatusServeDeps {+ tickMs?: number;+ log?: (msg: string) => void;+ /** Boots the full server on the adopted listener (default: serve.ts `runServe`). */+ runServe?: (engine: BrainEngine, args: string[], opts: { adoptServer: AdoptableServer }) => Promise<void>;+ exit?: (code: number) => void;+ /** Test seam: the running instance (its listener, nonce and shutdown). */+ onReady?: (handle: { server: Server; nonce: string; shutdown(): Promise<void> }) => void;+}++function argValue(args: readonly string[], flag: string): string | undefined {+ const i = args.indexOf(flag);+ return i >= 0 ? args[i + 1] : undefined;+}++function sendJson(res: ServerResponse, status: number, body: unknown): void {+ res.writeHead(status, { 'Content-Type': 'application/json', 'Retry-After': String(HTTP_STATUS_RETRY_AFTER_S), Connection: 'close' });+ res.end(JSON.stringify(body));+}++async function serveStatusMcp(state: StatusModeState, req: IncomingMessage, res: ServerResponse): Promise<void> {+ const server = new McpServer({ name: 'gbrain', version: VERSION }, { capabilities: { tools: {} }, instructions: statusInstructionLine(state, 'http') });+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [HTTP_STATUS_TOOL_DEF] }));+ server.setRequestHandler(CallToolRequestSchema, async (request) => (request.params.name === STATUS_TOOL_NAME+ ? statusToolResult(state, 'http') : statusModeErrorResult(state, request.params.name, 'http')));+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });+ res.on('close', () => { transport.close().catch(() => {}); server.close().catch(() => {}); });+ res.setHeader('Connection', 'close');+ try {+ await server.connect(transport);+ await transport.handleRequest(req, res);+ } catch {+ if (!res.headersSent) sendJson(res, 503, httpStatusEnvelope());+ }+}++function statusHandler(state: StatusModeState, nonce: string): HttpRequestHandler {+ return (req, res) => {+ const path = (req.url ?? '/').split('?')[0];+ if (path === '/health') return sendJson(res, 503, { ...httpStatusPayload(), instance: nonce });+ if (path === '/mcp' && req.method === 'POST') { void serveStatusMcp(state, req, res); return; }+ if (path === '/mcp' && req.method === 'GET') {+ res.writeHead(405, { 'Content-Type': 'application/json', Allow: 'POST, DELETE', Connection: 'close' });+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed' }, id: null }));+ return;+ }+ sendJson(res, 503, httpStatusEnvelope());+ };+}++/** The human banner: the reason, the fix and how the daemon behaves. */+function banner(state: StatusModeState, where: string): string {+ const fix = renderAction(statusFix(state, 'http').fix, cliRenderContext());+ return [+ `GBrain MCP server: status-only mode on ${where} (the brain cannot be opened).`,+ ` Reason: ${statusHeadline(state)}`,+ ` Fix: ${fix.command ?? fix.why}`,+ ` Re-checking every ${HTTP_STATUS_RETRY_AFTER_S} s; Ctrl-C to stop; --fail-fast to exit instead.`,+ ].join('\n');+}++/**+ * Serve the status listener until the brain opens (then the full server owns+ * the process) or shutdown. `probe` is the shared re-probe from+ * `runStatusModeServe`: null while blocked, an engine once connected.+ */+export async function runHttpStatusServe(+ state: StatusModeState, args: string[], probe: () => Promise<BrainEngine | null>, deps: HttpStatusServeDeps = {},+): Promise<void> {+ const log = deps.log ?? ((msg: string) => console.error(msg));+ const exit = deps.exit ?? ((code: number) => process.exit(code));+ const tickMs = deps.tickMs ?? HTTP_STATUS_TICK_MS;+ const port = parseInt(argValue(args, '--port') ?? '', 10) || 3131;+ const bind = argValue(args, '--bind') ?? '127.0.0.1';+ const nonce = randomBytes(16).toString('hex');+ const enteredAt = Date.now();++ let handler: HttpRequestHandler = statusHandler(state, nonce);+ const dispatch: HttpRequestHandler = (req, res) => handler(req, res);+ const sockets = new Set<Socket>();+ const listen = (p: number, h: string) => createServer(dispatch)+ .on('connection', (socket: Socket) => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)); })+ .listen(p, h);+ // A taken port (usually the HTTP serve that holds the brain) exits with serve_port_in_use.+ const server = await listenOrRefuse(Object.assign(dispatch, { listen }), port, bind);++ const marker = () => writeStatusMarker({ pid: process.pid, instance_nonce: nonce, brain_id: currentBrainId(), bind, port, reason: state.reason, since: new Date().toISOString() });+ marker();+ const dropMarker = () => removeStatusMarker(port, nonce);+ process.once('exit', dropMarker);+ log(banner(state, `http://${bind}:${port}`));++ let adopted = false;+ let stopping = false;+ let recovered: BrainEngine | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ let inflight: Promise<void> | null = null;+ let settle!: (outcome: { error?: unknown }) => void;+ const done = new Promise<{ error?: unknown }>(resolve => { settle = resolve; });++ const backToStatus = async (engine: BrainEngine, e: unknown) => {+ await engine.disconnect().catch(() => {});+ if (stopping) return;+ Object.assign(state, initialStatusState('brain_unopenable'), { reason: 'brain_unopenable', recovered: false });+ marker();+ log(`GBrain MCP server: the brain opened but the full server did not start (${e instanceof Error ? e.message : String(e)}); the brain is released and this server stays in status-only mode.`);+ logStatusTransition('serve_status_mode_enter', state, 'http', enteredAt);+ };++ const recover = (engine: BrainEngine) => new Promise<void>((swapped) => {+ recovered = markStatusModeEngine(engine, state);+ const runServe = deps.runServe ?? (async (e, a, o) => (await import('./serve.ts')).runServe(e, a, o));+ const adoptServer: AdoptableServer = {+ server,+ adopt(next: HttpRequestHandler) {+ if (stopping) throw new Error('gbrain serve --http is shutting down');+ handler = next;+ adopted = true;+ // The full server's lifecycle owns SIGINT from here on.+ process.off('SIGINT', onSigint);+ dropMarker();+ log(`GBrain MCP server: the brain is open; the full server now answers on http://${bind}:${port}.`);+ swapped();+ },+ };+ runServe(engine, args, { adoptServer }).then(+ () => settle({}),+ async (e: unknown) => {+ if (adopted) return settle({ error: e });+ recovered = null;+ await backToStatus(engine, e);+ swapped();+ },+ );+ });++ const tick = async () => {+ const before = state.reason;+ let engine: BrainEngine | null;+ try {+ engine = await probe();+ } catch (e) {+ Object.assign(state, initialStatusState(statusReasonForError(e) ?? 'brain_unopenable'), { recovered: false });+ if (state.reason !== before) { marker(); log(`GBrain MCP server: the brain did not open (${e instanceof Error ? e.message : String(e)}); still status-only: ${statusHeadline(state)}`); }+ return;+ }+ if (engine === null) {+ if (state.reason !== before) { marker(); log(`GBrain MCP server: still status-only: ${statusHeadline(state)}`); }+ return;+ }+ if (stopping) { await engine.disconnect().catch(() => {}); return; }+ await recover(engine);+ };++ const schedule = () => {+ if (stopping || adopted) return;+ timer = setTimeout(() => {+ timer = null;+ inflight = tick().finally(() => { inflight = null; schedule(); });+ }, tickMs);+ };++ const shutdown = async (): Promise<void> => {+ if (stopping) return;+ stopping = true;+ if (timer) clearTimeout(timer);+ await inflight;+ if (adopted) { await recovered?.disconnect().catch(() => {}); return; }+ dropMarker();+ await new Promise<void>(resolve => {+ server.close(() => resolve());+ for (const s of sockets) s.destroy();+ });+ settle({});+ };+ const deregister = registerCleanup('serve-http-status', shutdown);+ const onSigint = () => { void shutdown().then(() => exit(0)); };+ process.once('SIGINT', onSigint);+ deps.onReady?.({ server, nonce, shutdown });+ schedule();++ const outcome = await done;+ process.off('SIGINT', onSigint);+ deregister();+ if (outcome.error) throw outcome.error;+}diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 1626e23160..28e21056fd 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -15,7 +15,7 @@* is re-exported below.*/-import { listenOrRefuse } from './serve-http-listen.ts';+import { listenOrRefuse, type AdoptableServer } from './serve-http-listen.ts';import express from 'express';import type { Socket } from 'net';import type { Request, RequestHandler, CookieOptions } from 'express';@@ -404,6 +404,8 @@ interface ServeHttpOptions {* captured to a non-interactive log and accept the leak.*/printAdminToken?: boolean;+ /** A status-only serve's bound listener: recovery swaps its handler to this app instead of binding (serve-http-listen.ts). */+ adoptServer?: AdoptableServer;}/**@@ -848,7 +850,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// ---------------------------------------------------------------------------const clientCount = await sql`SELECT count(*)::int as count FROM oauth_clients`;- const httpServer = await listenOrRefuse(app, port, bind);+ const httpServer = await listenOrRefuse(app, port, bind, options.adoptServer);console.error(`╔══════════════════════════════════════════════════════╗║ GBrain MCP Server v${VERSION.padEnd(37)}║diff --git a/src/commands/serve-status.ts b/src/commands/serve-status.tsindex 8e0934468a..853a7d8d1d 100644--- a/src/commands/serve-status.ts+++ b/src/commands/serve-status.ts@@ -1,17 +1,19 @@/**- * Status-only stdio serve entry (agent operator contract v1, F4): cli.ts- * hands over a `gbrain serve` whose brain cannot be opened (lock held by a- * live holder, no brain, unreadable config). The server completes the MCP- * handshake with one `gbrain_status` tool instead of exiting; a later tool- * call recovers in place through the gated lazy engine (src/mcp/status-mode.ts).+ * Status-only serve entry (agent operator contract v1, F4): cli.ts hands over+ * a `gbrain serve` (stdio or `--http`) whose brain cannot be opened (lock held+ * by a live holder, no brain, a missing or repair-failed brain, unreadable+ * config). `runStatusModeServe` is the one entry point for both transports and+ * `reprobe` (src/mcp/status-mode.ts) the one re-probe: stdio answers the MCP+ * handshake with one `gbrain_status` tool and re-probes inside tool calls+ * through the gated lazy engine; `--http` serves the status listener+ * (serve-http-status.ts) and re-probes on a 5 s background tick.*- * Not for `--http` (an HTTP serve is a supervised daemon; its contention is- * the bind/lock error), and skipped under `--fail-fast` /- * GBRAIN_SERVE_FAIL_FAST=1 so supervisors keep a non-zero exit (C10).+ * Skipped under `--fail-fast` / GBRAIN_SERVE_FAIL_FAST=1 so supervisors keep+ * a non-zero exit (C10).*/import type { BrainEngine } from '../core/engine.ts';import { loadConfig } from '../core/config.ts';-import { gatedReconnect, initialStatusState, markStatusModeEngine, probeStatus, statusHeadline, type StatusReason } from '../mcp/status-mode.ts';+import { initialStatusState, markStatusModeEngine, probeStatus, reprobe, statusHeadline, statusReconnect, type StatusModeState, type StatusReason, type StatusTransport } from '../mcp/status-mode.ts';export function serveFailFast(args: readonly string[]): boolean {return args.includes('--fail-fast') || process.env.GBRAIN_SERVE_FAIL_FAST === '1';@@ -19,7 +21,7 @@ export function serveFailFast(args: readonly string[]): boolean {/** Whether this `serve` invocation takes the status-only path on a startup failure. */export function statusModeEligible(args: readonly string[], hostBrain: boolean): boolean {- return hostBrain && !args.includes('--http') && !serveFailFast(args);+ return hostBrain && !serveFailFast(args);}/**@@ -41,16 +43,37 @@ export function statusReasonForError(e: unknown): StatusReason | null {return null;}-/** Run the stdio server over a gated lazy engine; resolves when serve's lifecycle does. */+/** One structured stderr line per status-mode transition (host-local: the detailed reason is safe here). */+export function logStatusTransition(event: 'serve_status_mode_enter' | 'serve_status_mode_recovered', state: StatusModeState, transport: StatusTransport, enteredAt: number): void {+ try { process.stderr.write(`${JSON.stringify({ event, reason: state.reason, transport, elapsed_ms: Date.now() - enteredAt })}\n`); } catch { /* stderr gone */ }+}++/**+ * Serve in status-only mode until the brain opens; resolves when serve's+ * lifecycle does. `connect` is throw-only (src/core/engine-connect.ts).+ */export async function runStatusModeServe(reason: StatusReason, initialError: unknown, args: string[], connect: () => Promise<BrainEngine>,): Promise<void> {const state = initialStatusState(reason);+ const transport: StatusTransport = args.includes('--http') ? 'http' : 'stdio';+ const enteredAt = Date.now();+ logStatusTransition('serve_status_mode_enter', state, transport, enteredAt);+ // The one re-probe both transports run; a check that must run on every re-probe hooks here.+ const probeAgain = async (): Promise<BrainEngine | null> => {+ const engine = await reprobe(state, connect);+ if (engine) logStatusTransition('serve_status_mode_recovered', state, transport, enteredAt);+ return engine;+ };+ if (transport === 'http') {+ const { runHttpStatusServe } = await import('./serve-http-status.ts');+ return runHttpStatusServe(state, args, probeAgain);+ }const { createDegradedEngine } = await import('../core/degraded-engine.ts');const kind = loadConfig()?.engine === 'postgres' ? 'postgres' : 'pglite';const engine = markStatusModeEngine(createDegradedEngine({initialError: initialError ?? new Error(statusHeadline(state)),- reconnect: () => gatedReconnect(state, connect),+ reconnect: () => statusReconnect(state, probeAgain),// A PGLite open + pending migrations can take longer than the degraded default.callerWaitMs: 20_000,kind,diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 3dd36fd4b8..1ab222bd45 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -133,6 +133,8 @@ export interface ServeOptions {// without booting the real OAuth server. Type-only reference to// serve-http.ts — erased at compile time, so the lazy runtime import stays.runServeHttp?: (typeof import('./serve-http.ts'))['runServeHttp'];+ /** `--http` recovery from status-only mode: the listener the status server already bound (serve-http-status.ts). */+ adoptServer?: import('./serve-http-listen.ts').AdoptableServer;// Test seam (#4281): replaces installLoopStallWatchdog.installStallWatchdog?: (o: LoopStallWatchdogOpts) => WatchdogHandle;// Test seam (#4281) for the loop-stall threshold in ms; 0 = off. Defaults@@ -318,7 +320,7 @@ export async function runServe(}try {- await runHttp(engine, { port, tokenTtl, enableDcr, enableDcrInsecure, publicUrl, logFullParams, bind, suppressBootstrapToken, printAdminToken, surface });+ await runHttp(engine, { port, tokenTtl, enableDcr, enableDcrInsecure, publicUrl, logFullParams, bind, suppressBootstrapToken, printAdminToken, surface, adoptServer: opts.adoptServer });} finally {stallWatchdog?.dispose();}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 02d15a8203..ec8dc4f44e 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -234,7 +234,7 @@ export const CODES = {scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },- serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },+ serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed', 'unavailable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },skill_asset_not_found: { class: 'caller', summary: "The requested file is not in the approved revision manifest." },diff --git a/src/core/serve-http-status-marker.ts b/src/core/serve-http-status-marker.tsnew file mode 100644index 0000000000..6c9098ae0d--- /dev/null+++ b/src/core/serve-http-status-marker.ts@@ -0,0 +1,117 @@+/**+ * The per-instance marker a status-only `gbrain serve --http` writes while it+ * cannot open its brain: `GBRAIN_HOME/serve-http-status-<port>.json`. It holds+ * the detailed reason the unauthenticated HTTP responses never state, so+ * readiness, doctor and `gbrain mcp expose` on the host can say why the+ * shared server answers 503 and give the reason's fix.+ *+ * Live means: the PID is alive and `since` is after the last boot (config+ * plane, no network); doctor additionally asks `/health` for a 503 carrying+ * this marker's `instance_nonce` within 500 ms, and deletes dead markers. A+ * process removes only its own marker (matched by nonce).+ */+import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { uptime } from 'node:os';+import { gbrainPath } from './config.ts';++export interface HttpStatusMarker {+ pid: number;+ instance_nonce: string;+ brain_id: string;+ bind: string;+ port: number;+ /** The detailed status reason (host-local only). */+ reason: string;+ /** ISO time status mode was entered or last changed reason. */+ since: string;+}++const MARKER_RE = /^serve-http-status-(\d+)\.json$/;+export const STATUS_MARKER_PROBE_MS = 500;++export function statusMarkerPath(port: number): string {+ return gbrainPath(`serve-http-status-${port}.json`);+}++export function writeStatusMarker(m: HttpStatusMarker): void {+ const path = statusMarkerPath(m.port);+ mkdirSync(gbrainPath(), { recursive: true });+ const tmp = `${path}.${process.pid}.tmp`;+ writeFileSync(tmp, `${JSON.stringify(m, null, 2)}\n`, { mode: 0o600 });+ renameSync(tmp, path);+}++function parseMarker(path: string): HttpStatusMarker | null {+ try {+ const m = JSON.parse(readFileSync(path, 'utf8')) as Partial<HttpStatusMarker>;+ if (typeof m.pid !== 'number' || typeof m.port !== 'number' || typeof m.instance_nonce !== 'string' || typeof m.since !== 'string') return null;+ return { pid: m.pid, instance_nonce: m.instance_nonce, brain_id: String(m.brain_id ?? ''), bind: String(m.bind ?? '127.0.0.1'), port: m.port, reason: String(m.reason ?? ''), since: m.since };+ } catch {+ return null;+ }+}++/** Remove this instance's marker; another instance's marker on the same port is left alone. */+export function removeStatusMarker(port: number, nonce: string): void {+ const path = statusMarkerPath(port);+ if (parseMarker(path)?.instance_nonce !== nonce) return;+ try { rmSync(path, { force: true }); } catch { /* already gone */ }+}++/** Every marker file under GBRAIN_HOME, live or not. */+export function readStatusMarkers(): HttpStatusMarker[] {+ const dir = gbrainPath();+ if (!existsSync(dir)) return [];+ let names: string[];+ try { names = readdirSync(dir); } catch { return []; }+ return names.filter(n => MARKER_RE.test(n)).map(n => parseMarker(gbrainPath(n))).filter((m): m is HttpStatusMarker => m !== null);+}++function pidAlive(pid: number): boolean {+ try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }+}++/** Config-plane liveness: the PID is alive and the marker was written after the last boot. */+export function statusMarkerLive(m: HttpStatusMarker, now = Date.now()): boolean {+ const since = Date.parse(m.since);+ return Number.isFinite(since) && since >= now - uptime() * 1000 && pidAlive(m.pid);+}++export function liveStatusMarkers(): HttpStatusMarker[] {+ return readStatusMarkers().filter(m => statusMarkerLive(m));+}++/** The marker for one port when it is live (`gbrain mcp expose` reads its own port). */+export function liveStatusMarkerFor(port: number): HttpStatusMarker | null {+ const m = parseMarker(statusMarkerPath(port));+ return m && statusMarkerLive(m) ? m : null;+}++/** Probed tier: `/health` answers 503 with this marker's instance nonce within 500 ms. */+export async function statusMarkerAnswers(m: HttpStatusMarker, timeoutMs = STATUS_MARKER_PROBE_MS): Promise<boolean> {+ const host = m.bind === '0.0.0.0' || m.bind === '' ? '127.0.0.1' : m.bind === '::' ? '[::1]' : m.bind.includes(':') ? `[${m.bind}]` : m.bind;+ try {+ const res = await fetch(`http://${host}:${m.port}/health`, { signal: AbortSignal.timeout(timeoutMs) });+ if (res.status !== 503) { await res.body?.cancel().catch(() => {}); return false; }+ const body = await res.json() as { instance?: unknown };+ return body.instance === m.instance_nonce;+ } catch {+ return false;+ }+}++/**+ * Doctor's view: live markers whose server answers as that instance. A marker+ * whose PID is gone (or predates the last boot) is deleted.+ */+export async function verifiedStatusMarkers(): Promise<HttpStatusMarker[]> {+ const out: HttpStatusMarker[] = [];+ for (const m of readStatusMarkers()) {+ if (!statusMarkerLive(m)) {+ try { rmSync(statusMarkerPath(m.port), { force: true }); } catch { /* best-effort */ }+ continue;+ }+ if (await statusMarkerAnswers(m)) out.push(m);+ }+ return out;+}diff --git a/src/mcp/status-mode.ts b/src/mcp/status-mode.tsindex 04bfc1d4dc..486ce5462c 100644--- a/src/mcp/status-mode.ts+++ b/src/mcp/status-mode.ts@@ -22,10 +22,11 @@ import { opError } from '../core/ops/contract.ts';import { configPath, gbrainPath, loadConfig, type GBrainConfig } from '../core/config.ts';import { inspectLockHolder, peekLock } from '../core/pglite-lock.ts';import { HANDS_OFF_BRAIN_FILES, readRepairFailedMarker, type RepairFailedMarker } from '../core/pglite-repair.ts';-import { resetReadinessMemo } from '../core/readiness.ts';export const STATUS_TOOL_NAME = 'gbrain_status';export type StatusReason = 'lock_held' | 'no_brain' | 'config_unreadable' | 'missing_brain' | 'brain_unopenable' | 'repair_failed';+/** stdio: a harness-launched server re-probing inside tool calls. http: a `serve --http` daemon re-probing on a 5 s tick. */+export type StatusTransport = 'stdio' | 'http';export interface StatusModeState {reason: StatusReason;@@ -96,22 +97,34 @@ export function initialStatusState(fallback: StatusReason): StatusModeState {}/**- * The reconnect gate: re-probe; while still blocked, update the state and- * throw (no lock attempt); otherwise forget memoized readiness and connect.+ * The one re-probe both transports run (stdio inside a tool call, HTTP on its+ * 5 s tick): classify with file reads only; while still blocked, update the+ * state and return null (no lock attempt); otherwise forget memoized+ * readiness and connect once. `connect` is throw-only, so a failed attempt+ * rejects into the caller and never exits the process.*/-export async function gatedReconnect<E>(state: StatusModeState, connect: () => Promise<E>): Promise<E> {+export async function reprobe<E>(state: StatusModeState, connect: () => Promise<E>): Promise<E | null> {const probed = probeStatus();if (probed) {Object.assign(state, probed);- throw opError('serve_status_only', statusHeadline(state), 'Call gbrain_status for the cause, the fix and what to tell the user.', { reason: state.reason });+ return null;}- resetReadinessMemo();+ (await import('../core/readiness.ts')).resetReadinessMemo();const engine = await connect();state.recovered = true;state.checked_at = Date.now();return engine;}+/** The lazy engine's reconnect gate on stdio: `reprobe`, throwing `serve_status_only` while still blocked. */+export async function statusReconnect<E>(state: StatusModeState, probe: () => Promise<E | null>): Promise<E> {+ const engine = await probe();+ if (engine === null) {+ throw opError('serve_status_only', statusHeadline(state), 'Call gbrain_status for the cause, the fix and what to tell the user.', { reason: state.reason });+ }+ return engine;+}+function ownerPhrase(state: StatusModeState): string {const o = state.lock_owner;if (!o) return 'another process';@@ -130,14 +143,27 @@ export function statusHeadline(state: StatusModeState): string {return `No gbrain brain is set up on this machine yet (no config at ${state.config_path}), so this server has no brain to open.`;}-const RESTART_NOTE = 'If your client does not refresh its tool list after recovery, restart this MCP server.';+function restartNote(t: StatusTransport): string {+ return t === 'http'+ ? 'HTTP clients then re-list tools or reconnect; a client that connected during status mode signs in again (HTTP 401 with WWW-Authenticate).'+ : 'If your client does not refresh its tool list after recovery, restart this MCP server.';+}++/** How the server picks the brain up once the cause is fixed. */+function recheck(t: StatusTransport): string {+ return t === 'http' ? 'this HTTP server re-checks every 5 s and opens the brain in place' : 'call gbrain_status again and this server opens the brain in place';+}++/** The stdio wait fix calls gbrain_status; an HTTP daemon re-checks on its own. */+const statusCall = (t: StatusTransport) => (t === 'stdio' ? { mcp: { tool: STATUS_TOOL_NAME, arguments: {} } } : {});-function statusFix(state: StatusModeState): { fix: Action; user_message: string; decisions?: Decision[]; plan?: Action } {+/** The cause's fix, decisions and relay text; `transport` says how the blocked server re-checks. */+export function statusFix(state: StatusModeState, t: StatusTransport = 'stdio'): { fix: Action; user_message: string; decisions?: Decision[]; plan?: Action } {if (state.reason === 'no_brain') {return {fix: {argv: ['gbrain', 'init', '--pglite', '--no-embedding'], consent: ['persistent_install'], actor: 'agent', requires_exclusive: false,- why: `Creates a keyless local brain (config at ${state.config_path}); semantic search can be enabled later. Then call gbrain_status again: this server picks the new brain up without a restart. ${RESTART_NOTE}`,+ why: `Creates a keyless local brain (config at ${state.config_path}); semantic search can be enabled later. Then ${recheck(t)}, without a restart. ${restartNote(t)}`,user_message: 'gbrain memory is installed but no brain exists yet. Should I create a local one now? It stays on this machine and needs no API key.',verify: { argv: ['gbrain', 'doctor', '--json'] }, docs: 'INSTALL_FOR_AGENTS.md',},@@ -151,8 +177,8 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;: `Your gbrain brain at ${where} is there, but gbrain can't open its lock file next to it (a read-only or unmounted drive, or a permissions problem). Can you check that drive? Once it's writable I'll reconnect.`;return {fix: {- mcp: { tool: STATUS_TOOL_NAME, arguments: {} }, consent: [], actor: 'user', requires_exclusive: false,- why: `${state.reason === 'missing_brain' ? `Mount or reconnect the drive that holds ${where}, or point \`database_path\` in ${state.config_path} at where the brain lives now` : `Make the folder holding ${where} writable for this user (or mount the drive read-write)`}; then call gbrain_status again and this server opens the brain in place. ${RESTART_NOTE}`,+ ...statusCall(t), consent: [], actor: 'user', requires_exclusive: false,+ why: `${state.reason === 'missing_brain' ? `Mount or reconnect the drive that holds ${where}, or point \`database_path\` in ${state.config_path} at where the brain lives now` : `Make the folder holding ${where} writable for this user (or mount the drive read-write)`}; then ${recheck(t)}. ${restartNote(t)}`,user_message,verify: { argv: ['gbrain', 'doctor', '--only', 'connection', '--json'] },},@@ -161,7 +187,7 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;id: 'missing_brain_recovery',question: `The brain at ${where} is not there. Bring it back, or start a new empty brain?`,options: [- { id: 'reconnect', label: 'Mount or move the brain back; this server reconnects on the next gbrain_status call.' },+ { id: 'reconnect', label: `Mount or move the brain back; ${t === 'http' ? 'this server reconnects within 5 s' : 'this server reconnects on the next gbrain_status call'}.` },{ id: 'new_brain', label: 'Create a new, empty keyless brain at that path (the old notes are not in it).', argv: ['gbrain', 'init', '--pglite', '--no-embedding', '--path', where] },],default: 'reconnect',@@ -174,7 +200,7 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;return {fix: {argv: ['gbrain', 'pglite-repair', '--dry-run', '--json'], consent: [], actor: 'user', requires_exclusive: false,- why: `${HANDS_OFF_BRAIN_FILES} The read-only preview names the consented repair (\`gbrain pglite-repair --yes --expect <plan_hash>\`, effects destructive) the user runs once they agree; then call gbrain_status again. ${RESTART_NOTE}`,+ why: `${HANDS_OFF_BRAIN_FILES} The read-only preview names the consented repair (\`gbrain pglite-repair --yes --expect <plan_hash>\`, effects destructive) the user runs once they agree; then ${recheck(t)}. ${restartNote(t)}`,user_message,},user_message,@@ -184,7 +210,7 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;return {fix: {argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,- why: `Fix or restore ${state.config_path} (it must be valid JSON; \`gbrain doctor --json\` names the problem), then call gbrain_status again. Never delete it without asking: it holds the brain's settings and may hold keys.`,+ why: `Fix or restore ${state.config_path} (it must be valid JSON; \`gbrain doctor --json\` names the problem), then ${recheck(t)}. Never delete it without asking: it holds the brain's settings and may hold keys.`,user_message: `Your gbrain config file (${state.config_path}) is damaged, so memory is offline. Can you check it, or should I show you what doctor reports?`,},user_message: `Your gbrain config file (${state.config_path}) is damaged, so memory is offline. Can you check it, or should I show you what doctor reports?`,@@ -201,6 +227,14 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;// A shared HTTP server already owns the brain: only this harness needs rewiring.return { fix: wireHarnesses, user_message: wireHarnesses.user_message! };}+ if (t === 'http') {+ // This process is the shared HTTP server: once the owner stops, it opens the brain and the harnesses move to it.+ const user_message = `Your gbrain brain is open in ${owner.replace(/`/g, '')}, so the shared gbrain server can't open it. Should I stop that session so every agent shares the server?`;+ return { user_message, fix: {+ ...(state.lock_owner?.pid !== undefined ? { argv: ['kill', String(state.lock_owner.pid)] } : {}), consent: [], actor: 'user', requires_exclusive: false, user_message,+ why: `Stop ${owner} (or quit that session); ${recheck(t)}. Then wire the harnesses to it.`, then: wireHarnesses,+ } };+ }const startHttp: Action = {argv: ['gbrain', 'serve', '--http'], consent: ['persistent_install'], actor: 'user', requires_exclusive: true,why: 'Run ONE shared HTTP server for every agent session on this machine (keep it running, e.g. under autopilot or a terminal).',@@ -211,8 +245,8 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;why: `Stop ${owner} first (or quit that session); the shared server needs the brain's single-writer lock.`, then: startHttp }: startHttp;const waitFix: Action = {- mcp: { tool: STATUS_TOOL_NAME, arguments: {} }, consent: [], actor: 'user', requires_exclusive: false,- why: `Close the session that owns the brain (${owner}); then call gbrain_status again and this server opens the brain in place (re-checked at most every 5 s). ${RESTART_NOTE}`,+ ...statusCall(t), consent: [], actor: 'user', requires_exclusive: false,+ why: `Close the session that owns the brain (${owner}); then ${recheck(t)} (re-checked at most every 5 s). ${restartNote(t)}`,};const user_message = `Your gbrain brain is already open in ${owner.replace(/`/g, '')}, so this session can't use memory right now. Close that session and I'll reconnect, or I can set up one shared gbrain server so both sessions work at once. Which do you prefer?`;return {@@ -234,16 +268,60 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;/** Status mode's render context: on stdio, only gbrain_status is callable. */const STATUS_RENDER: RenderContext = { transport: 'stdio', isCallable: n => n === STATUS_TOOL_NAME, preapproved: () => false };+/** HTTP status mode: every caller is unauthenticated (its tokens live in the brain it cannot open). */+const HTTP_STATUS_RENDER: RenderContext = { transport: 'http', isCallable: n => n === STATUS_TOOL_NAME, preapproved: () => false };++/** Seconds an HTTP client waits before asking again (the daemon's re-probe interval). */+export const HTTP_STATUS_RETRY_AFTER_S = 5;+/**+ * The only cause an unauthenticated HTTP response states. The bind address+ * cannot tell who is asking (Tailscale Funnel delivers public requests from a+ * loopback address), so the detailed reason stays in stderr, the status+ * marker and doctor on the host.+ */+const HTTP_UNAVAILABLE_WHY = 'This gbrain server cannot open its brain; its host operator can see why with `gbrain doctor`.';+const HTTP_USER_MESSAGE = 'The gbrain memory server is running but cannot open its brain, so memory is offline. Can whoever runs that machine run `gbrain doctor` there? The server reconnects by itself once it is fixed.';++function httpStatusFix(): Action {+ return {+ argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'host_admin', requires_exclusive: false, user_message: HTTP_USER_MESSAGE,+ why: `Run on the brain host: doctor names the cause and its fix. This server re-checks every ${HTTP_STATUS_RETRY_AFTER_S} s and serves the full tool list once the brain opens; then re-list tools or reconnect.`,+ verify: { mcp: { tool: STATUS_TOOL_NAME, arguments: {} } }, docs: 'docs/mcp/DEPLOY.md#status-only-mode',+ };+}++/**+ * The unauthenticated HTTP status payload, built from an allowlist (never by+ * redacting the stdio payload): no path, PID, config or repair detail, and+ * the reason collapsed to `unavailable`.+ */+export function httpStatusPayload(): Record<string, unknown> {+ return {+ status: 'unavailable', reason: 'unavailable', why: HTTP_UNAVAILABLE_WHY,+ fix: renderAction(httpStatusFix(), HTTP_STATUS_RENDER), user_message: HTTP_USER_MESSAGE,+ retry_after_s: HTTP_STATUS_RETRY_AFTER_S, contract_version: 1,+ };+}++/** The `serve_status_only` error envelope for HTTP (OAuth/admin routes and any tool but gbrain_status). */+export function httpStatusEnvelope(tool?: string): Record<string, unknown> {+ const e = opError('serve_status_only', tool ? `${HTTP_UNAVAILABLE_WHY} ${tool} is unavailable until it can.` : HTTP_UNAVAILABLE_WHY,+ `Tell the user what user_message says; retry after ${HTTP_STATUS_RETRY_AFTER_S} s.`, { reason: 'unavailable', why: HTTP_UNAVAILABLE_WHY, fix: httpStatusFix() });+ return { ...toAgentError(e, { transport: 'http', ...(tool ? { op: tool } : {}), render: HTTP_STATUS_RENDER }), user_message: HTTP_USER_MESSAGE, retry_after_s: HTTP_STATUS_RETRY_AFTER_S };+}/** The `gbrain_status` tool result: {status, reason, why, fix, user_message, …}. */-export function statusPayload(state: StatusModeState): Record<string, unknown> {+export function statusPayload(state: StatusModeState, t: StatusTransport = 'stdio'): Record<string, unknown> {if (state.recovered) {return {status: 'recovered', reason: state.reason,- why: `The brain is open now; the full tool list replaced gbrain_status (tools/list_changed was sent). ${RESTART_NOTE}`,+ why: t === 'http'+ ? 'The brain is open now and this server serves the full tool list. Re-list tools or restart this MCP connection (an HTTP server cannot push tools/list_changed to this client).'+ : `The brain is open now; the full tool list replaced gbrain_status (tools/list_changed was sent). ${restartNote(t)}`,contract_version: 1,};}+ if (t === 'http') return httpStatusPayload();const { fix, user_message, decisions, plan } = statusFix(state);return {status: 'unavailable',@@ -270,6 +348,12 @@ export const STATUS_TOOL_DEF = {annotations: { title: 'gbrain status (status-only mode)', readOnlyHint: true },};+/** The same tool on an HTTP status server: no host detail; the server re-checks on its own. */+export const HTTP_STATUS_TOOL_DEF = {+ ...STATUS_TOOL_DEF,+ description: 'This gbrain server is running in status-only mode: it cannot open its brain. Call this for what to tell the user; the server re-checks every 5 s, and once this reports recovered, re-list tools or reconnect for the full tool list.',+};+/*** One recovery attempt from inside a tool call: re-probe (file reads only);* when nothing blocks, touch the lazy engine so its gated reconnect runs@@ -289,12 +373,13 @@ export async function attemptStatusRecovery(engine: { getConfig(key: string): Pr}/** `gbrain_status` as an MCP result (never isError: the status IS the answer). */-export function statusToolResult(state: StatusModeState): ToolResultShape {- return { content: [{ type: 'text', text: JSON.stringify(statusPayload(state), null, 2) }] };+export function statusToolResult(state: StatusModeState, t: StatusTransport = 'stdio'): ToolResultShape {+ return { content: [{ type: 'text', text: JSON.stringify(statusPayload(state, t), null, 2) }] };}/** Any other tool while still in status mode: one error block naming gbrain_status. */-export function statusModeErrorResult(state: StatusModeState, tool: string): ToolResultShape {+export function statusModeErrorResult(state: StatusModeState, tool: string, t: StatusTransport = 'stdio'): ToolResultShape {+ if (t === 'http') return { content: [{ type: 'text', text: JSON.stringify(httpStatusEnvelope(tool), null, 2) }], isError: true };const { fix } = statusFix(state);const e = opError('serve_status_only', `${statusHeadline(state)} ${tool} is unavailable until it can.`,'Call gbrain_status for the cause, the fix and what to tell the user.', { reason: state.reason, fix });@@ -302,6 +387,7 @@ export function statusModeErrorResult(state: StatusModeState, tool: string): Too}/** Line appended to the initialize instructions in status mode. */-export function statusInstructionLine(state: StatusModeState): string {+export function statusInstructionLine(state: StatusModeState, t: StatusTransport = 'stdio'): string {+ if (t === 'http') return `STATUS-ONLY MODE: ${HTTP_UNAVAILABLE_WHY} Only gbrain_status is available: call it for what to tell the user. This server re-checks every ${HTTP_STATUS_RETRY_AFTER_S} s; once gbrain_status reports recovered, re-list tools or reconnect.`;return `STATUS-ONLY MODE: ${statusHeadline(state)} Only gbrain_status is available: call it for the fix and what to tell the user. The full tool list returns (tools/list_changed) once the brain opens.`;}