@executor-js/sdk 0.2.0 → 1.4.20

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.
@@ -3,10 +3,34 @@ import {
3
3
  ScopeId,
4
4
  collectSchemas,
5
5
  makeInMemoryBlobStore
6
- } from "./chunk-VLVPSIQ4.js";
6
+ } from "./chunk-OIJL6F6M.js";
7
7
 
8
8
  // src/plugin.ts
9
+ import { Effect } from "effect";
9
10
  var defineSchema = (schema) => schema;
11
+ var decodeStaticToolArgs = (schema, args) => {
12
+ if (schema == null) return Effect.succeed(args);
13
+ return Effect.promise(() => Promise.resolve(schema["~standard"].validate(args))).pipe(
14
+ Effect.flatMap(
15
+ (result) => "value" in result ? Effect.succeed(result.value) : Effect.fail(result)
16
+ )
17
+ );
18
+ };
19
+ var tool = (input) => ({
20
+ name: input.name,
21
+ description: input.description,
22
+ inputSchema: input.inputSchema,
23
+ outputSchema: input.outputSchema,
24
+ annotations: input.annotations,
25
+ handler: ({ args, ctx, elicit }) => decodeStaticToolArgs(input.inputSchema, args).pipe(
26
+ Effect.flatMap(
27
+ (decoded) => input.execute(
28
+ decoded,
29
+ { ctx, elicit }
30
+ )
31
+ )
32
+ )
33
+ });
10
34
  function definePlugin(authorFactory) {
11
35
  return (options) => {
12
36
  const {
@@ -24,10 +48,10 @@ function definePlugin(authorFactory) {
24
48
 
25
49
  // src/test-config.ts
26
50
  import { makeMemoryAdapter } from "@executor-js/storage-core/testing/memory";
27
- import { Effect } from "effect";
51
+ import { Effect as Effect2 } from "effect";
28
52
  var makeTestConfig = (options) => {
29
53
  const scopes = options?.scopes ?? [
30
- new Scope({
54
+ Scope.make({
31
55
  id: ScopeId.make("test-scope"),
32
56
  name: options?.scopeName ?? "test",
33
57
  createdAt: /* @__PURE__ */ new Date()
@@ -50,12 +74,12 @@ var memorySecretsPlugin = definePlugin(() => {
50
74
  const provider = {
51
75
  key: "memory",
52
76
  writable: true,
53
- get: (id, scope) => Effect.sync(() => store.get(`${scope}\0${id}`) ?? null),
54
- set: (id, value, scope) => Effect.sync(() => {
77
+ get: (id, scope) => Effect2.sync(() => store.get(`${scope}\0${id}`) ?? null),
78
+ set: (id, value, scope) => Effect2.sync(() => {
55
79
  store.set(`${scope}\0${id}`, value);
56
80
  }),
57
- delete: (id, scope) => Effect.sync(() => store.delete(`${scope}\0${id}`)),
58
- list: () => Effect.sync(
81
+ delete: (id, scope) => Effect2.sync(() => store.delete(`${scope}\0${id}`)),
82
+ list: () => Effect2.sync(
59
83
  () => Array.from(store.keys()).map((key) => {
60
84
  const name = key.split("\0", 2)[1] ?? key;
61
85
  return { id: name, name };
@@ -71,8 +95,9 @@ var memorySecretsPlugin = definePlugin(() => {
71
95
 
72
96
  export {
73
97
  defineSchema,
98
+ tool,
74
99
  definePlugin,
75
100
  makeTestConfig,
76
101
  memorySecretsPlugin
77
102
  };
78
- //# sourceMappingURL=chunk-FPV6KONN.js.map
103
+ //# sourceMappingURL=chunk-I2OEQ2GJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugin.ts","../src/test-config.ts"],"sourcesContent":["import { Effect } from \"effect\";\nimport type { Context, Layer } from \"effect\";\nimport type { HttpClient } from \"effect/unstable/http\";\nimport type { HttpApiGroup } from \"effect/unstable/httpapi\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { DBSchema, StorageFailure } from \"@executor-js/storage-core\";\n\nimport type { PluginBlobStore } from \"./blob\";\nimport type {\n ConnectionProvider,\n ConnectionRef,\n ConnectionRefreshError,\n CreateConnectionInput,\n RemoveConnectionInput,\n UpdateConnectionTokensInput,\n} from \"./connections\";\nimport type { CredentialBindingsFacade } from \"./credential-bindings\";\nimport type { DefinitionsInput, SourceInput, ToolAnnotations, ToolRow } from \"./core-schema\";\nimport type { RemoveSourceInput, SourceDetectionResult } from \"./types\";\nimport type {\n ElicitationDeclinedError,\n ElicitationHandler,\n ElicitationRequest,\n ElicitationResponse,\n} from \"./elicitation\";\nimport type {\n ConnectionInUseError,\n ConnectionNotFoundError,\n ConnectionProviderNotRegisteredError,\n ConnectionReauthRequiredError,\n ConnectionRefreshNotSupportedError,\n SecretInUseError,\n SecretOwnedByConnectionError,\n} from \"./errors\";\nimport type { OAuthService } from \"./oauth\";\nimport type { Scope } from \"./scope\";\nimport type { ScopedDBAdapter, ScopedTypedAdapter } from \"./scoped-adapter\";\nimport type { RemoveSecretInput, SecretProvider, SecretRef, SetSecretInput } from \"./secrets\";\nimport type { Usage, UsagesForConnectionInput, UsagesForSecretInput } from \"./usages\";\n\n// ---------------------------------------------------------------------------\n// StorageDeps — backing passed to a plugin's `storage` factory. The only\n// place a plugin ever sees storage; `PluginCtx` does not carry it. The\n// `adapter` field is a `TypedAdapter<TSchema>` view narrowed by the\n// plugin's own declared `schema` — plugins never import or construct\n// a typed adapter themselves, the executor infers TSchema from the\n// `schema` field on their spec and hands back a typed view.\n//\n// Plugins with no schema (secret-provider-only plugins, etc.) get a\n// bare `DBAdapter` they can ignore.\n// ---------------------------------------------------------------------------\n\nexport interface StorageDeps<TSchema extends DBSchema | undefined = undefined> {\n /**\n * Precedence-ordered scope stack visible to this executor. Innermost\n * first. Reads on scoped tables walk every scope; writes require the\n * plugin to name a target scope explicitly (via `scope_id` on the\n * adapter payload, via `options.scope` on the blob store).\n */\n readonly scopes: readonly Scope[];\n /**\n * Plugin-facing typed adapter. Failures surface as raw `StorageFailure`\n * (`StorageError` | `UniqueViolationError`). Plugins can\n * `catchTag(\"UniqueViolationError\", …)` to translate to their own\n * user-facing errors. `StorageError` bubbles up; the HTTP edge (see\n * `@executor-js/api` `withCapture`) is the one place that\n * translates it to the opaque `InternalError({ traceId })`.\n */\n readonly adapter: TSchema extends DBSchema ? ScopedTypedAdapter<TSchema> : ScopedDBAdapter;\n readonly blobs: PluginBlobStore;\n}\n\n// ---------------------------------------------------------------------------\n// defineSchema — sugar around `as const satisfies DBSchema`. Preserves\n// literal types via the `const` type parameter modifier so plugins can\n// just write `const mySchema = defineSchema({ ... })` without annotation\n// ceremony.\n// ---------------------------------------------------------------------------\n\nexport const defineSchema = <const S extends DBSchema>(schema: S): S => schema;\n\n// ---------------------------------------------------------------------------\n// Elicit — suspends the fiber, calls the invoke-time elicitation\n// handler, resumes with the user's response. Available on both static\n// tool handlers and dynamic `invokeTool` handlers. Threaded through\n// the executor from `createExecutor({ onElicitation })`.\n// ---------------------------------------------------------------------------\n\nexport type Elicit = (\n request: ElicitationRequest,\n) => Effect.Effect<ElicitationResponse, ElicitationDeclinedError>;\n\n// ---------------------------------------------------------------------------\n// PluginCtx — threaded into every extension method, static tool handler,\n// and dynamic tool handler. No raw adapter, no raw blobs. Core writes\n// go through `core.sources.register` / `core.definitions.register`.\n// ---------------------------------------------------------------------------\n\nexport interface PluginCtx<TStore = unknown> {\n /**\n * Precedence-ordered scope stack visible to this executor. Innermost\n * first. Plugins that write scoped rows must pick an element of\n * `scopes` as the `scope`/`scope_id` they stamp; reads through the\n * adapter or `ctx.secrets` automatically fall through the stack.\n */\n readonly scopes: readonly Scope[];\n readonly storage: TStore;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient>;\n\n readonly core: {\n readonly sources: {\n readonly register: (input: SourceInput) => Effect.Effect<void, StorageFailure>;\n readonly unregister: (input: RemoveSourceInput) => Effect.Effect<void, StorageFailure>;\n readonly update: (input: {\n readonly id: string;\n readonly scope: string;\n readonly name?: string;\n readonly url?: string | null;\n }) => Effect.Effect<void, StorageFailure>;\n };\n /** Register shared JSON-schema `$defs` for a source. Tool\n * input/output schemas registered via `sources.register` can carry\n * `$ref: \"#/$defs/X\"` pointers; `executor.tools.schema(toolId)`\n * attaches matching defs to the returned schema. Call inside the\n * same `ctx.transaction` as `sources.register` for atomicity.\n * Replaces any existing defs for the given sourceId. */\n readonly definitions: {\n readonly register: (input: DefinitionsInput) => Effect.Effect<void, StorageFailure>;\n };\n };\n\n readonly secrets: {\n readonly get: (\n id: string,\n ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>;\n readonly getAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>;\n /** List user-visible secrets. Connection-owned secrets (rows with\n * `owned_by_connection_id` set) are filtered out so they don't\n * clutter the UI — users see the Connection instead. */\n readonly list: () => Effect.Effect<\n readonly { readonly id: string; readonly name: string; readonly provider: string }[],\n StorageFailure\n >;\n /** Write a secret value through a provider. Used by plugins that\n * mint secrets on behalf of the user (OAuth2 token storage,\n * interactive onboarding flows). Normally writes go through\n * `executor.secrets.set` on the host surface, but OAuth2 refresh\n * and one-shot token capture from plugin-owned flows need it here\n * too. Same routing rules as the host-level setter. */\n readonly set: (input: SetSecretInput) => Effect.Effect<SecretRef, StorageFailure>;\n /** Delete a secret from its pinned provider and the core table.\n * Rejects with `SecretOwnedByConnectionError` if the row is owned\n * by a connection — callers must go through `connections.remove`\n * to drop the whole sign-in. Rejects with `SecretInUseError` if\n * any plugin reports the secret as in use; the caller should ask\n * the user to detach the listed sources first. */\n readonly remove: (\n input: RemoveSecretInput,\n ) => Effect.Effect<void, SecretOwnedByConnectionError | SecretInUseError | StorageFailure>;\n };\n\n /** Connections — product-level sign-in state. Owns backing secret\n * rows via `secret.owned_by_connection_id`. Plugins call\n * `connections.accessToken(id)` at invoke time to get a guaranteed-\n * fresh token (the SDK handles refresh via the registered provider\n * keyed by `connection.provider`). */\n readonly connections: {\n readonly get: (id: string) => Effect.Effect<ConnectionRef | null, StorageFailure>;\n readonly getAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<ConnectionRef | null, StorageFailure>;\n readonly list: () => Effect.Effect<readonly ConnectionRef[], StorageFailure>;\n readonly create: (\n input: CreateConnectionInput,\n ) => Effect.Effect<ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure>;\n readonly updateTokens: (\n input: UpdateConnectionTokensInput,\n ) => Effect.Effect<ConnectionRef, ConnectionNotFoundError | StorageFailure>;\n readonly setIdentityLabel: (\n id: string,\n label: string | null,\n ) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>;\n /** Get a guaranteed-fresh access token. Calls the provider's\n * `refresh` handler if `expires_at` is in the past / within the\n * refresh skew window. */\n readonly accessToken: (\n id: string,\n ) => Effect.Effect<\n string,\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure\n >;\n readonly accessTokenAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<\n string,\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure\n >;\n /** Refuses with `ConnectionInUseError` if any plugin reports the\n * connection as in use. Caller surfaces the `usages` list to the\n * user. */\n readonly remove: (\n input: RemoveConnectionInput,\n ) => Effect.Effect<void, ConnectionInUseError | StorageFailure>;\n };\n\n readonly credentialBindings: CredentialBindingsFacade;\n\n /** Shared OAuth service. Plugins use this to probe/start/complete OAuth\n * flows; invocation should still resolve tokens via `connections.accessToken`. */\n readonly oauth: OAuthService;\n\n /** Run `effect` inside a database transaction. Wraps the underlying\n * adapter's transaction method. Use this in extension methods that\n * need atomicity across plugin storage writes AND core source/tool\n * registration. */\n readonly transaction: <A, E>(effect: Effect.Effect<A, E>) => Effect.Effect<A, E | StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Static tool / source declarations. Pure data + handlers declared at\n// plugin-definition time.\n//\n// Importantly, `StaticToolDecl.handler` does NOT reference TExtension.\n// If it did, the nested generic would break inference for the whole\n// PluginSpec (TS would fall back to the `object` constraint on TExtension).\n// `self: NoInfer<TExtension>` lives on `staticSources` one level up\n// instead, and plugin authors close over it via the arrow-function\n// closure when they write their handler.\n// ---------------------------------------------------------------------------\n\nexport interface StaticToolHandlerInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly args: unknown;\n /** Suspend the fiber to request user input. The handler passed to\n * `createExecutor({ onElicitation })` is called. */\n readonly elicit: Elicit;\n}\n\nexport interface StaticToolExecuteContext<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n /** Suspend the fiber to request user input. The handler passed to\n * `createExecutor({ onElicitation })` is called. */\n readonly elicit: Elicit;\n}\n\nexport type StaticToolSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output> &\n StandardJSONSchemaV1<Input, Output>;\n\nexport interface StaticToolDecl<TStore = unknown> {\n readonly name: string;\n readonly description: string;\n readonly inputSchema?: StaticToolSchema;\n readonly outputSchema?: StaticToolSchema;\n /** Default-policy annotations — `requiresApproval`, `approvalDescription`,\n * `mayElicit`. Enforced by the executor before the handler runs.\n * Inline because static tools have no plugin storage to resolve from;\n * the plugin author literally writes this at definition time. */\n readonly annotations?: ToolAnnotations;\n readonly handler: (input: StaticToolHandlerInput<TStore>) => Effect.Effect<unknown, unknown>;\n}\n\nconst decodeStaticToolArgs = (\n schema: StaticToolSchema | undefined,\n args: unknown,\n): Effect.Effect<unknown, unknown> => {\n if (schema == null) return Effect.succeed(args);\n return Effect.promise(() => Promise.resolve(schema[\"~standard\"].validate(args))).pipe(\n Effect.flatMap((result) =>\n \"value\" in result ? Effect.succeed(result.value) : Effect.fail(result),\n ),\n );\n};\n\nexport interface StaticToolInput<\n TStore = unknown,\n TInputSchema extends StaticToolSchema | undefined = StaticToolSchema | undefined,\n> {\n readonly name: string;\n readonly description: string;\n readonly inputSchema?: TInputSchema;\n readonly outputSchema?: StaticToolSchema;\n /** Default-policy annotations — `requiresApproval`, `approvalDescription`,\n * `mayElicit`. Enforced by the executor before the handler runs. */\n readonly annotations?: ToolAnnotations;\n readonly execute: (\n args: TInputSchema extends StaticToolSchema\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : unknown,\n context: StaticToolExecuteContext<TStore>,\n ) => Effect.Effect<unknown, unknown>;\n}\n\nexport const tool = <\n TStore = unknown,\n TInputSchema extends StaticToolSchema | undefined = StaticToolSchema | undefined,\n>(\n input: StaticToolInput<TStore, TInputSchema>,\n): StaticToolDecl<TStore> => ({\n name: input.name,\n description: input.description,\n inputSchema: input.inputSchema,\n outputSchema: input.outputSchema,\n annotations: input.annotations,\n handler: ({ args, ctx, elicit }) =>\n decodeStaticToolArgs(input.inputSchema, args).pipe(\n Effect.flatMap((decoded) =>\n input.execute(\n decoded as TInputSchema extends StaticToolSchema\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : unknown,\n { ctx, elicit },\n ),\n ),\n ),\n});\n\nexport interface StaticSourceDecl<TStore = unknown> {\n readonly id: string;\n readonly kind: string;\n readonly name: string;\n readonly url?: string;\n /** Static sources default to `canRemove: false` because they are\n * plugin-provided surfaces and shouldn't usually be user-removable.\n * Override only if you really want that. */\n readonly canRemove?: boolean;\n readonly canRefresh?: boolean;\n readonly canEdit?: boolean;\n readonly tools: readonly StaticToolDecl<TStore>[];\n}\n\n// ---------------------------------------------------------------------------\n// Dynamic invoke / source lifecycle inputs.\n// ---------------------------------------------------------------------------\n\nexport interface InvokeToolInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n /** Already-loaded tool row. Plugin doesn't need to re-fetch or parse\n * the tool id. Carries source_id, name, input/output schemas,\n * annotations. */\n readonly toolRow: ToolRow;\n readonly args: unknown;\n /** Elicitation handle for plugins that need mid-invocation user input\n * (onepassword auth prompt, interactive MCP tools, etc.). */\n readonly elicit: Elicit;\n}\n\nexport interface SourceLifecycleInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly sourceId: string;\n /**\n * Scope of the source row being removed/refreshed — resolved by the\n * SDK's `sources.remove` / `sources.refresh` via innermost-wins lookup\n * across the executor's scope stack. Plugins that own a side table\n * keyed by (id, scope_id) must pin their own cleanup to this scope;\n * relying on the scoped adapter's `scope_id IN (stack)` fall-through\n * would widen the mutation across the whole stack and wipe a\n * shadowed outer-scope row.\n */\n readonly scope: string;\n}\n\n// ---------------------------------------------------------------------------\n// PluginSpec — what a `definePlugin(factory)` call returns.\n// ---------------------------------------------------------------------------\n\n// Defaults are `any` for slots that surface in contravariant positions\n// (storage/extension callbacks consume `TStore`/`TSchema`; `staticSources`\n// closes over `TExtension` via `NoInfer`). `any` is bivariant, so\n// `Plugin<string>` is a structural supertype of every concrete plugin\n// — `AnyPlugin = Plugin<string>` keeps the generic explosion contained\n// to this single declaration. Concrete specs ignore the defaults; TS\n// infers each slot from the literal returned by the author factory.\n//\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface PluginSpec<\n TId extends string = string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtension extends object = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TStore = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TSchema extends DBSchema | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = any,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n> {\n readonly id: TId;\n /** npm package name. The Vite plugin uses this to derive the\n * `./client` import path for the frontend bundle (so the same\n * `executor.config.ts` drives both server and client) — `${packageName}/client`\n * is what gets bundled. The author writes the same string they\n * publish to npm; no transforms, no scope conventions. Required for\n * plugins that ship a `./client` entry; can be omitted for SDK-only\n * plugins (no client bundle = nothing to resolve). */\n readonly packageName?: string;\n /** Plugin-declared schema. Merged with coreSchema and other plugins'\n * schemas at executor startup via `collectSchemas`. The type flows\n * into the `storage` factory's `deps.adapter` as a `TypedAdapter<TSchema>`\n * so plugins get narrowed model names + typed rows for free. */\n readonly schema?: TSchema;\n /** Build the plugin's typed store from backing. `deps.adapter` is\n * already narrowed to this plugin's schema; `deps.blobs` is already\n * scoped to the plugin id so key collisions across plugins are\n * structurally impossible. */\n readonly storage: (deps: StorageDeps<TSchema>) => TStore;\n\n /** JSON-serializable config the plugin wants its `./client` bundle to\n * see. The Vite plugin reads this off each `executor.config.ts` spec\n * at build time and bakes it into the virtual `plugins-client`\n * module by calling the plugin's default `./client` export as a\n * factory: `__p(<JSON.stringify(clientConfig)>)`. Plugins that don't\n * set this stay as bare-value default exports — no churn.\n *\n * Use this when a server-side option (e.g. `dangerouslyAllowStdioMCP`)\n * needs to drive client UI behaviour: declaring it once in\n * `executor.config.ts` flows through to the bundle automatically,\n * with no runtime fetch and no parallel client-side flag to keep in\n * sync. */\n readonly clientConfig?: unknown;\n\n /** Build the plugin's extension API. The returned object becomes\n * `executor[plugin.id]` and is also the `self` passed to\n * `staticSources`. Field order matters: `extension` MUST appear\n * before `staticSources` so TS infers TExtension from this\n * factory's return BEFORE type-checking `self: NoInfer<TExtension>`. */\n readonly extension?: (ctx: PluginCtx<TStore>) => TExtension;\n\n /** Static sources contributed by this plugin with inline tool\n * handlers. Lives entirely in memory — no DB writes at startup.\n * Handlers close over `self` via the closure, so a control tool\n * that delegates to the plugin's real API is a one-liner:\n * `({ args }) => self.addSpec(args)`. */\n readonly staticSources?: (self: NoInfer<TExtension>) => readonly StaticSourceDecl<TStore>[];\n\n /** HttpApiGroup contributed by this plugin. Composed into the host's\n * `HttpApi` via the `addGroup` helper at runtime. The host mounts\n * the group at `/_executor/plugins/{id}/...` (or wherever the\n * plugin declares its base path) with the host's auth + scope\n * middleware applied. Endpoints automatically appear in the\n * executor OpenAPI doc and the typed reactive client.\n *\n * TGroup is inferred from the plugin's own group declaration so the\n * precise group identity flows through `composePluginApi(plugins)` —\n * the host's typed `HttpApi<\"executor\", CoreGroups | PluginGroups>`\n * is derived from the plugin tuple alone, with no per-plugin Group\n * imports at the host. Per-endpoint typing already lives inside the\n * plugin — its `handlers` Layer is built against its own bundled\n * `HttpApi.make(\"foo\").add(FooApi)` for full `.handle(\"name\", ...)`\n * inference, and its client imports the same group directly. */\n readonly routes?: () => TGroup;\n\n /** Handlers Layer for this plugin's group. Built by the plugin against\n * its own bundled API for full type safety on `.handle(\"name\", ...)`,\n * composes into the host's runtime `FullApi` because\n * `HttpApiBuilder.group` keys the layer by group identity, not by the\n * surrounding API.\n *\n * Late-binding: the layer leaves the plugin's extension as a Service\n * Tag requirement (see `extensionService` below). The host satisfies\n * it however its runtime wants:\n * - local: at boot via `Layer.succeed(extensionService)(executor[id])`\n * (see `composePluginHandlers`)\n * - cloud: per-request via `Effect.provideService(extensionService,\n * requestExecutor[id])` in the auth middleware\n *\n * The Layer's channels are typed `any` because `Layer<RIn, E, ROut>`'s\n * `ROut` is contravariant — the host accepts any layer here and merges\n * them; per-plugin requirements flow through the merge. */\n readonly handlers?: () => THandlersLayer;\n\n /** Service tag the plugin's `handlers` layer requires. Set by plugins\n * whose handlers consume their extension via a `Context.Service` tag\n * (the established pattern: `*Handlers` reads `*ExtensionService`).\n * The host binds the tag to the live extension — at boot for local,\n * per request for cloud. Pairs with `handlers`; either both fields\n * are set or neither.\n *\n * Inferred via the `TExtensionService` generic so the per-plugin\n * Service class identity propagates through `composePluginHandlers`,\n * `composePluginHandlerLayer`, and `providePluginExtensions` —\n * cloud's per-request middleware needs the precise tag for layer\n * satisfaction. */\n readonly extensionService?: TExtensionService;\n\n /** Invoke a dynamic tool. Called when the executor's static-handler\n * map doesn't have the toolId. The plugin reads its own enrichment\n * via `ctx.storage` and returns the result. Optional — plugins with\n * only static tools can omit it. */\n readonly invokeTool?: (input: InvokeToolInput<TStore>) => Effect.Effect<unknown, unknown>;\n\n /** Bulk resolve annotations (requiresApproval, approvalDescription,\n * mayElicit) for a set of tool rows under a single source. Called\n * by the executor:\n * - at invoke time with a single-element `toolRows` array, to\n * enforce approval on the about-to-run tool\n * - at list time with every dynamic tool row under each source,\n * grouped by source_id, to populate `Tool.annotations` for UI\n *\n * The expected implementation for most plugins is: read plugin\n * storage once for the given source/rows, derive annotations from\n * the same data that was used to build the tool (HTTP method +\n * path for openapi, introspection kind for graphql, etc.), return\n * a map keyed by tool id.\n *\n * Omit if the plugin has no annotations to contribute — executor\n * treats tools from that plugin as auto-approved with no\n * elicitation. */\n readonly resolveAnnotations?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly sourceId: string;\n readonly toolRows: readonly ToolRow[];\n }) => Effect.Effect<Record<string, ToolAnnotations>, unknown>;\n\n /** Find every place a secret id is referenced by this plugin's stored\n * rows. Implementations query their normalized columns (e.g.\n * `WHERE secret_id = $1`) and return one `Usage` per hit, with\n * `ownerKind` / `slot` tagging the location. The executor fans out\n * across all plugins and the result powers the Secrets-tab \"Used\n * by\" list and the deletion-blocking check in `secrets.remove`.\n *\n * Plugins that never store secret refs (secret-provider-only\n * plugins like keychain / file-secrets / 1password) omit this. */\n readonly usagesForSecret?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly args: UsagesForSecretInput;\n }) => Effect.Effect<readonly Usage[], unknown>;\n\n /** Same shape as `usagesForSecret`, but for connection refs. */\n readonly usagesForConnection?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly args: UsagesForConnectionInput;\n }) => Effect.Effect<readonly Usage[], unknown>;\n\n /** Called when `executor.sources.remove({ id, targetScope })` targets\n * a source owned by this plugin. Plugin-side cleanup only; the\n * executor deletes the core source/tool rows after this callback\n * returns, inside the same transaction. */\n readonly removeSource?: (input: SourceLifecycleInput<TStore>) => Effect.Effect<void, unknown>;\n\n readonly refreshSource?: (input: SourceLifecycleInput<TStore>) => Effect.Effect<void, unknown>;\n\n /** URL autodetection hook. When the user pastes a URL in the\n * onboarding UI, `executor.sources.detect(url)` fans out to every\n * plugin's `detect`. Return a `SourceDetectionResult` if you\n * recognize the URL, `null` otherwise. Implementations should be\n * defensive — swallow fetch errors and return null rather than\n * throwing. First high-confidence match wins. */\n readonly detect?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly url: string;\n }) => Effect.Effect<SourceDetectionResult | null, unknown>;\n\n /** Secret providers contributed by this plugin. Either a static\n * array, a function of ctx (for providers that need per-instance\n * state like the keychain's scope-derived service name), or a\n * function returning an Effect so plugins can probe for backend\n * availability at startup and register conditionally. Called once\n * at executor startup after `storage` and `extension` have been\n * built. */\n readonly secretProviders?:\n | readonly SecretProvider[]\n | ((ctx: PluginCtx<TStore>) => readonly SecretProvider[])\n | ((ctx: PluginCtx<TStore>) => Effect.Effect<readonly SecretProvider[]>);\n\n /** Connection providers contributed by this plugin. Same registration\n * shape as `secretProviders`. Each provider's `key` is what\n * `connection.provider` references in the core table; the `refresh`\n * handler is the SDK's single entry point for token lifecycle —\n * plugins don't run their own refresh loops anymore. */\n readonly connectionProviders?:\n | readonly ConnectionProvider[]\n | ((ctx: PluginCtx<TStore>) => readonly ConnectionProvider[])\n | ((ctx: PluginCtx<TStore>) => Effect.Effect<readonly ConnectionProvider[]>);\n\n readonly close?: () => Effect.Effect<void, unknown>;\n}\n\nexport interface Plugin<\n TId extends string = string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtension extends object = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TStore = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TSchema extends DBSchema | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = any,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n> extends PluginSpec<TId, TExtension, TStore, TSchema, TExtensionService, THandlersLayer, TGroup> {}\n\n// ---------------------------------------------------------------------------\n// definePlugin — factory-returning-spec. Options from the author factory\n// are merged with a storage override so consumers can swap the default\n// store implementation without touching plugin internals.\n// ---------------------------------------------------------------------------\n\nexport type ConfiguredPlugin<\n TId extends string,\n TExtension extends object,\n TStore,\n TOptions extends object,\n TSchema extends DBSchema | undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = Layer.Layer<unknown, never, never>,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n> = (\n options?: TOptions & {\n readonly storage?: (deps: StorageDeps<TSchema>) => TStore;\n },\n) => Plugin<TId, TExtension, TStore, TSchema, TExtensionService, THandlersLayer, TGroup>;\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function definePlugin<\n TId extends string,\n TExtension extends object,\n TStore,\n TSchema extends DBSchema | undefined = undefined,\n TOptions extends object = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = Layer.Layer<unknown, never, never>,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n>(\n authorFactory: (\n options?: TOptions,\n ) => PluginSpec<TId, TExtension, TStore, TSchema, TExtensionService, THandlersLayer, TGroup>,\n): ConfiguredPlugin<\n TId,\n TExtension,\n TStore,\n TOptions,\n TSchema,\n TExtensionService,\n THandlersLayer,\n TGroup\n> {\n return (options) => {\n const {\n storage: storageOverride,\n ...rest\n }: {\n storage?: (deps: StorageDeps<TSchema>) => TStore;\n [key: string]: unknown;\n } = options ?? {};\n\n const hasAuthorOptions = Object.keys(rest).length > 0;\n const spec = authorFactory(hasAuthorOptions ? (rest as TOptions) : undefined);\n\n return {\n ...spec,\n storage: storageOverride ?? spec.storage,\n };\n };\n}\n\n// ---------------------------------------------------------------------------\n// AnyPlugin / PluginExtensions — type-level glue for the Executor surface.\n// ---------------------------------------------------------------------------\n\n// `Plugin<string>` (with all subsequent slots taking their wide defaults)\n// is structurally any concrete plugin — the `any` cascade stays inside\n// the spec's defaults instead of leaking into every consumer.\nexport type AnyPlugin = Plugin<string>;\n\nexport type PluginExtensions<TPlugins extends readonly AnyPlugin[]> = {\n readonly [P in TPlugins[number] as P[\"id\"]]: P extends Plugin<string, infer TExt> ? TExt : never;\n};\n\n/** Lightweight projection of a secret entry as returned by `ctx.secrets.list`. */\nexport interface SecretListEntry {\n readonly id: string;\n readonly name: string;\n readonly provider: string;\n}\n\n// Re-exported for consumers that check the elicitation handler type.\nexport type { ElicitationHandler };\n","import { makeMemoryAdapter } from \"@executor-js/storage-core/testing/memory\";\n\nimport { Effect } from \"effect\";\n\nimport { makeInMemoryBlobStore } from \"./blob\";\nimport type { ExecutorConfig } from \"./executor\";\nimport { collectSchemas } from \"./executor\";\nimport { ScopeId } from \"./ids\";\nimport { definePlugin, type AnyPlugin } from \"./plugin\";\nimport { Scope } from \"./scope\";\nimport type { SecretProvider } from \"./secrets\";\n\n// ---------------------------------------------------------------------------\n// makeTestConfig — build an ExecutorConfig backed by in-memory adapter +\n// blob store. For unit tests, plugin authors validating their plugin,\n// REPL experimentation. No persistence.\n//\n// Defaults to a single-element scope stack (\"test-scope\") — tests that\n// need multi-scope behavior can pass `scopes` explicitly.\n// ---------------------------------------------------------------------------\n\nexport const makeTestConfig = <const TPlugins extends readonly AnyPlugin[] = []>(options?: {\n readonly scopeName?: string;\n readonly scopes?: readonly Scope[];\n readonly plugins?: TPlugins;\n}): ExecutorConfig<TPlugins> => {\n const scopes = options?.scopes ?? [\n Scope.make({\n id: ScopeId.make(\"test-scope\"),\n name: options?.scopeName ?? \"test\",\n createdAt: new Date(),\n }),\n ];\n\n const schema = collectSchemas(options?.plugins ?? []);\n\n return {\n scopes,\n adapter: makeMemoryAdapter({ schema }),\n blobs: makeInMemoryBlobStore(),\n plugins: options?.plugins,\n // Tests default to auto-accepting elicitation prompts. Override via\n // a wrapping spread if a test exercises a real handler:\n // { ...makeTestConfig(...), onElicitation: customHandler }\n onElicitation: \"accept-all\",\n };\n};\n\nexport const memorySecretsPlugin = definePlugin(() => {\n const store = new Map<string, string>();\n\n const provider: SecretProvider = {\n key: \"memory\",\n writable: true,\n get: (id, scope) => Effect.sync(() => store.get(`${scope}\\u0000${id}`) ?? null),\n set: (id, value, scope) =>\n Effect.sync(() => {\n store.set(`${scope}\\u0000${id}`, value);\n }),\n delete: (id, scope) => Effect.sync(() => store.delete(`${scope}\\u0000${id}`)),\n list: () =>\n Effect.sync(() =>\n Array.from(store.keys()).map((key) => {\n const name = key.split(\"\\u0000\", 2)[1] ?? key;\n return { id: name, name };\n }),\n ),\n };\n\n return {\n id: \"memory-secrets\" as const,\n storage: () => ({}),\n secretProviders: [provider],\n };\n});\n"],"mappings":"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","names":["Effect","Effect"]}