import { Context, Deferred, Effect, Option, Result, Schema, Semaphore } from "effect";import { generateKeyBetween } from "fractional-indexing";import { StorageError, typedAdapter, type DBAdapter, type DBSchema, type DBTransactionAdapter, type StorageFailure, type TypedAdapter,} from "@executor-js/storage-core"; import { pluginBlobStore, type BlobStore,} from "./blob";import { ConnectionProviderState, ConnectionRef, ConnectionRefreshError, type ConnectionProvider, type ConnectionRefreshResult, type CreateConnectionInput, type UpdateConnectionTokensInput,} from "./connections";import { coreSchema, isToolPolicyAction, type ConnectionRow, type CoreSchema, type DefinitionsInput, type SecretRow, type SourceInput, type SourceRow, type ToolAnnotations, type ToolPolicyRow, type ToolRow,} from "./core-schema";import { ElicitationDeclinedError, ElicitationResponse, FormElicitation, type ElicitationHandler, type ElicitationRequest,} from "./elicitation";import { ConnectionNotFoundError, ConnectionProviderNotRegisteredError, ConnectionReauthRequiredError, ConnectionRefreshNotSupportedError, NoHandlerError, PluginNotLoadedError, SecretOwnedByConnectionError, SourceRemovalNotAllowedError, ToolBlockedError, ToolInvocationError, ToolNotFoundError,} from "./errors";import { ConnectionId, ScopeId, SecretId, ToolId } from "./ids";import { makeOAuth2Service } from "./oauth-service";import type { OAuthService } from "./oauth";import { comparePolicyRow, isValidPattern, resolveToolPolicy, rowToToolPolicy, type CreateToolPolicyInput, type PolicyMatch, type ToolPolicy, type UpdateToolPolicyInput,} from "./policies";import type { AnyPlugin, Elicit, PluginCtx, PluginExtensions, StaticSourceDecl, StaticToolDecl, StorageDeps,} from "./plugin";import type { Scope } from "./scope";import { SecretRef, SetSecretInput, type SecretProvider,} from "./secrets";import { ToolSchema, type Source, type SourceDetectionResult, type Tool, type ToolListFilter,} from "./types";import { buildToolTypeScriptPreview } from "./schema-types";import { scopeAdapter } from "./scoped-adapter"; // ---------------------------------------------------------------------------// Elicitation handler — set once at `createExecutor({ onElicitation })`// and threaded into every tool invocation. A tool that requests user// input mid-execution suspends the fiber and the handler decides how to// respond. Tools that never elicit simply don't trigger the handler.//// The "accept-all" sentinel is convenient for tests and CLI automation —// every elicitation request gets auto-accepted with an empty content// payload. For real interactive hosts, pass a real handler.//// Required at the executor level rather than per-invoke, so the// "what if a caller forgot to pass a handler" branch is structurally// impossible. Higher layers that need per-invocation handler control// (an MCP server bridging different per-client handlers, the execution// engine threading agent-loop callbacks) can pass an override via// `tools.invoke(id, args, { onElicitation })` — the executor-level// handler is the fallback, never null.// --------------------------------------------------------------------------- export type OnElicitation = ElicitationHandler | "accept-all"; export interface InvokeOptions { /** Override the executor-level handler for this single call. */ readonly onElicitation?: OnElicitation;} const acceptAllHandler: ElicitationHandler = () => Effect.succeed(new ElicitationResponse({ action: "accept" })); const resolveElicitationHandler = ( onElicitation: OnElicitation,): ElicitationHandler => onElicitation === "accept-all" ? acceptAllHandler : onElicitation; // ---------------------------------------------------------------------------// Executor — public surface. Every list/invoke/schema call is a direct// core-table query (for dynamic rows) unioned with the in-memory static// pool. No ToolRegistry, no SourceRegistry, no SecretStore services.// --------------------------------------------------------------------------- export type Executor<TPlugins extends readonly AnyPlugin[] = []> = { /** * Precedence-ordered scope stack this executor was configured with. * Innermost first. Consumers that need "the display scope" typically * pick `scopes.at(-1)` (outermost, e.g. the organization) or * `scopes[0]` (innermost, e.g. the current user-in-org) depending on * what they're rendering. */ readonly scopes: readonly Scope[]; readonly tools: { readonly list: ( filter?: ToolListFilter, ) => Effect.Effect<readonly Tool[], StorageFailure>; /** Fetch a tool's full schema view: JSON schemas with `$defs` * attached from the core `definition` table, plus TypeScript * preview strings rendered from them. Returns `null` for unknown * tool ids. */ readonly schema: ( toolId: string, ) => Effect.Effect<ToolSchema | null, StorageFailure>; /** Every `$defs` entry across every source, grouped by source id. * Used for bulk schema export and downstream TypeScript rendering. */ readonly definitions: () => Effect.Effect< Record<string, Record<string, unknown>>, StorageFailure >; readonly invoke: ( toolId: string, args: unknown, options?: InvokeOptions, ) => Effect.Effect< unknown, | ToolNotFoundError | ToolBlockedError | PluginNotLoadedError | NoHandlerError | ToolInvocationError | ElicitationDeclinedError | StorageFailure >; }; readonly sources: { readonly list: () => Effect.Effect<readonly Source[], StorageFailure>; readonly remove: ( sourceId: string, ) => Effect.Effect<void, SourceRemovalNotAllowedError | StorageFailure>; readonly refresh: (sourceId: string) => Effect.Effect<void, StorageFailure>; /** URL autodetection — fans out to every plugin's `detect` hook * (if declared), returns every high/medium/low-confidence match. * UI picks a winner from the list. */ readonly detect: ( url: string, ) => Effect.Effect<readonly SourceDetectionResult[], StorageFailure>; /** All `$defs` registered for a single source, keyed by def name. */ readonly definitions: ( sourceId: string, ) => Effect.Effect<Record<string, unknown>, StorageFailure>; }; readonly secrets: { readonly get: ( id: string, ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>; /** Fast-path existence check — hits the core `secret` routing table * only, never calls the provider. Use this for UI state ("secret * missing, prompt to add") to avoid keychain permission prompts * or 1password IPC roundtrips on a pre-flight check. */ readonly status: ( id: string, ) => Effect.Effect<"resolved" | "missing", StorageFailure>; readonly set: ( input: SetSecretInput, ) => Effect.Effect<SecretRef, StorageFailure>; /** Delete a bare (non-connection-owned) secret. Connection-owned * secrets are rejected with `SecretOwnedByConnectionError` — use * `connections.remove` instead. */ readonly remove: ( id: string, ) => Effect.Effect<void, SecretOwnedByConnectionError | StorageFailure>; readonly list: () => Effect.Effect<readonly SecretRef[], StorageFailure>; readonly providers: () => Effect.Effect<readonly string[]>; }; readonly connections: { readonly get: ( id: string, ) => Effect.Effect<ConnectionRef | null, StorageFailure>; readonly list: () => Effect.Effect<readonly ConnectionRef[], StorageFailure>; readonly create: ( input: CreateConnectionInput, ) => Effect.Effect< ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure >; readonly updateTokens: ( input: UpdateConnectionTokensInput, ) => Effect.Effect< ConnectionRef, ConnectionNotFoundError | StorageFailure >; readonly setIdentityLabel: ( id: string, label: string | null, ) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>; readonly accessToken: ( id: string, ) => Effect.Effect< string, | ConnectionNotFoundError | ConnectionProviderNotRegisteredError | ConnectionRefreshNotSupportedError | ConnectionReauthRequiredError | ConnectionRefreshError | StorageFailure >; readonly remove: (id: string) => Effect.Effect<void, StorageFailure>; readonly providers: () => Effect.Effect<readonly string[]>; }; /** Shared OAuth service. Hosts use this through the core HTTP OAuth group; * plugins see the same service as `ctx.oauth`. */ readonly oauth: OAuthService; readonly policies: { /** All policies visible across the executor's scope stack, sorted * by (innermost-scope-first, position ascending) — i.e. the order * in which they're evaluated by first-match-wins. */ readonly list: () => Effect.Effect<readonly ToolPolicy[], StorageFailure>; /** Create a new policy. Defaults to the top of the target scope's * list (highest precedence) when `position` is omitted. */ readonly create: ( input: CreateToolPolicyInput, ) => Effect.Effect<ToolPolicy, StorageFailure>; readonly update: ( input: UpdateToolPolicyInput, ) => Effect.Effect<ToolPolicy, StorageFailure>; readonly remove: (id: string) => Effect.Effect<void, StorageFailure>; /** Resolve the effective policy for a tool id by walking the scope- * stacked policy list with first-match-wins semantics. Returns * `undefined` when no rule matches (caller falls back to the * plugin's `resolveAnnotations` output). */ readonly resolve: ( toolId: string, ) => Effect.Effect<PolicyMatch | undefined, StorageFailure>; }; readonly close: () => Effect.Effect<void, StorageFailure>;} & PluginExtensions<TPlugins>; export interface ExecutorConfig< TPlugins extends readonly AnyPlugin[] = [],> { /** * Precedence-ordered scope stack. Innermost first; typical shape is * `[userInOrgScope, orgScope]`. Reads on scoped tables walk the * stack (first hit wins for shadow-by-id consumers like secrets and * blobs); writes require callers to name an explicit target scope. * Must be non-empty. */ readonly scopes: readonly Scope[]; readonly adapter: DBAdapter; readonly blobs: BlobStore; readonly plugins?: TPlugins; /** * How to respond when a tool requests user input mid-invocation. Pass * `"accept-all"` for tests / non-interactive hosts, or a handler * `(ctx) => Effect<ElicitationResponse>` for interactive ones. * Required at construction so per-invoke calls don't have to thread * an options arg. */ readonly onElicitation: OnElicitation;} // ---------------------------------------------------------------------------// collectSchemas — merge coreSchema with every plugin's declared schema.// Hosts call this and pass the result to the migration runner (or to// the adapter factory for backends that auto-migrate from a schema// manifest) before constructing the executor.// --------------------------------------------------------------------------- export const collectSchemas = ( plugins: readonly AnyPlugin[],): DBSchema => { const merged: Record<string, DBSchema[string]> = { ...coreSchema }; for (const plugin of plugins) { if (!plugin.schema) continue; for (const [modelKey, model] of Object.entries(plugin.schema)) { if (merged[modelKey]) { throw new Error( `Duplicate model "${modelKey}" contributed by plugin "${plugin.id}"` + ` (reserved by core or another plugin)`, ); } merged[modelKey] = model as DBSchema[string]; } } return merged;}; // ---------------------------------------------------------------------------// Row → public projection conversions// --------------------------------------------------------------------------- const rowToSource = (row: SourceRow): Source => ({ id: row.id, scopeId: row.scope_id, kind: row.kind, name: row.name, url: row.url ?? undefined, pluginId: row.plugin_id, canRemove: Boolean(row.can_remove), canRefresh: Boolean(row.can_refresh), canEdit: Boolean(row.can_edit), runtime: false,}); const staticDeclToSource = ( decl: StaticSourceDecl, pluginId: string,): Source => ({ id: decl.id, scopeId: undefined, kind: decl.kind, name: decl.name, url: decl.url, pluginId, canRemove: decl.canRemove ?? false, canRefresh: decl.canRefresh ?? false, canEdit: decl.canEdit ?? false, runtime: true,}); const decodeJsonColumn = (value: unknown): unknown => { if (value === null || value === undefined) return undefined; if (typeof value !== "string") return value; try { return JSON.parse(value); } catch { return value; }}; const rowToTool = ( row: ToolRow, annotations?: ToolAnnotations,): Tool => ({ id: row.id, sourceId: row.source_id, pluginId: row.plugin_id, name: row.name, description: row.description, inputSchema: decodeJsonColumn(row.input_schema), outputSchema: decodeJsonColumn(row.output_schema), annotations,}); const staticDeclToTool = ( source: StaticSourceDecl, tool: StaticToolDecl, pluginId: string,): Tool => ({ id: `${source.id}.${tool.name}`, sourceId: source.id, pluginId, name: tool.name, description: tool.description, inputSchema: tool.inputSchema, outputSchema: tool.outputSchema, annotations: tool.annotations,}); // ---------------------------------------------------------------------------// Dynamic-row writers — used by ctx.core.sources.register. Static sources// never touch these functions.// --------------------------------------------------------------------------- // Upsert shape: delete any existing source + tools + definitions for// `input.id` before creating fresh rows. Keeps replayable — boot-time// sync from executor.jsonc can call register() on rows that already// exist without tripping a UNIQUE constraint.const writeSourceInput = ( core: TypedAdapter<CoreSchema>, pluginId: string, input: SourceInput,): Effect.Effect<void, StorageFailure> => Effect.gen(function* () { yield* deleteSourceById(core, input.id, input.scope); const now = new Date(); yield* core.create({ model: "source", data: { id: input.id, scope_id: input.scope, plugin_id: pluginId, kind: input.kind, name: input.name, url: input.url ?? undefined, can_remove: input.canRemove ?? true, can_refresh: input.canRefresh ?? false, can_edit: input.canEdit ?? false, created_at: now, updated_at: now, }, forceAllowId: true, }); if (input.tools.length > 0) { yield* core.createMany({ model: "tool", data: input.tools.map((tool) => ({ id: `${input.id}.${tool.name}`, scope_id: input.scope, source_id: input.id, plugin_id: pluginId, name: tool.name, description: tool.description, input_schema: tool.inputSchema ?? undefined, output_schema: tool.outputSchema ?? undefined, created_at: now, updated_at: now, })), forceAllowId: true, }); } }); // Delete a source and its tools + definitions at ONE specific scope.// The scoped adapter already narrows reads/writes to the executor's// stack via `scope_id IN (...)`, but we pin `scope_id = scopeId` here// so this helper never widens into a stack-wide wipe — a bystander// scope's rows with a colliding `source_id` must survive.const deleteSourceById = ( core: TypedAdapter<CoreSchema>, sourceId: string, scopeId: string,): Effect.Effect<void, StorageFailure> => Effect.gen(function* () { yield* core.deleteMany({ model: "tool", where: [ { field: "source_id", value: sourceId }, { field: "scope_id", value: scopeId }, ], }); yield* core.deleteMany({ model: "definition", where: [ { field: "source_id", value: sourceId }, { field: "scope_id", value: scopeId }, ], }); yield* core.delete({ model: "source", where: [ { field: "id", value: sourceId }, { field: "scope_id", value: scopeId }, ], }); }); const writeDefinitions = (Lines 1–500 of 2841. Load more
import { Context, Deferred, Effect, Option, Result, Schema, Semaphore } from "effect"; import { generateKeyBetween } from "fractional-indexing"; import { StorageError, typedAdapter, type DBAdapter, type DBSchema, type DBTransactionAdapter, type StorageFailure, type TypedAdapter, } from "@executor-js/storage-core"; import { pluginBlobStore, type BlobStore, } from "./blob"; import { ConnectionProviderState, ConnectionRef, ConnectionRefreshError, type ConnectionProvider, type ConnectionRefreshResult, type CreateConnectionInput, type UpdateConnectionTokensInput, } from "./connections"; import { coreSchema, isToolPolicyAction, type ConnectionRow, type CoreSchema, type DefinitionsInput, type SecretRow, type SourceInput, type SourceRow, type ToolAnnotations, type ToolPolicyRow, type ToolRow, } from "./core-schema"; import { ElicitationDeclinedError, ElicitationResponse, FormElicitation, type ElicitationHandler, type ElicitationRequest, } from "./elicitation"; import { ConnectionNotFoundError, ConnectionProviderNotRegisteredError, ConnectionReauthRequiredError, ConnectionRefreshNotSupportedError, NoHandlerError, PluginNotLoadedError, SecretOwnedByConnectionError, SourceRemovalNotAllowedError, ToolBlockedError, ToolInvocationError, ToolNotFoundError, } from "./errors"; import { ConnectionId, ScopeId, SecretId, ToolId } from "./ids"; import { makeOAuth2Service } from "./oauth-service"; import type { OAuthService } from "./oauth"; import { comparePolicyRow, isValidPattern, resolveToolPolicy, rowToToolPolicy, type CreateToolPolicyInput, type PolicyMatch, type ToolPolicy, type UpdateToolPolicyInput, } from "./policies"; import type { AnyPlugin, Elicit, PluginCtx, PluginExtensions, StaticSourceDecl, StaticToolDecl, StorageDeps, } from "./plugin"; import type { Scope } from "./scope"; import { SecretRef, SetSecretInput, type SecretProvider, } from "./secrets"; import { ToolSchema, type Source, type SourceDetectionResult, type Tool, type ToolListFilter, } from "./types"; import { buildToolTypeScriptPreview } from "./schema-types"; import { scopeAdapter } from "./scoped-adapter"; // --------------------------------------------------------------------------- // Elicitation handler — set once at `createExecutor({ onElicitation })` // and threaded into every tool invocation. A tool that requests user // input mid-execution suspends the fiber and the handler decides how to // respond. Tools that never elicit simply don't trigger the handler. // // The "accept-all" sentinel is convenient for tests and CLI automation — // every elicitation request gets auto-accepted with an empty content // payload. For real interactive hosts, pass a real handler. // // Required at the executor level rather than per-invoke, so the // "what if a caller forgot to pass a handler" branch is structurally // impossible. Higher layers that need per-invocation handler control // (an MCP server bridging different per-client handlers, the execution // engine threading agent-loop callbacks) can pass an override via // `tools.invoke(id, args, { onElicitation })` — the executor-level // handler is the fallback, never null. // --------------------------------------------------------------------------- export type OnElicitation = ElicitationHandler | "accept-all"; export interface InvokeOptions { /** Override the executor-level handler for this single call. */ readonly onElicitation?: OnElicitation; } const acceptAllHandler: ElicitationHandler = () => Effect.succeed(new ElicitationResponse({ action: "accept" })); const resolveElicitationHandler = ( onElicitation: OnElicitation, ): ElicitationHandler => onElicitation === "accept-all" ? acceptAllHandler : onElicitation; // --------------------------------------------------------------------------- // Executor — public surface. Every list/invoke/schema call is a direct // core-table query (for dynamic rows) unioned with the in-memory static // pool. No ToolRegistry, no SourceRegistry, no SecretStore services. // --------------------------------------------------------------------------- export type Executor<TPlugins extends readonly AnyPlugin[] = []> = { /** * Precedence-ordered scope stack this executor was configured with. * Innermost first. Consumers that need "the display scope" typically * pick `scopes.at(-1)` (outermost, e.g. the organization) or * `scopes[0]` (innermost, e.g. the current user-in-org) depending on * what they're rendering. */ readonly scopes: readonly Scope[]; readonly tools: { readonly list: ( filter?: ToolListFilter, ) => Effect.Effect<readonly Tool[], StorageFailure>; /** Fetch a tool's full schema view: JSON schemas with `$defs` * attached from the core `definition` table, plus TypeScript * preview strings rendered from them. Returns `null` for unknown * tool ids. */ readonly schema: ( toolId: string, ) => Effect.Effect<ToolSchema | null, StorageFailure>; /** Every `$defs` entry across every source, grouped by source id. * Used for bulk schema export and downstream TypeScript rendering. */ readonly definitions: () => Effect.Effect< Record<string, Record<string, unknown>>, StorageFailure >; readonly invoke: ( toolId: string, args: unknown, options?: InvokeOptions, ) => Effect.Effect< unknown, | ToolNotFoundError | ToolBlockedError | PluginNotLoadedError | NoHandlerError | ToolInvocationError | ElicitationDeclinedError | StorageFailure >; }; readonly sources: { readonly list: () => Effect.Effect<readonly Source[], StorageFailure>; readonly remove: ( sourceId: string, ) => Effect.Effect<void, SourceRemovalNotAllowedError | StorageFailure>; readonly refresh: (sourceId: string) => Effect.Effect<void, StorageFailure>; /** URL autodetection — fans out to every plugin's `detect` hook * (if declared), returns every high/medium/low-confidence match. * UI picks a winner from the list. */ readonly detect: ( url: string, ) => Effect.Effect<readonly SourceDetectionResult[], StorageFailure>; /** All `$defs` registered for a single source, keyed by def name. */ readonly definitions: ( sourceId: string, ) => Effect.Effect<Record<string, unknown>, StorageFailure>; }; readonly secrets: { readonly get: ( id: string, ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>; /** Fast-path existence check — hits the core `secret` routing table * only, never calls the provider. Use this for UI state ("secret * missing, prompt to add") to avoid keychain permission prompts * or 1password IPC roundtrips on a pre-flight check. */ readonly status: ( id: string, ) => Effect.Effect<"resolved" | "missing", StorageFailure>; readonly set: ( input: SetSecretInput, ) => Effect.Effect<SecretRef, StorageFailure>; /** Delete a bare (non-connection-owned) secret. Connection-owned * secrets are rejected with `SecretOwnedByConnectionError` — use * `connections.remove` instead. */ readonly remove: ( id: string, ) => Effect.Effect<void, SecretOwnedByConnectionError | StorageFailure>; readonly list: () => Effect.Effect<readonly SecretRef[], StorageFailure>; readonly providers: () => Effect.Effect<readonly string[]>; }; readonly connections: { readonly get: ( id: string, ) => Effect.Effect<ConnectionRef | null, StorageFailure>; readonly list: () => Effect.Effect<readonly ConnectionRef[], StorageFailure>; readonly create: ( input: CreateConnectionInput, ) => Effect.Effect< ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure >; readonly updateTokens: ( input: UpdateConnectionTokensInput, ) => Effect.Effect< ConnectionRef, ConnectionNotFoundError | StorageFailure >; readonly setIdentityLabel: ( id: string, label: string | null, ) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>; readonly accessToken: ( id: string, ) => Effect.Effect< string, | ConnectionNotFoundError | ConnectionProviderNotRegisteredError | ConnectionRefreshNotSupportedError | ConnectionReauthRequiredError | ConnectionRefreshError | StorageFailure >; readonly remove: (id: string) => Effect.Effect<void, StorageFailure>; readonly providers: () => Effect.Effect<readonly string[]>; }; /** Shared OAuth service. Hosts use this through the core HTTP OAuth group; * plugins see the same service as `ctx.oauth`. */ readonly oauth: OAuthService; readonly policies: { /** All policies visible across the executor's scope stack, sorted * by (innermost-scope-first, position ascending) — i.e. the order * in which they're evaluated by first-match-wins. */ readonly list: () => Effect.Effect<readonly ToolPolicy[], StorageFailure>; /** Create a new policy. Defaults to the top of the target scope's * list (highest precedence) when `position` is omitted. */ readonly create: ( input: CreateToolPolicyInput, ) => Effect.Effect<ToolPolicy, StorageFailure>; readonly update: ( input: UpdateToolPolicyInput, ) => Effect.Effect<ToolPolicy, StorageFailure>; readonly remove: (id: string) => Effect.Effect<void, StorageFailure>; /** Resolve the effective policy for a tool id by walking the scope- * stacked policy list with first-match-wins semantics. Returns * `undefined` when no rule matches (caller falls back to the * plugin's `resolveAnnotations` output). */ readonly resolve: ( toolId: string, ) => Effect.Effect<PolicyMatch | undefined, StorageFailure>; }; readonly close: () => Effect.Effect<void, StorageFailure>; } & PluginExtensions<TPlugins>; export interface ExecutorConfig< TPlugins extends readonly AnyPlugin[] = [], > { /** * Precedence-ordered scope stack. Innermost first; typical shape is * `[userInOrgScope, orgScope]`. Reads on scoped tables walk the * stack (first hit wins for shadow-by-id consumers like secrets and * blobs); writes require callers to name an explicit target scope. * Must be non-empty. */ readonly scopes: readonly Scope[]; readonly adapter: DBAdapter; readonly blobs: BlobStore; readonly plugins?: TPlugins; /** * How to respond when a tool requests user input mid-invocation. Pass * `"accept-all"` for tests / non-interactive hosts, or a handler * `(ctx) => Effect<ElicitationResponse>` for interactive ones. * Required at construction so per-invoke calls don't have to thread * an options arg. */ readonly onElicitation: OnElicitation; } // --------------------------------------------------------------------------- // collectSchemas — merge coreSchema with every plugin's declared schema. // Hosts call this and pass the result to the migration runner (or to // the adapter factory for backends that auto-migrate from a schema // manifest) before constructing the executor. // --------------------------------------------------------------------------- export const collectSchemas = ( plugins: readonly AnyPlugin[], ): DBSchema => { const merged: Record<string, DBSchema[string]> = { ...coreSchema }; for (const plugin of plugins) { if (!plugin.schema) continue; for (const [modelKey, model] of Object.entries(plugin.schema)) { if (merged[modelKey]) { throw new Error( `Duplicate model "${modelKey}" contributed by plugin "${plugin.id}"` + ` (reserved by core or another plugin)`, ); } merged[modelKey] = model as DBSchema[string]; } } return merged; }; // --------------------------------------------------------------------------- // Row → public projection conversions // --------------------------------------------------------------------------- const rowToSource = (row: SourceRow): Source => ({ id: row.id, scopeId: row.scope_id, kind: row.kind, name: row.name, url: row.url ?? undefined, pluginId: row.plugin_id, canRemove: Boolean(row.can_remove), canRefresh: Boolean(row.can_refresh), canEdit: Boolean(row.can_edit), runtime: false, }); const staticDeclToSource = ( decl: StaticSourceDecl, pluginId: string, ): Source => ({ id: decl.id, scopeId: undefined, kind: decl.kind, name: decl.name, url: decl.url, pluginId, canRemove: decl.canRemove ?? false, canRefresh: decl.canRefresh ?? false, canEdit: decl.canEdit ?? false, runtime: true, }); const decodeJsonColumn = (value: unknown): unknown => { if (value === null || value === undefined) return undefined; if (typeof value !== "string") return value; try { return JSON.parse(value); } catch { return value; } }; const rowToTool = ( row: ToolRow, annotations?: ToolAnnotations, ): Tool => ({ id: row.id, sourceId: row.source_id, pluginId: row.plugin_id, name: row.name, description: row.description, inputSchema: decodeJsonColumn(row.input_schema), outputSchema: decodeJsonColumn(row.output_schema), annotations, }); const staticDeclToTool = ( source: StaticSourceDecl, tool: StaticToolDecl, pluginId: string, ): Tool => ({ id: `${source.id}.${tool.name}`, sourceId: source.id, pluginId, name: tool.name, description: tool.description, inputSchema: tool.inputSchema, outputSchema: tool.outputSchema, annotations: tool.annotations, }); // --------------------------------------------------------------------------- // Dynamic-row writers — used by ctx.core.sources.register. Static sources // never touch these functions. // --------------------------------------------------------------------------- // Upsert shape: delete any existing source + tools + definitions for // `input.id` before creating fresh rows. Keeps replayable — boot-time // sync from executor.jsonc can call register() on rows that already // exist without tripping a UNIQUE constraint. const writeSourceInput = ( core: TypedAdapter<CoreSchema>, pluginId: string, input: SourceInput, ): Effect.Effect<void, StorageFailure> => Effect.gen(function* () { yield* deleteSourceById(core, input.id, input.scope); const now = new Date(); yield* core.create({ model: "source", data: { id: input.id, scope_id: input.scope, plugin_id: pluginId, kind: input.kind, name: input.name, url: input.url ?? undefined, can_remove: input.canRemove ?? true, can_refresh: input.canRefresh ?? false, can_edit: input.canEdit ?? false, created_at: now, updated_at: now, }, forceAllowId: true, }); if (input.tools.length > 0) { yield* core.createMany({ model: "tool", data: input.tools.map((tool) => ({ id: `${input.id}.${tool.name}`, scope_id: input.scope, source_id: input.id, plugin_id: pluginId, name: tool.name, description: tool.description, input_schema: tool.inputSchema ?? undefined, output_schema: tool.outputSchema ?? undefined, created_at: now, updated_at: now, })), forceAllowId: true, }); } }); // Delete a source and its tools + definitions at ONE specific scope. // The scoped adapter already narrows reads/writes to the executor's // stack via `scope_id IN (...)`, but we pin `scope_id = scopeId` here // so this helper never widens into a stack-wide wipe — a bystander // scope's rows with a colliding `source_id` must survive. const deleteSourceById = ( core: TypedAdapter<CoreSchema>, sourceId: string, scopeId: string, ): Effect.Effect<void, StorageFailure> => Effect.gen(function* () { yield* core.deleteMany({ model: "tool", where: [ { field: "source_id", value: sourceId }, { field: "scope_id", value: scopeId }, ], }); yield* core.deleteMany({ model: "definition", where: [ { field: "source_id", value: sourceId }, { field: "scope_id", value: scopeId }, ], }); yield* core.delete({ model: "source", where: [ { field: "id", value: sourceId }, { field: "scope_id", value: scopeId }, ], }); }); const writeDefinitions = (