@brainbox-labs/sdk 0.0.0-stage → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,148 @@
1
+ import { ContextTool as ContextTool$1, ContextToolExecution, ContextToolInputSchema } from '@brainbox-labs/types';
2
+
3
+ interface ContextTool extends ContextTool$1 {
4
+ /**
5
+ * Which project this tool was synced from. Only set in tenant-key,
6
+ * multi-project sync mode — lets an agent (or dispatch) tell overlay
7
+ * tools from base tools instead of merging them into one anonymous list.
8
+ */
9
+ sourceProject?: {
10
+ projectId: string;
11
+ role: 'overlay' | 'base' | 'project';
12
+ };
13
+ }
14
+ /**
15
+ * SQL connector client — available in tool handlers as ctx.sql.
16
+ * Specific to the SQL connector. Future connectors (REST, MongoDB, etc.)
17
+ * will expose their own typed clients on ctx.
18
+ */
19
+ interface SqlClient {
20
+ /** Execute a parameterized SQL query, returning rows. Params are positional ($1, $2...). */
21
+ query(sql: string, params?: unknown[]): Promise<unknown[]>;
22
+ }
23
+ /** Context passed to middleware and tool handlers. */
24
+ interface ToolContext {
25
+ /**
26
+ * SQL connector client (available when connectors.sql is configured).
27
+ * Named ctx.sql — not ctx.db — to be explicit that it's the SQL connector.
28
+ * Future connectors will add ctx.rest, ctx.mongo, etc.
29
+ */
30
+ sql: SqlClient;
31
+ /** The SQL/query string from the approved model — for auto-tier and enhanced overrides. */
32
+ defaultQuery?: string;
33
+ /** Tool name being called. */
34
+ toolName: string;
35
+ /**
36
+ * HTTP headers from the incoming MCP request (Authorization, X-Tenant-ID, etc.).
37
+ * This is how middleware accesses end-user auth tokens for multi-tenant scenarios.
38
+ */
39
+ headers: Record<string, string | string[] | undefined>;
40
+ /** Arbitrary data set by middleware (e.g. user, tenantId). Use index signature to add custom fields. */
41
+ [key: string]: unknown;
42
+ }
43
+ /**
44
+ * A catch-all executor for tools that don't have a per-tool override and aren't auto-tier SQL.
45
+ * Used by NoSQL, REST, and other connector types where the user supplies query logic.
46
+ */
47
+ type CustomExecutor = (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
48
+ type MiddlewareFn = (ctx: ToolContext, next: () => Promise<void>) => Promise<void>;
49
+ type ToolHandlerFn = (params: Record<string, unknown>, ctx: ToolContext) => Promise<unknown>;
50
+
51
+ interface MCPOptions {
52
+ /** BrainBox API key (bb_...) */
53
+ apiKey: string;
54
+ /**
55
+ * Project name/slug — same value as BRAINBOX_PROJECT in .env. Resolved to a
56
+ * project ID on startup. Omit for a tenant key (`bb_tenant_...`): the
57
+ * overlay + readable base projects are discovered automatically instead.
58
+ */
59
+ project?: string;
60
+ /**
61
+ * Connector configuration. Each key is a connector type.
62
+ * SQL is the first supported connector; REST, MongoDB, etc. will be added here.
63
+ */
64
+ connectors?: {
65
+ /** SQL connector (Postgres, MySQL, etc.). Required for auto-tier SQL tools. */
66
+ sql?: {
67
+ url: string;
68
+ };
69
+ /**
70
+ * Custom connector: a catch-all executor for tools not served by the SQL connector.
71
+ * Used for NoSQL, REST, or any data source where the user supplies query logic.
72
+ * Receives the tool name and arguments; returns the result.
73
+ */
74
+ custom?: {
75
+ execute: CustomExecutor;
76
+ };
77
+ };
78
+ /**
79
+ * Include brain (domain model) tools. Default: true.
80
+ * Set to false to exclude brain tools — useful for A/B experimentation.
81
+ */
82
+ brain?: boolean;
83
+ /** BrainBox base URL (no /api suffix). Defaults to https://ctx.brainbox-ai.app. For local dev: http://localhost:5002 */
84
+ apiUrl?: string;
85
+ /**
86
+ * How often to poll BrainBox for updated tool definitions (ms).
87
+ * Default: undefined — no polling, only the initial fetch on startup.
88
+ * Future: Firebase push notifications will replace polling.
89
+ */
90
+ pollIntervalMs?: number;
91
+ /**
92
+ * When true, custom tools without an override are registered and return a clear
93
+ * error when called. Default: false — unimplemented tools are excluded entirely.
94
+ */
95
+ serveUnimplementedTools?: boolean;
96
+ }
97
+ interface StartOptions {
98
+ port?: number;
99
+ }
100
+ declare class MCP {
101
+ private readonly middlewares;
102
+ private readonly overrides;
103
+ private readonly disabled;
104
+ private readonly syncCallbacks;
105
+ private readonly sqlClient;
106
+ private readonly customExecutor;
107
+ private readonly opts;
108
+ private sync;
109
+ private brainExecutor;
110
+ constructor(options: MCPOptions);
111
+ /** Register middleware that runs before every tool call. */
112
+ use(fn: MiddlewareFn): this;
113
+ /** Register a custom or enhanced tool handler. */
114
+ tool(name: string, fn: ToolHandlerFn): this;
115
+ /** Explicitly exclude a tool from the MCP server (won't appear in tools/list). */
116
+ disable(name: string): this;
117
+ /** Register a callback fired when tool definitions are refreshed. */
118
+ onSync(fn: (tools: ContextTool[]) => void): this;
119
+ /** Fetch tool definitions and start the MCP server. */
120
+ start(opts?: StartOptions): Promise<void>;
121
+ private activeTools;
122
+ private logStartupTable;
123
+ }
124
+
125
+ /**
126
+ * @brainbox-labs/sdk/serve — server-builder surface for the BrainBox Context Layer.
127
+ *
128
+ * Hosts the MCP server class, connector types, and middleware/handler types.
129
+ * @packageDocumentation
130
+ */
131
+
132
+ type index_ContextTool = ContextTool;
133
+ declare const index_ContextToolExecution: typeof ContextToolExecution;
134
+ declare const index_ContextToolInputSchema: typeof ContextToolInputSchema;
135
+ type index_CustomExecutor = CustomExecutor;
136
+ type index_MCP = MCP;
137
+ declare const index_MCP: typeof MCP;
138
+ type index_MCPOptions = MCPOptions;
139
+ type index_MiddlewareFn = MiddlewareFn;
140
+ type index_SqlClient = SqlClient;
141
+ type index_StartOptions = StartOptions;
142
+ type index_ToolContext = ToolContext;
143
+ type index_ToolHandlerFn = ToolHandlerFn;
144
+ declare namespace index {
145
+ export { type index_ContextTool as ContextTool, index_ContextToolExecution as ContextToolExecution, index_ContextToolInputSchema as ContextToolInputSchema, type index_CustomExecutor as CustomExecutor, index_MCP as MCP, type index_MCPOptions as MCPOptions, type index_MiddlewareFn as MiddlewareFn, type index_SqlClient as SqlClient, type index_StartOptions as StartOptions, type index_ToolContext as ToolContext, type index_ToolHandlerFn as ToolHandlerFn };
146
+ }
147
+
148
+ export { type ContextTool as C, type MCPOptions as M, type SqlClient as S, type ToolContext as T, MCP as a, type CustomExecutor as b, type MiddlewareFn as c, type StartOptions as d, type ToolHandlerFn as e, index as i };
@@ -0,0 +1,387 @@
1
+ import { AnalysisDepth, GrepWikiArgs, GrepWikiResult, McpToolDefinition, GetIndexArgs, GetIndexResult, ListLearningsResult, ListPersonalPagesArgs, ListPersonalPagesResult, GetRecentChangesArgs, GetRecentChangesResult, RecallDomainArgs, ListTracesArgs, ListTracesResult, RecallTracesArgs, ListWikiPagesArgs, ListWikiPagesResult, RecallWikiArgs, CheckContextDraftArgs, CheckContextDraftResult, GetTraceArgs, GetWikiPageArgs, ResearchTaskArgs, ResearchTaskResult, ListSkillsResult, GetSkillArgs, GetSkillResult, CreateLearningArgs, CreateLearningResult, RetireLearningArgs, RetireLearningResult, ReportContextGapArgs, ReportContextGapResult, SaveDomainArgs, SaveDomainResult, ProcessEventArgs, CreateSkillArgs, CreateSkillResult, ArchiveWikiPageArgs, ArchiveResult, ArchiveTraceArgs, SaveWikiPageArgs, AppendWikiPageResult, SaveWikiPageResult, SavePersonalPageArgs, SavePersonalPageResult, AppendWikiPageArgs, FlagPersonalPageForReviewArgs, Project } from '@brainbox-labs/types';
2
+ import { M as MCPOptions, a as MCP } from './index-qV0gq2eJ.js';
3
+ export { i as serve } from './index-qV0gq2eJ.js';
4
+
5
+ interface IngestPostgresOptions {
6
+ connectionString: string;
7
+ /** Restrict introspection to these table names. */
8
+ tables?: string[];
9
+ /** Dialect tag passed to the server (defaults to 'postgres'). */
10
+ dialect?: string;
11
+ }
12
+ interface IngestTrinoOptions {
13
+ /** trino://user[:password]@host[:port]/catalog[/schema] connection URL. */
14
+ connectionString: string;
15
+ /** Restrict introspection to these table names. */
16
+ tables?: string[];
17
+ /** Dialect tag passed to the server (defaults to 'trino'). */
18
+ dialect?: string;
19
+ }
20
+ interface IngestAthenaOptions {
21
+ /** athena://region/database[?catalog=AwsDataCatalog&workgroup=primary&output=s3://bucket/prefix] connection URL.
22
+ * AWS credentials come from the standard AWS SDK credential chain, not the URL. */
23
+ connectionString: string;
24
+ /** Restrict introspection to these table names. */
25
+ tables?: string[];
26
+ /** Dialect tag passed to the server (defaults to 'athena'). */
27
+ dialect?: string;
28
+ }
29
+ interface IngestSkillOptions {
30
+ /** Skill name — shown in the agent's skill list. */
31
+ name: string;
32
+ /** Skill description — used for skill discovery/routing. */
33
+ description: string;
34
+ /** Glob patterns matching source files to merge into the skill (md, txt, html, pdf, docx). */
35
+ sources: string[];
36
+ }
37
+ interface IngestProfileOptions {
38
+ /**
39
+ * 'cardinality': distinctCount + nullRate + numeric/string stats only.
40
+ * 'full': also collects enum values (for low-cardinality columns) and JSON key shapes.
41
+ */
42
+ mode: 'cardinality' | 'full';
43
+ /** Max rows to sample per table for sample-based stats (default: 10 000). */
44
+ sampleRows?: number;
45
+ /** "tablename.columnname" pairs to exclude from profiling. */
46
+ skipColumns?: string[];
47
+ }
48
+ interface IngestOptions {
49
+ postgres?: IngestPostgresOptions;
50
+ /** Trino source — mutually exclusive with `postgres` and `athena`. Introspection covers tables
51
+ * and columns only; Trino has no enforced PKs, FKs, or indexes. */
52
+ trino?: IngestTrinoOptions;
53
+ /** Athena source — mutually exclusive with `postgres` and `trino`. Introspection covers tables
54
+ * and columns only; like Trino, Athena has no enforced PKs, FKs, or indexes. */
55
+ athena?: IngestAthenaOptions;
56
+ /** SQL files or directories to parse and submit alongside the schema. */
57
+ sql?: string[];
58
+ /**
59
+ * Glob patterns matching doc files (md, txt, html, pdf, docx).
60
+ * PDF and DOCX are auto-converted to markdown; html is passed as-is.
61
+ */
62
+ docs?: string[];
63
+ /**
64
+ * Directory where converted markdown files (from PDF and DOCX sources) are written.
65
+ * Created automatically if it does not exist. Only applies when `docs` is set.
66
+ */
67
+ convertedOutputDir?: string;
68
+ /** Free-form text to attach as an inline document. */
69
+ text?: string;
70
+ /**
71
+ * Merge one or more source files into a single Agent Skill. Resolves synchronously —
72
+ * unlike the other source kinds, there is no context generate/poll/activate step.
73
+ */
74
+ skill?: IngestSkillOptions;
75
+ /**
76
+ * How deeply to analyse `docs`/`text` sources. Applied to every source in this
77
+ * ingest that doesn't set its own depth; the server falls back to 'shallow' when unset.
78
+ */
79
+ analysisDepth?: AnalysisDepth;
80
+ /**
81
+ * Profile column data from the database. Only applies when `postgres`, `trino`, or `athena` is set.
82
+ * Supports Postgres, MySQL, SQLite, DuckDB, Trino, and Athena via the connection string dialect.
83
+ */
84
+ profile?: IngestProfileOptions;
85
+ /** Free-form description of this ingest. Not sent to the server today; reserved for
86
+ * future use (e.g. a commit-message-style field on the connector draft). */
87
+ message?: string;
88
+ /** Per-stage poll timeout in ms. Defaults to 300_000 (5 min). */
89
+ timeoutMs?: number;
90
+ /** Stop after the context is `ready` — skip activation so a reviewer can curate first. */
91
+ reviewOnly?: boolean;
92
+ /** Re-process the last connector draft instead of uploading sources again. */
93
+ force?: boolean;
94
+ /**
95
+ * Stop after creating the connector draft — do not create a context or activate a version.
96
+ * Useful for inspecting what would be submitted before committing to a full ingest.
97
+ */
98
+ dryRun?: boolean;
99
+ }
100
+ interface IngestStageResult {
101
+ kind: 'sql' | 'docs' | 'skill';
102
+ connectorDraftId: string;
103
+ /** Absent when `dryRun: true`. */
104
+ contextId?: string;
105
+ /** Present unless `reviewOnly: true` or `dryRun: true`. */
106
+ version?: number;
107
+ /** Present unless `reviewOnly: true` or `dryRun: true`. */
108
+ layerId?: string;
109
+ /** Non-fatal issues collected during this stage (e.g. SQL files that failed to parse). */
110
+ warnings?: string[];
111
+ }
112
+ interface IngestResult {
113
+ stages: IngestStageResult[];
114
+ }
115
+ /**
116
+ * Thrown when a later stage fails after an earlier stage already activated a new
117
+ * version. `completed` carries the stages that did succeed so callers can decide
118
+ * whether to compensate (e.g. roll back, alert, retry just the failed stage).
119
+ */
120
+ declare class IngestPartialFailureError extends Error {
121
+ readonly completed: IngestStageResult[];
122
+ readonly failedKind: IngestStageResult['kind'];
123
+ readonly cause: unknown;
124
+ constructor(failedKind: IngestStageResult['kind'], completed: IngestStageResult[], cause: unknown);
125
+ }
126
+
127
+ declare function isTenantKey(apiKey: string): boolean;
128
+ interface ProjectView {
129
+ projectId: string;
130
+ name?: string;
131
+ role: 'overlay' | 'base' | 'project';
132
+ /** One-line description of what the brain covers, when the project has one. */
133
+ description?: string;
134
+ /** Alternate names / domain terms for the brain. */
135
+ aliases?: string[];
136
+ }
137
+ interface TenantView {
138
+ overlay: ProjectView;
139
+ bases: ProjectView[];
140
+ }
141
+
142
+ interface BrainExecutorCallOptions {
143
+ /**
144
+ * Target a specific project by ID for this call. Only meaningful for
145
+ * tenant-key handles — routes a read to one of the tenant's readable base
146
+ * projects instead of the default (overlay). Write tools ignore this and
147
+ * always target the overlay. Single-project (non-tenant) executors throw
148
+ * if a projectId other than their bound project is requested.
149
+ */
150
+ projectId?: string;
151
+ }
152
+ /**
153
+ * A non-2xx brain dispatch response. `message` keeps the legacy
154
+ * `Brain dispatch <status> (<tool>): <body>` text so existing regex checks still match.
155
+ * `code` is the server's error code when the body carries one (e.g. 'VERSION_CONFLICT' from
156
+ * save_wiki_page with a stale baseVersion), else 'CONFLICT' for 409 and `HTTP_<status>` otherwise.
157
+ */
158
+ declare class BrainDispatchError extends Error {
159
+ readonly status: number;
160
+ readonly toolName: string;
161
+ readonly body: string;
162
+ readonly code: string;
163
+ /** The JSON error body, when there is one (e.g. `currentVersion` on a VERSION_CONFLICT). */
164
+ readonly details?: Record<string, unknown>;
165
+ /**
166
+ * True when the same call can succeed later: 429, 502, 503, 504, and the process_event 409
167
+ * for a source.externalId that is still being processed. Other 409s (VERSION_CONFLICT, an
168
+ * archived skill) need the caller to change something first, so they are not retryable.
169
+ */
170
+ readonly retryable: boolean;
171
+ /** Seconds from the Retry-After header, when the server sent one. */
172
+ readonly retryAfter?: number;
173
+ constructor(status: number, toolName: string, body: string, opts?: {
174
+ message?: string;
175
+ retryAfter?: number;
176
+ });
177
+ }
178
+
179
+ interface LocalGrepWikiArgs extends GrepWikiArgs {
180
+ /** Narrow to this namespace and everything under it. Mutually exclusive with `tag`. */
181
+ namespace?: string;
182
+ }
183
+ interface LocalGrepWikiResult extends GrepWikiResult {
184
+ /**
185
+ * True when older pages of some kind may not have been searched: the kind has
186
+ * at least ~1000 pages (the deepest the server's list cursor goes), or the
187
+ * server can't page at all (before context-layer #409) and returned a full
188
+ * first page. Narrow with `tag`, `namespace` or `kind` to cover such a wiki.
189
+ */
190
+ pagesTruncated: boolean;
191
+ }
192
+
193
+ /**
194
+ * One callable verb on a brain namespace (e.g. `brain.recall.get_index`).
195
+ * Args are optional — tools with no `required` parameters can be called with `()`.
196
+ * `callOpts` is only meaningful for tenant-key handles: pass `{ projectId }`
197
+ * to target a specific readable base project instead of the default overlay.
198
+ */
199
+ type VerbHandler<Args extends object = Record<string, unknown>, Result = unknown> = (args?: Args, callOpts?: BrainExecutorCallOptions) => Promise<Result>;
200
+ /**
201
+ * A tool catalog entry as exposed by `.asTools()`. Carries the MCP-format
202
+ * schema plus a bound `execute` so a single array drops straight into an
203
+ * agent loop without a per-tool dispatch table.
204
+ *
205
+ * for (const block of response.content) {
206
+ * if (block.type === 'tool_use') {
207
+ * const tool = tools.find(t => t.name === block.name);
208
+ * const result = await tool.execute(block.input);
209
+ * }
210
+ * }
211
+ *
212
+ * Anthropic/OpenAI tool params accept extra fields structurally, so this
213
+ * still works as-is when spread into `tools: [...]`.
214
+ */
215
+ interface VerbTool extends McpToolDefinition {
216
+ execute: VerbHandler;
217
+ }
218
+
219
+ type BrainRecall = {
220
+ get_index: VerbHandler<GetIndexArgs, GetIndexResult>;
221
+ list_learnings: VerbHandler<Record<string, never>, ListLearningsResult>;
222
+ list_personal_pages: VerbHandler<ListPersonalPagesArgs, ListPersonalPagesResult>;
223
+ get_recent_changes: VerbHandler<GetRecentChangesArgs, GetRecentChangesResult>;
224
+ recall_domain: VerbHandler<RecallDomainArgs, unknown>;
225
+ list_traces: VerbHandler<ListTracesArgs, ListTracesResult>;
226
+ recall_traces: VerbHandler<RecallTracesArgs, unknown>;
227
+ list_wiki_pages: VerbHandler<ListWikiPagesArgs, ListWikiPagesResult>;
228
+ recall_wiki: VerbHandler<RecallWikiArgs, unknown>;
229
+ /** Client-side: lists + fetches pages and greps locally. Result adds `pagesTruncated`. */
230
+ grep_wiki: VerbHandler<LocalGrepWikiArgs, LocalGrepWikiResult>;
231
+ check_context_draft: VerbHandler<CheckContextDraftArgs, CheckContextDraftResult>;
232
+ get_trace: VerbHandler<GetTraceArgs, unknown>;
233
+ get_wiki_page: VerbHandler<GetWikiPageArgs, unknown>;
234
+ research_task: VerbHandler<ResearchTaskArgs, ResearchTaskResult>;
235
+ list_skills: VerbHandler<Record<string, never>, ListSkillsResult>;
236
+ get_skill: VerbHandler<GetSkillArgs, GetSkillResult>;
237
+ asTools(): VerbTool[];
238
+ /** Like {@link asTools} minus tools this org has switched off (server-reported). Local verbs such as grep_wiki are always kept. */
239
+ asEnabledTools(): Promise<VerbTool[]>;
240
+ };
241
+ type BrainUpdate = {
242
+ create_learning: VerbHandler<CreateLearningArgs, CreateLearningResult>;
243
+ retire_learning: VerbHandler<RetireLearningArgs, RetireLearningResult>;
244
+ report_context_gap: VerbHandler<ReportContextGapArgs, ReportContextGapResult>;
245
+ save_domain: VerbHandler<SaveDomainArgs, SaveDomainResult>;
246
+ /**
247
+ * `source.externalId` is the idempotency key: a retry with the same externalId returns the
248
+ * existing trace instead of writing a second one. A concurrent duplicate that is still being
249
+ * processed is rejected with a 409, surfaced as `BrainDispatchError` (`code: 'CONFLICT'`,
250
+ * `retryable: true`); retry after a short backoff and you get the winner's trace.
251
+ */
252
+ process_event: VerbHandler<ProcessEventArgs, unknown>;
253
+ /**
254
+ * `onConflict: 'update'` replaces an existing same-named skill's body as a new version instead
255
+ * of failing; the result's `outcome` is 'created' or 'updated' and `version` is the new version.
256
+ * Refused if the skill is archived or has a pending proposed revision.
257
+ */
258
+ create_skill: VerbHandler<CreateSkillArgs, CreateSkillResult>;
259
+ /**
260
+ * Moves a synthesis wiki page into pending deletion (hidden from every read at once, purged
261
+ * after 7 days unless a person restores it). Hidden unless the org enables `agentArchiveTools`,
262
+ * so asEnabledTools() leaves it out by default.
263
+ */
264
+ archive_wiki_page: VerbHandler<ArchiveWikiPageArgs, ArchiveResult>;
265
+ /** Same as {@link archive_wiki_page} for a trace. Also gated by `agentArchiveTools`. */
266
+ archive_trace: VerbHandler<ArchiveTraceArgs, ArchiveResult>;
267
+ /** With `mode: 'append'` adds `body` to the end of page `id` and returns {@link AppendWikiPageResult}. */
268
+ save_wiki_page: {
269
+ (args: SaveWikiPageArgs & {
270
+ mode: 'append';
271
+ }, callOpts?: BrainExecutorCallOptions): Promise<AppendWikiPageResult>;
272
+ (args?: SaveWikiPageArgs, callOpts?: BrainExecutorCallOptions): Promise<SaveWikiPageResult>;
273
+ };
274
+ /** With `id` + `flagForReview: true` and no title/body, flags the page without changing it. */
275
+ save_personal_page: VerbHandler<SavePersonalPageArgs, SavePersonalPageResult>;
276
+ /** @deprecated Use `save_wiki_page({ mode: 'append', id, body })`. Not listed by asTools(). */
277
+ append_wiki_page: VerbHandler<AppendWikiPageArgs, AppendWikiPageResult>;
278
+ /** @deprecated Use `save_personal_page({ id, flagForReview: true })`. Not listed by asTools(). */
279
+ flag_personal_page_for_review: VerbHandler<FlagPersonalPageForReviewArgs, SavePersonalPageResult & {
280
+ flagged: true;
281
+ }>;
282
+ asTools(): VerbTool[];
283
+ asEnabledTools(): Promise<VerbTool[]>;
284
+ };
285
+ /**
286
+ * `brain.projects.*` — org-level project discovery and creation. Needs no
287
+ * `project` on the handle. `create` requires a write-scoped org/project key (tenant
288
+ * keys are refused); renaming/deleting projects and all tenant management are
289
+ * admin-tier and not reachable with an API key.
290
+ */
291
+ type BrainProjects = {
292
+ /** Projects this key can address, role-tagged, with description/aliases. Works for every key type. */
293
+ list(): Promise<ProjectView[]>;
294
+ create(name: string): Promise<Project>;
295
+ };
296
+ interface BrainBoxOptions {
297
+ /** BrainBox API key (bb_...). */
298
+ apiKey: string;
299
+ /** Organization slug. The API key is org-scoped; this is asserted on resolve. */
300
+ org: string;
301
+ /** Project (brain) slug. Omit to address the org-level default brain. */
302
+ project?: string;
303
+ /** BrainBox base URL (no /api suffix). Defaults to https://ctx.brainbox-ai.app. */
304
+ apiUrl?: string;
305
+ }
306
+ /**
307
+ * Root handle to a BrainBox brain. Holds credentials and addressing for the
308
+ * server-builder (`brain.serve`), read verbs (`brain.recall.*`), and write
309
+ * verbs (`brain.update.*`).
310
+ *
311
+ * Project ID resolution is lazy — the first `recall`/`update` call resolves
312
+ * the project slug; a successful resolve is cached, a failed resolve is
313
+ * cleared so the next call retries instead of replaying the rejection.
314
+ */
315
+ declare class BrainBox {
316
+ readonly options: BrainBoxOptions;
317
+ readonly serve: BrainBoxServe;
318
+ readonly recall: BrainRecall;
319
+ readonly update: BrainUpdate;
320
+ readonly projects: BrainProjects;
321
+ private projectIdPromise?;
322
+ private tenantViewPromise?;
323
+ private discoveryPromise?;
324
+ private executor?;
325
+ constructor(options: BrainBoxOptions);
326
+ /**
327
+ * GET /api/projects for any key type: the addressable projects plus the tools
328
+ * this org has switched off. A successful fetch is cached; a failed one is
329
+ * cleared so the next call retries.
330
+ */
331
+ private getDiscovery;
332
+ /** Tenant-key agents call this first to find the base Brains they can pass as `projectId`. */
333
+ private listProjectsTool;
334
+ /** Best-effort: discovery failing must never hide tools, so an error means "nothing disabled". */
335
+ private getDisabledTools;
336
+ /** Drops tools this org has switched off. Local verbs (grep_wiki) never hit the gated server tool, so they stay. */
337
+ private enabledTools;
338
+ /**
339
+ * A gated tool fails with a bare dispatch 403. Only on that failure, look up
340
+ * the org's disabled set (no extra request on the happy path) and replace the
341
+ * error with a clear one if the tool is in it.
342
+ */
343
+ private explainDisabledTool;
344
+ private client;
345
+ /** Tenant keys see projects through the overlay/base view, and POST /projects returns their existing overlay instead of creating. */
346
+ private assertNotTenantKey;
347
+ /**
348
+ * Ingest sources into this brain — equivalent to running `brainbox meta ingest`
349
+ * + `repo push` + `repo meta create` + `repo meta approve`. Blocks until each
350
+ * stage's context is activated and a new version is published.
351
+ *
352
+ * For tenant keys, always targets the tenant's overlay project — `project`
353
+ * on the parent {@link BrainBox} handle is ignored, since base projects are
354
+ * shared, read-only brains that a tenant must never write into. For
355
+ * project/org keys, requires `project` on the parent handle.
356
+ */
357
+ ingest(opts: IngestOptions): Promise<IngestResult>;
358
+ private getExecutor;
359
+ /** Best-effort scope label from the key prefix alone — logged before any network call. */
360
+ private logDeclaredScope;
361
+ /** Backend-confirmed scope, logged once a resolving call (tenant view / project lookup) succeeds. */
362
+ private logConfirmedScope;
363
+ /**
364
+ * Resolves a tenant key's view (overlay + readable bases) from the cached GET /api/projects.
365
+ * A successful resolve is cached; a failed resolve is cleared so the next call
366
+ * retries instead of replaying the rejection.
367
+ */
368
+ private getTenantView;
369
+ private resolveProjectId;
370
+ }
371
+ /** `brain.serve.*` — server-builder factories scoped to a brain handle. */
372
+ declare class BrainBoxServe {
373
+ private readonly handle;
374
+ constructor(handle: BrainBoxOptions);
375
+ /**
376
+ * Build an MCP server bound to this brain. Returns an unstarted MCP
377
+ * instance — call `.start({ port })` to begin serving.
378
+ *
379
+ * A `project` is required on the parent {@link BrainBox} handle until
380
+ * org-level default brains are supported by the server runtime — except
381
+ * for tenant keys, which discover their overlay + base projects at
382
+ * `start()` time via GET /api/projects instead.
383
+ */
384
+ mcp(opts?: Omit<MCPOptions, 'apiKey' | 'project' | 'apiUrl'>): MCP;
385
+ }
386
+
387
+ export { BrainBox, type BrainBoxOptions, BrainBoxServe, BrainDispatchError, type BrainProjects, type IngestOptions, IngestPartialFailureError, type IngestPostgresOptions, type IngestResult, type IngestStageResult, type LocalGrepWikiArgs, type LocalGrepWikiResult, type ProjectView, type TenantView, isTenantKey };