@executor-js/sdk 1.5.20 → 1.5.22

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.
Files changed (43) hide show
  1. package/dist/{chunk-EJKXSREX.js → chunk-DN5AKD4U.js} +3 -1
  2. package/dist/chunk-DN5AKD4U.js.map +1 -0
  3. package/dist/{chunk-MYRPYTSV.js → chunk-GUZHNTDQ.js} +197 -57
  4. package/dist/chunk-GUZHNTDQ.js.map +1 -0
  5. package/dist/{chunk-PCSRC6WP.js → chunk-SNWDGE3G.js} +47 -17
  6. package/dist/chunk-SNWDGE3G.js.map +1 -0
  7. package/dist/client.d.ts +9 -1
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js.map +1 -1
  10. package/dist/core.js +11 -5
  11. package/dist/core.js.map +1 -1
  12. package/dist/executor.d.ts +2 -0
  13. package/dist/executor.d.ts.map +1 -1
  14. package/dist/index.d.ts +3 -3
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -2
  17. package/dist/integration.d.ts +4 -3
  18. package/dist/integration.d.ts.map +1 -1
  19. package/dist/oauth-callback-state.test.d.ts +2 -0
  20. package/dist/oauth-callback-state.test.d.ts.map +1 -0
  21. package/dist/oauth-service.d.ts +23 -13
  22. package/dist/oauth-service.d.ts.map +1 -1
  23. package/dist/oauth.d.ts +23 -0
  24. package/dist/oauth.d.ts.map +1 -1
  25. package/dist/plugin.d.ts +35 -1
  26. package/dist/plugin.d.ts.map +1 -1
  27. package/dist/server-connection.d.ts +1 -0
  28. package/dist/server-connection.d.ts.map +1 -1
  29. package/dist/shared.d.ts +2 -1
  30. package/dist/shared.d.ts.map +1 -1
  31. package/dist/shared.js +8 -2
  32. package/dist/test-config.d.ts +1 -0
  33. package/dist/test-config.d.ts.map +1 -1
  34. package/dist/testing/oauth-test-server.d.ts +3 -0
  35. package/dist/testing/oauth-test-server.d.ts.map +1 -1
  36. package/dist/testing.d.ts +1 -1
  37. package/dist/testing.d.ts.map +1 -1
  38. package/dist/testing.js +9 -3
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-EJKXSREX.js.map +0 -1
  42. package/dist/chunk-MYRPYTSV.js.map +0 -1
  43. package/dist/chunk-PCSRC6WP.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fuma-runtime.ts","../src/blob.ts","../src/plugin.ts","../src/owner-policy.ts","../src/core-schema.ts","../src/plugin-storage.ts","../src/schema-refs.ts","../src/vendor/json-schema-to-typescript/compat.ts","../src/vendor/json-schema-to-typescript/formatter.ts","../src/vendor/json-schema-to-typescript/types/AST.ts","../src/vendor/json-schema-to-typescript/types/JSONSchema.ts","../src/vendor/json-schema-to-typescript/utils.ts","../src/vendor/json-schema-to-typescript/generator.ts","../src/vendor/json-schema-to-typescript/typesOfSchema.ts","../src/vendor/json-schema-to-typescript/applySchemaTyping.ts","../src/vendor/json-schema-to-typescript/normalizer.ts","../src/vendor/json-schema-to-typescript/optimizer.ts","../src/vendor/json-schema-to-typescript/parser.ts","../src/vendor/json-schema-to-typescript/resolver.ts","../src/vendor/json-schema-to-typescript/validator.ts","../src/vendor/json-schema-to-typescript/linker.ts","../src/vendor/json-schema-to-typescript/optionValidator.ts","../src/vendor/json-schema-to-typescript/index.ts","../src/schema-types.ts","../src/tool-result.ts","../src/executor.ts","../src/core-tools.ts","../src/oauth-service.ts","../src/oauth-discovery.ts"],"sourcesContent":["import { Cause, Context, Data, Effect, Exit, Layer, Predicate } from \"effect\";\nimport type { AbstractQuery } from \"@executor-js/fumadb/query\";\nimport type { AnySchema, AnyTable, Schema as FumaSchema } from \"@executor-js/fumadb/schema\";\n\nexport class StorageError extends Data.TaggedError(\"StorageError\")<{\n readonly message: string;\n readonly cause: unknown;\n}> {}\n\nexport class UniqueViolationError extends Data.TaggedError(\"UniqueViolationError\")<{\n readonly model?: string;\n}> {}\n\nexport type StorageFailure = StorageError | UniqueViolationError;\n\nexport type FumaTables = Record<string, AnyTable>;\ntype EmptyFumaSchema = FumaSchema<\"latest\", Record<never, never>>;\nexport type TablesToFumaSchema<TTables extends FumaTables | undefined> = TTables extends FumaTables\n ? string extends keyof TTables\n ? AnySchema\n : FumaSchema<\"latest\", TTables>\n : EmptyFumaSchema;\nexport type FumaDb<TSchema extends AnySchema = AnySchema> = AbstractQuery<TSchema>;\nexport type FumaQuery<TSchema extends AnySchema = AnySchema> = Omit<\n AbstractQuery<TSchema>,\n \"internal\" | \"withContext\" | \"transaction\"\n> & {\n readonly transaction: <A>(run: (db: FumaQuery<TSchema>) => Promise<A>) => Promise<A>;\n};\nexport type FumaRow<TTable extends AnyTable> = Omit<\n {\n readonly [K in keyof TTable[\"columns\"]]: TTable[\"columns\"][K][\"$out\"];\n },\n \"row_id\"\n>;\n\nconst isUniqueViolation = (cause: unknown): boolean => {\n let current = cause;\n for (let i = 0; i < 5; i += 1) {\n const err =\n current && typeof current === \"object\" ? (current as Record<string, unknown>) : null;\n if (!err) return false;\n const code = err[\"code\"];\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: database drivers expose unique-violation details on native error messages\n const message = err[\"message\"];\n const innerCause = err[\"cause\"];\n if (code === \"23505\") return true;\n if (\n typeof message === \"string\" &&\n /unique constraint|duplicate key|violates unique constraint/i.test(message)\n ) {\n return true;\n }\n if (!innerCause || innerCause === current) return false;\n current = innerCause;\n }\n return false;\n};\n\nconst causeMessage = (cause: unknown): string | undefined => {\n const message =\n cause && typeof cause === \"object\"\n ? // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: preserve database driver error text inside typed StorageError\n (cause as Record<string, unknown>)[\"message\"]\n : undefined;\n return typeof message === \"string\" && message.length > 0 ? message : undefined;\n};\n\nexport const isStorageFailure = (error: unknown): error is StorageFailure =>\n Predicate.isTagged(error, \"StorageError\") || Predicate.isTagged(error, \"UniqueViolationError\");\n\nexport const fumaFailureFromCause = (label: string, cause: unknown): StorageFailure => {\n if (isStorageFailure(cause)) return cause;\n if (isUniqueViolation(cause)) return new UniqueViolationError({ model: label });\n return new StorageError({\n message: causeMessage(cause) ?? `FumaDB operation failed: ${label}`,\n cause,\n });\n};\n\nexport const fumaEffect = <A>(\n label: string,\n run: () => Promise<A>,\n): Effect.Effect<A, StorageFailure> =>\n Effect.tryPromise({\n try: run,\n catch: (cause) => fumaFailureFromCause(label, cause),\n });\n\nexport const activeFumaDbRef = Context.Reference<FumaDb | null>(\"executor/ActiveFumaDb\", {\n defaultValue: () => null,\n});\n\nclass TransactionEffectFailure {\n constructor(readonly error: unknown) {}\n}\n\nclass TransactionEffectDefect {\n constructor(readonly cause: unknown) {}\n}\n\nexport type IFumaClient<TSchema extends AnySchema = AnySchema> = Readonly<{\n use: <A>(\n label: string,\n fn: (db: FumaQuery<TSchema>) => Promise<A>,\n ) => Effect.Effect<A, StorageFailure>;\n transaction: <A, E>(effect: Effect.Effect<A, E>) => Effect.Effect<A, E | StorageFailure>;\n}>;\n\nexport interface MakeFumaClientOptions {\n readonly tables?: ReadonlySet<string>;\n}\n\nconst isAllowedTable = (tables: ReadonlySet<string> | undefined, table: PropertyKey): boolean =>\n tables === undefined || (typeof table === \"string\" && tables.has(table));\n\nconst assertAllowedTable = (tables: ReadonlySet<string> | undefined, table: PropertyKey): void => {\n if (isAllowedTable(tables, table)) return;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: plugin-facing FumaDB facade rejects unavailable tables synchronously before query execution\n throw new StorageError({\n message: `FumaDB table \"${String(table)}\" is not available through this storage boundary.`,\n cause: undefined,\n });\n};\n\nconst makeSafeFumaQuery = <TSchema extends AnySchema>(\n db: FumaDb<TSchema>,\n options: MakeFumaClientOptions,\n): FumaQuery<TSchema> => {\n const table = <TableName extends keyof TSchema[\"tables\"]>(name: TableName): TableName => {\n assertAllowedTable(options.tables, name);\n return name;\n };\n\n const query: FumaQuery<TSchema> = {\n count: (name, value) => db.count(table(name), value),\n create: (name, value) => db.create(table(name), value),\n createMany: (name, values) => db.createMany(table(name), values),\n deleteMany: (name, value) => db.deleteMany(table(name), value),\n findFirst: (name, value) => db.findFirst(table(name), value),\n findMany: (name, value) => db.findMany(table(name), value),\n transaction: (run) =>\n db.transaction((transactionDb) => run(makeSafeFumaQuery(transactionDb, options))),\n updateMany: (name, value) => db.updateMany(table(name), value),\n upsert: (name, value) => db.upsert(table(name), value),\n };\n\n return Object.freeze(query);\n};\n\nexport const makeFumaClient = (db: FumaDb, options: MakeFumaClientOptions = {}): IFumaClient => {\n const use: IFumaClient[\"use\"] = (label, fn) =>\n Effect.flatMap(Effect.service(activeFumaDbRef), (active) =>\n fumaEffect(label, () => fn(makeSafeFumaQuery(active ?? db, options))),\n ).pipe(Effect.withSpan(`fumadb.${label}`));\n\n const transaction = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, E | StorageFailure> =>\n Effect.flatMap(Effect.service(activeFumaDbRef), (active) => {\n if (active) return effect as Effect.Effect<unknown, unknown>;\n\n return Effect.tryPromise({\n try: () =>\n db.transaction(async (transactionDb) => {\n const exit = await Effect.runPromiseExit(\n effect.pipe(Effect.provideService(activeFumaDbRef, transactionDb)),\n );\n if (Exit.isSuccess(exit)) return exit.value;\n\n const failure = exit.cause.reasons.find(Cause.isFailReason);\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: FumaDB transactions roll back when the callback rejects\n if (failure) throw new TransactionEffectFailure(failure.error);\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: FumaDB transactions roll back when the callback rejects\n throw new TransactionEffectDefect(exit.cause);\n }),\n catch: (cause): E | StorageFailure => {\n if (cause instanceof TransactionEffectFailure) return cause.error as E;\n if (cause instanceof TransactionEffectDefect) {\n return fumaFailureFromCause(\"transaction\", cause.cause);\n }\n return fumaFailureFromCause(\"transaction\", cause);\n },\n });\n }).pipe(Effect.withSpan(\"fumadb.transaction\")) as Effect.Effect<A, E | StorageFailure>;\n\n return { use, transaction };\n};\n\nexport class FumaClient extends Context.Service<FumaClient, IFumaClient>()(\"executor/FumaClient\") {\n static layer = (db: FumaDb) => Layer.succeed(this)(makeFumaClient(db));\n}\n","// ---------------------------------------------------------------------------\n// BlobStore — the seam for large, opaque, write-once data. Blobs are stored\n// in FumaDB with their own lifecycle and namespacing, separate from source\n// metadata and plugin-owned config rows.\n//\n// Plugins see a `PluginBlobStore` that's already namespaced to the\n// plugin id and bound to the executor's scope stack. Reads fall through\n// the stack in order (innermost first, first hit wins); writes and\n// deletes require an explicit scope id naming where the operation\n// should land. That mirrors the secrets API — shadowing by key on\n// read, explicit target on write.\n//\n// Error channel is `StorageError` — blobs only do read/write/delete, so\n// they never produce `UniqueViolationError`. The HTTP edge translates\n// `StorageError` to the opaque public `InternalError({ traceId })`.\n// ---------------------------------------------------------------------------\n\nimport { Effect } from \"effect\";\n\nimport { StorageError, type IFumaClient } from \"./fuma-runtime\";\nimport type { Owner } from \"./ids\";\n\nexport interface BlobStore {\n readonly get: (namespace: string, key: string) => Effect.Effect<string | null, StorageError>;\n /** Multi-namespace lookup for a single key. Backends issue one query\n * (`WHERE namespace IN (...) AND key = ?`) and return the hits keyed\n * by namespace — the caller applies its own precedence. Lets\n * `pluginBlobStore` walk the scope stack in O(1) round-trips instead\n * of one per scope. */\n readonly getMany: (\n namespaces: readonly string[],\n key: string,\n ) => Effect.Effect<ReadonlyMap<string, string>, StorageError>;\n readonly put: (\n namespace: string,\n key: string,\n value: string,\n ) => Effect.Effect<void, StorageError>;\n readonly delete: (namespace: string, key: string) => Effect.Effect<void, StorageError>;\n readonly has: (namespace: string, key: string) => Effect.Effect<boolean, StorageError>;\n}\n\nexport interface PluginBlobStore {\n /** Read precedence: this subject's own (`user`) value first, then the\n * org-shared value. Returns the first non-null. */\n readonly get: (key: string) => Effect.Effect<string | null, StorageError>;\n /** Write `value` under `key` for the named owner (`\"org\"` shared, `\"user\"`\n * private). `\"user\"` requires the executor to be bound to a subject. */\n readonly put: (\n key: string,\n value: string,\n options: { readonly owner: Owner },\n ) => Effect.Effect<void, StorageError>;\n /** Delete `key` for the named owner. */\n readonly delete: (\n key: string,\n options: { readonly owner: Owner },\n ) => Effect.Effect<void, StorageError>;\n /** True if either the user or org partition has a value for `key`. */\n readonly has: (key: string) => Effect.Effect<boolean, StorageError>;\n}\n\n/** The owner partition strings an executor binding resolves to: the org\n * partition (always present) and this subject's user partition (null for a\n * pure-org executor). Reads walk `[user, org]`; writes target one. */\nexport interface OwnerPartitions {\n readonly org: string;\n readonly user: string | null;\n}\n\nconst nsFor = (partition: string, pluginId: string) => `${partition}/${pluginId}`;\n\n/**\n * Bind a `BlobStore` to an owner partitioning + plugin id. Reads fall through\n * `[user, org]` (user first); writes target an explicit owner. Used by the\n * executor to build the `blobs` field handed to each plugin's `storage` factory.\n */\nexport const pluginBlobStore = (\n store: BlobStore,\n partitions: OwnerPartitions,\n pluginId: string,\n): PluginBlobStore => {\n const readNamespaces = (): readonly string[] =>\n (partitions.user == null ? [partitions.org] : [partitions.user, partitions.org]).map((p) =>\n nsFor(p, pluginId),\n );\n\n const partitionFor = (owner: Owner): Effect.Effect<string, StorageError> => {\n if (owner === \"org\") return Effect.succeed(partitions.org);\n if (partitions.user == null) {\n return Effect.fail(\n new StorageError({\n message: 'Blob write targets owner \"user\" but the executor has no subject.',\n cause: undefined,\n }),\n );\n }\n return Effect.succeed(partitions.user);\n };\n\n return {\n get: (key) =>\n Effect.gen(function* () {\n const namespaces = readNamespaces();\n const hits = yield* store.getMany(namespaces, key);\n if (hits.size === 0) return null;\n for (const ns of namespaces) {\n const v = hits.get(ns);\n if (v !== undefined) return v;\n }\n return null;\n }),\n put: (key, value, options) =>\n Effect.flatMap(partitionFor(options.owner), (partition) =>\n store.put(nsFor(partition, pluginId), key, value),\n ),\n delete: (key, options) =>\n Effect.flatMap(partitionFor(options.owner), (partition) =>\n store.delete(nsFor(partition, pluginId), key),\n ),\n has: (key) => store.getMany(readNamespaces(), key).pipe(Effect.map((hits) => hits.size > 0)),\n };\n};\n\n/**\n * Minimal in-memory BlobStore — good for tests and trivial hosts. Real\n * backends (filesystem, S3/R2, SQLite-table-backed) implement the same\n * interface.\n *\n * Every method is `Effect<_, never>` — a pure in-memory Map can't fail.\n * `never` is assignable to `StorageError`, so the result still fits the\n * `BlobStore` interface.\n */\nexport const makeInMemoryBlobStore = (): BlobStore => {\n const store = new Map<string, string>();\n const k = (ns: string, key: string) => `${ns}::${key}`;\n return {\n get: (ns, key) => Effect.sync(() => store.get(k(ns, key)) ?? null),\n getMany: (namespaces, key) =>\n Effect.sync(() => {\n const hits = new Map<string, string>();\n for (const ns of namespaces) {\n const v = store.get(k(ns, key));\n if (v !== undefined) hits.set(ns, v);\n }\n return hits;\n }),\n put: (ns, key, value) =>\n Effect.sync(() => {\n store.set(k(ns, key), value);\n }),\n delete: (ns, key) =>\n Effect.sync(() => {\n store.delete(k(ns, key));\n }),\n has: (ns, key) => Effect.sync(() => store.has(k(ns, key))),\n };\n};\n\n/** Hex SHA-256 of a UTF-8 string — the content-address key plugins use for\n * write-once blobs (`put(key(hash), …)` is then idempotent and orphaned\n * writes are harmless). Web Crypto, so it runs on Workers/Bun/Node alike. */\nexport const sha256Hex = (text: string): Effect.Effect<string> =>\n Effect.promise(async () => {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n });\n\nconst blobId = (namespace: string, key: string): string => JSON.stringify([namespace, key]);\n\ntype BlobRow = {\n readonly id: string;\n readonly namespace: string;\n readonly key: string;\n readonly value: string;\n};\n\nconst toBlobRows = (rows: unknown): readonly BlobRow[] => rows as readonly BlobRow[];\n\nexport const makeFumaBlobStore = (fuma: IFumaClient): BlobStore => ({\n get: (namespace, key) =>\n fuma\n .use(\"blob.get\", (db) =>\n db.findFirst(\"blob\", {\n where: (b) => b.and(b(\"namespace\", \"=\", namespace), b(\"key\", \"=\", key)),\n }),\n )\n .pipe(Effect.map((row) => row as BlobRow | null))\n .pipe(\n Effect.map((row) => row?.value ?? null),\n Effect.mapError(\n (cause) => new StorageError({ message: \"FumaDB blob operation failed\", cause }),\n ),\n ),\n getMany: (namespaces, key) =>\n namespaces.length === 0\n ? Effect.succeed(new Map<string, string>())\n : fuma\n .use(\"blob.getMany\", (db) =>\n db.findMany(\"blob\", {\n where: (b) => b.and(b(\"namespace\", \"in\", [...namespaces]), b(\"key\", \"=\", key)),\n }),\n )\n .pipe(Effect.map(toBlobRows))\n .pipe(\n Effect.map((rows) => {\n const out = new Map<string, string>();\n for (const row of rows) out.set(row.namespace, row.value);\n return out;\n }),\n Effect.mapError(\n (cause) => new StorageError({ message: \"FumaDB blob operation failed\", cause }),\n ),\n ),\n put: (namespace, key, value) =>\n Effect.gen(function* () {\n const id = blobId(namespace, key);\n const existing = (yield* fuma.use(\"blob.findForPut\", (db) =>\n db.findFirst(\"blob\", { where: (b) => b(\"id\", \"=\", id) }),\n )) as BlobRow | null;\n if (existing) {\n yield* fuma.use(\"blob.update\", (db) =>\n db.updateMany(\"blob\", { where: (b) => b(\"id\", \"=\", id), set: { value } }),\n );\n return;\n }\n yield* fuma.use(\"blob.create\", (db) => db.create(\"blob\", { id, namespace, key, value }));\n }).pipe(\n Effect.mapError(\n (cause) => new StorageError({ message: \"FumaDB blob operation failed\", cause }),\n ),\n ),\n delete: (namespace, key) =>\n fuma\n .use(\"blob.delete\", (db) =>\n db.deleteMany(\"blob\", { where: (b) => b(\"id\", \"=\", blobId(namespace, key)) }),\n )\n .pipe(\n Effect.asVoid,\n Effect.mapError(\n (cause) => new StorageError({ message: \"FumaDB blob operation failed\", cause }),\n ),\n ),\n has: (namespace, key) =>\n fuma\n .use(\"blob.has\", (db) =>\n db.count(\"blob\", { where: (b) => b(\"id\", \"=\", blobId(namespace, key)) }),\n )\n .pipe(\n Effect.map((count) => count > 0),\n Effect.mapError(\n (cause) => new StorageError({ message: \"FumaDB blob operation failed\", cause }),\n ),\n ),\n});\n","import { Effect, type Schema as EffectSchema } 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 { StorageFailure } from \"./fuma-runtime\";\n\nimport type { PluginBlobStore } from \"./blob\";\nimport type {\n Connection,\n ConnectionRef,\n CreateConnectionInput,\n UpdateConnectionInput,\n} from \"./connection\";\nimport type {\n AuthMethodDescriptor,\n Integration,\n IntegrationConfig,\n IntegrationDisplayDescriptor,\n RegisterIntegrationInput,\n} from \"./integration\";\nimport type { ToolInvocationRow } from \"./core-schema\";\nimport type {\n AuthTemplateSlug,\n ConnectionName,\n IntegrationSlug,\n Owner,\n ProviderKey,\n Subject,\n Tenant,\n} from \"./ids\";\nimport type { IntegrationDetectionResult } from \"./types\";\nimport type {\n ElicitationDeclinedError,\n ElicitationHandler,\n ElicitationRequest,\n ElicitationResponse,\n} from \"./elicitation\";\nimport type {\n ConnectionNotFoundError,\n CredentialProviderNotRegisteredError,\n IntegrationNotFoundError,\n IntegrationRemovalNotAllowedError,\n InvalidConnectionInputError,\n} from \"./errors\";\nimport type { OAuthService } from \"./oauth-client\";\nimport type { CredentialProvider, ProviderEntry } from \"./provider\";\nimport type { PluginStorageConfig, PluginStorageFacade } from \"./plugin-storage\";\nimport type {\n CreateToolPolicyInput,\n EffectivePolicy,\n RemoveToolPolicyInput,\n ToolPolicy,\n UpdateToolPolicyInput,\n} from \"./policies\";\nimport type { Tool, ToolAnnotations, ToolDef } from \"./tool\";\n\n// ---------------------------------------------------------------------------\n// OwnerBinding — replaces v1's scope stack. The (tenant, subject?) the executor\n// acts as. `owner:\"user\"` writes require a subject; pure-org executors leave it\n// null. Plugins rarely read this — core handles partitioning — but it's exposed\n// for plugins that label or key their own state by owner.\n// ---------------------------------------------------------------------------\n\nexport interface OwnerBinding {\n readonly tenant: Tenant;\n readonly subject: Subject | null;\n}\n\n// ---------------------------------------------------------------------------\n// StorageDeps — backing passed to a plugin's `storage` factory. Plugins see\n// host-owned storage facades only. The (tenant, owner, subject) partition is\n// the host's concern; plugin storage is already owner-scoped under the hood.\n// ---------------------------------------------------------------------------\n\nexport interface StorageDeps {\n readonly owner: OwnerBinding;\n readonly blobs: PluginBlobStore;\n readonly pluginStorage: PluginStorageFacade;\n}\n\n// ---------------------------------------------------------------------------\n// Elicit — suspends the fiber, calls the invoke-time elicitation handler,\n// resumes with the user's response. Available on static tool handlers and\n// dynamic `invokeTool` handlers.\n// ---------------------------------------------------------------------------\n\nexport type Elicit = (\n request: ElicitationRequest,\n) => Effect.Effect<ElicitationResponse, ElicitationDeclinedError>;\n\n// ---------------------------------------------------------------------------\n// Active tool-policy provider.\n//\n// Normal executors resolve policies from core's owner-scoped `tool_policy`\n// table. A plugin may opt one executor instance into a different rule source\n// (for example, a toolkit-specific policy set). Core still owns enforcement;\n// the plugin owns where those policy-shaped rows are stored.\n// ---------------------------------------------------------------------------\n\nexport interface ToolPolicyProviderRule {\n readonly id: string;\n readonly pattern: string;\n readonly action: ToolPolicy[\"action\"];\n readonly position: string;\n}\n\nexport interface ToolPolicyProvider {\n readonly list: () => Effect.Effect<readonly ToolPolicyProviderRule[], StorageFailure>;\n readonly resolve?: (input: {\n readonly toolId: string;\n readonly defaultRequiresApproval?: boolean;\n }) => Effect.Effect<EffectivePolicy, StorageFailure>;\n /**\n * Batched per-operation resolver. When defined, core calls `prepare` once at\n * the start of an operation (a single tools/list or tools/call), fetching all\n * the underlying policy + connection state in one pass, and reuses the\n * returned pure resolver for every tool in that operation. This avoids the\n * per-tool `resolve` N+1 (2 uncached storage reads per tool) that scales with\n * the total catalog size on `toolsList`.\n *\n * The resolver is intentionally per-operation scoped, not memoized on the\n * provider: the provider instance is session-scoped (lives across many\n * requests), so caching on it would serve stale policy state. Each operation\n * gets a fresh snapshot.\n */\n readonly prepare?: () => Effect.Effect<\n (input: {\n readonly toolId: string;\n readonly defaultRequiresApproval?: boolean;\n }) => EffectivePolicy,\n StorageFailure\n >;\n}\n\n// ---------------------------------------------------------------------------\n// IntegrationRecord — the catalog row a plugin reads back (its own opaque\n// `config` included). Returned by `ctx.core.integrations.get`.\n// ---------------------------------------------------------------------------\n\nexport interface IntegrationRecord extends Integration {\n readonly config: IntegrationConfig;\n}\n\n// ---------------------------------------------------------------------------\n// PluginCtx — threaded into every extension method, static tool handler, and\n// dynamic tool handler. The v2 fold: `core.sources` → `core.integrations`,\n// `secrets`/`connections`/`credentialBindings` → `connections` (provider-\n// resolved) + `providers`, `scopes` → `owner`.\n// ---------------------------------------------------------------------------\n\nexport interface PluginCtx<TStore = unknown> {\n readonly owner: OwnerBinding;\n readonly storage: TStore;\n readonly pluginStorage: PluginStorageFacade;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient>;\n\n readonly core: {\n readonly integrations: {\n /** Register / replace this plugin's integration in the catalog. */\n readonly register: (input: RegisterIntegrationInput) => Effect.Effect<void, StorageFailure>;\n readonly update: (\n slug: IntegrationSlug,\n patch: {\n readonly name?: string;\n readonly description?: string;\n readonly config?: IntegrationConfig;\n },\n ) => Effect.Effect<void, StorageFailure>;\n readonly list: () => Effect.Effect<readonly Integration[], StorageFailure>;\n readonly get: (\n slug: IntegrationSlug,\n ) => Effect.Effect<IntegrationRecord | null, StorageFailure>;\n readonly remove: (\n slug: IntegrationSlug,\n ) => Effect.Effect<void, IntegrationRemovalNotAllowedError | StorageFailure>;\n readonly detect: (\n url: string,\n ) => Effect.Effect<readonly IntegrationDetectionResult[], StorageFailure>;\n readonly configureSchemas: () => readonly IntegrationConfigureSchema[];\n readonly presets: () => readonly IntegrationPresetCatalogEntry[];\n };\n readonly policies: {\n readonly list: () => Effect.Effect<readonly ToolPolicy[], StorageFailure>;\n readonly create: (input: CreateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;\n readonly update: (input: UpdateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;\n readonly remove: (input: RemoveToolPolicyInput) => Effect.Effect<void, StorageFailure>;\n };\n };\n\n /** Saved credentials. A connection IS the credential; resolve its value\n * (refreshing OAuth tokens as needed) via `resolveValue`. */\n readonly connections: {\n readonly create: (\n input: CreateConnectionInput,\n ) => Effect.Effect<\n Connection,\n | IntegrationNotFoundError\n | CredentialProviderNotRegisteredError\n | InvalidConnectionInputError\n | StorageFailure\n >;\n readonly list: (filter?: {\n readonly integration?: IntegrationSlug;\n readonly owner?: Owner;\n }) => Effect.Effect<readonly Connection[], StorageFailure>;\n readonly get: (ref: ConnectionRef) => Effect.Effect<Connection | null, StorageFailure>;\n /** Edit user-curated metadata (description, identityLabel). */\n readonly update: (\n ref: ConnectionRef,\n input: UpdateConnectionInput,\n ) => Effect.Effect<Connection, ConnectionNotFoundError | StorageFailure>;\n readonly remove: (\n ref: ConnectionRef,\n ) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>;\n readonly refresh: (\n ref: ConnectionRef,\n ) => Effect.Effect<\n readonly Tool[],\n ConnectionNotFoundError | IntegrationNotFoundError | StorageFailure\n >;\n /** Resolve a connection's value through its provider (and OAuth refresh).\n * null if the provider can't produce one. */\n readonly resolveValue: (ref: ConnectionRef) => Effect.Effect<string | null, StorageFailure>;\n };\n\n /** Registered credential backends — for discovery (browse a backend's items). */\n readonly providers: {\n readonly list: () => Effect.Effect<readonly ProviderKey[]>;\n readonly items: (\n provider: ProviderKey,\n ) => Effect.Effect<readonly ProviderEntry[], StorageFailure>;\n };\n\n /** Shared OAuth service. */\n readonly oauth: OAuthService;\n\n /** Run `effect` inside a FumaDB transaction (atomic across plugin storage +\n * core integration/tool writes). */\n readonly transaction: <A, E>(effect: Effect.Effect<A, E>) => Effect.Effect<A, E | StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Per-connection tool production (the v2 successor to v1's `sources.register`\n// inside a plugin's addSpec). Called by the executor at connections.create /\n// refresh / oauth.complete; the result is stamped with addresses and persisted.\n// ---------------------------------------------------------------------------\n\nexport interface ResolveToolsInput<TStore = unknown> {\n /** The catalog record (public projection) whose connection is being resolved. */\n readonly integration: Integration;\n /** The plugin's stored opaque config for that integration. */\n readonly config: IntegrationConfig;\n /** The plugin's typed store — the same instance the extension ctx sees.\n * Lets spec-derived plugins load build artifacts kept behind the storage\n * facades (e.g. a content-addressed spec blob) instead of inlining them\n * in `config`. */\n readonly storage: TStore;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient>;\n /** The connection whose tools are being resolved. */\n readonly connection: ConnectionRef;\n /** Which of the integration's declared auth methods the connection binds\n * (`connection.template`), so multi-method integrations render the right\n * one during discovery. `null` when the connection row isn't persisted yet. */\n readonly template: AuthTemplateSlug | null;\n /** Lazily resolve the connection's credential value via its provider — only\n * the kinds that actually call out (mcp) pay for it. */\n readonly getValue: () => Effect.Effect<string | null, StorageFailure>;\n /** Lazily resolve every credential input (`variable → value`) — the\n * multi-input analog of `getValue`, for methods whose placements reference\n * more than one variable. Empty map when the connection isn't persisted. */\n readonly getValues: () => Effect.Effect<Record<string, string | null>, StorageFailure>;\n}\n\nexport interface ResolveToolsResult {\n readonly tools: readonly ToolDef[];\n /** Shared JSON-schema `$defs` reachable from the tools' `$ref`s. */\n readonly definitions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Resolved credential handed to `invokeTool` so the plugin renders auth onto\n// the request (D11: \"auth state derived into the auth-template format\").\n// ---------------------------------------------------------------------------\n\nexport interface ToolInvocationCredential {\n readonly owner: Owner;\n readonly integration: IntegrationSlug;\n readonly connection: ConnectionName;\n readonly template: AuthTemplateSlug;\n /** The primary (`token`) resolved value — for OAuth (the access token) and\n * single-input apiKey methods. Equals `values.token`. */\n readonly value: string | null;\n /** Every resolved credential input (`variable → value`) for the connection.\n * Single-input methods have just `{ token }`; an apiKey method with two\n * distinct inputs (e.g. Datadog) has one entry per template variable. The\n * render layer substitutes each `variable(\"<name>\")` from this map. */\n readonly values: Record<string, string | null>;\n /** The integration's stored config, for template rendering. */\n readonly config: IntegrationConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Static tool / source declarations. Unchanged from v1 except the ctx shape.\n// ---------------------------------------------------------------------------\n\nexport interface StaticToolHandlerInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly args: unknown;\n readonly elicit: Elicit;\n}\n\nexport interface StaticToolExecuteContext<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\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 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 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 readonly canRemove?: boolean;\n readonly canRefresh?: boolean;\n readonly canEdit?: boolean;\n readonly tools: readonly StaticToolDecl<TStore>[];\n}\n\n// ---------------------------------------------------------------------------\n// Dynamic invoke / connection lifecycle inputs.\n// ---------------------------------------------------------------------------\n\nexport interface InvokeToolInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n /** Already-loaded per-connection tool row (carries integration, connection,\n * owner, name, schemas). */\n readonly toolRow: ToolInvocationRow;\n /** The resolved credential to apply to the outbound request. */\n readonly credential: ToolInvocationCredential;\n readonly args: unknown;\n readonly elicit: Elicit;\n}\n\n/** Called when the executor removes / refreshes a connection owned by this\n * plugin's integration — plugin-side cleanup or re-resolution only; the\n * executor handles the core tool rows. */\nexport interface ConnectionLifecycleInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly integration: IntegrationSlug;\n readonly connection: ConnectionRef;\n}\n\nexport interface ConfigureIntegrationHandlerInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly integration: IntegrationSlug;\n readonly config: unknown;\n}\n\nexport interface IntegrationConfigureDecl<TStore = unknown> {\n readonly type: string;\n readonly schema?: StaticToolSchema | EffectSchema.Decoder<unknown, never>;\n readonly configure: (\n input: ConfigureIntegrationHandlerInput<TStore>,\n ) => Effect.Effect<unknown, unknown>;\n}\n\nexport interface IntegrationConfigureSchema {\n readonly pluginId: string;\n readonly type: string;\n readonly schema?: unknown;\n}\n\nexport interface IntegrationPreset {\n readonly id: string;\n readonly name: string;\n readonly summary: string;\n readonly url?: string;\n readonly endpoint?: string;\n readonly icon?: string;\n readonly featured?: boolean;\n readonly transport?: \"remote\" | \"stdio\";\n readonly command?: string;\n readonly args?: readonly string[];\n readonly env?: Readonly<Record<string, string>>;\n}\n\nexport interface IntegrationPresetCatalogEntry extends IntegrationPreset {\n readonly pluginId: string;\n}\n\n// ---------------------------------------------------------------------------\n// PluginSpec — kept from v1 wholesale; only the data-model hooks change.\n// ---------------------------------------------------------------------------\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 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 `./client`\n * import path for the frontend bundle. */\n readonly packageName?: string;\n /** Build the plugin's typed store from host-owned backing. */\n readonly storage: (deps: StorageDeps) => TStore;\n\n /** Host-owned plugin storage declarations. */\n readonly pluginStorage?: PluginStorageConfig;\n\n /** JSON-serializable config the plugin wants its `./client` bundle to see. */\n readonly clientConfig?: unknown;\n\n /** Integration presets shown by the web UI's \"Popular integrations\" list. */\n readonly integrationPresets?: readonly IntegrationPreset[];\n\n /** Build the plugin's extension API — becomes `executor[plugin.id]` and the\n * `self` passed to `staticSources`. Field order matters: `extension` MUST\n * appear before `staticSources`. */\n readonly extension?: (ctx: PluginCtx<TStore>) => TExtension;\n\n /** Static sources contributed by this plugin with inline tool handlers. */\n readonly staticSources?: (self: NoInfer<TExtension>) => readonly StaticSourceDecl<TStore>[];\n\n /** HttpApiGroup contributed by this plugin. */\n readonly routes?: () => TGroup;\n\n /** Handlers Layer for this plugin's group. */\n readonly handlers?: () => THandlersLayer;\n\n /** Service tag the plugin's `handlers` layer requires. */\n readonly extensionService?: TExtensionService;\n\n /** Optional active policy source for this executor instance. At most one\n * loaded plugin may return a provider. When absent, core uses the normal\n * owner-scoped tool policies. */\n readonly toolPolicyProvider?: (\n ctx: PluginCtx<TStore>,\n ) => ToolPolicyProvider | null | Effect.Effect<ToolPolicyProvider | null, StorageFailure>;\n\n /** Produce a connection's tools (and shared $defs). The v2 successor to\n * registering per-source tools — called by the executor at connection\n * create / refresh / oauth.complete; the result is stamped with addresses\n * and persisted per-connection. Omit for plugins with no dynamic tools. */\n readonly resolveTools?: (\n input: ResolveToolsInput<TStore>,\n ) => Effect.Effect<ResolveToolsResult, StorageFailure>;\n\n /** Invoke a dynamic tool. Called when the static-handler map doesn't have the\n * address. The plugin applies `input.credential` to the outbound request. */\n readonly invokeTool?: (input: InvokeToolInput<TStore>) => Effect.Effect<unknown, unknown>;\n\n /** Bulk resolve annotations for a set of tool rows under one connection. */\n readonly resolveAnnotations?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly integration: IntegrationSlug;\n readonly connection: ConnectionName;\n readonly toolRows: readonly ToolInvocationRow[];\n }) => Effect.Effect<Record<string, ToolAnnotations>, unknown>;\n\n /** Plugin-side cleanup when a connection is removed. */\n readonly removeConnection?: (\n input: ConnectionLifecycleInput<TStore>,\n ) => Effect.Effect<void, unknown>;\n\n /** Core-dispatched integration configuration (beyond auth). */\n readonly integrationConfigure?: IntegrationConfigureDecl<TStore>;\n\n /** Project this plugin's opaque integration config into catalog-visible\n * declared auth methods. Synchronous and pure (the config is already loaded);\n * must tolerate a malformed/foreign config blob by returning `[]`. Absent ⇒\n * core surfaces `[]` (the client falls through to its generic fallback). */\n readonly describeAuthMethods?: (\n integration: IntegrationRecord,\n ) => readonly AuthMethodDescriptor[];\n\n /** Project this plugin's opaque integration config into safe catalog-visible\n * display metadata. This is intentionally narrow: the client needs a URL for\n * favicons without receiving the full plugin config. */\n readonly describeIntegrationDisplay?: (\n integration: IntegrationRecord,\n ) => IntegrationDisplayDescriptor;\n\n /** URL autodetection hook for onboarding. */\n readonly detect?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly url: string;\n }) => Effect.Effect<IntegrationDetectionResult | null, unknown>;\n\n /** Credential providers contributed by this plugin (keychain, file, vault, …).\n * The v2 successor to `secretProviders`. */\n readonly credentialProviders?:\n | readonly CredentialProvider[]\n | ((ctx: PluginCtx<TStore>) => readonly CredentialProvider[])\n | ((ctx: PluginCtx<TStore>) => Effect.Effect<readonly CredentialProvider[]>);\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 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, TExtensionService, THandlersLayer, TGroup> {}\n\n// ---------------------------------------------------------------------------\n// definePlugin — factory-returning-spec.\n// ---------------------------------------------------------------------------\n\nexport type ConfiguredPlugin<\n TId extends string,\n TExtension extends object,\n TStore,\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 options?: TOptions & {\n readonly storage?: (deps: StorageDeps) => TStore;\n },\n) => Plugin<TId, TExtension, TStore, 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 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, TExtensionService, THandlersLayer, TGroup>,\n): ConfiguredPlugin<TId, TExtension, TStore, TOptions, TExtensionService, THandlersLayer, TGroup> {\n return (options) => {\n const {\n storage: storageOverride,\n ...rest\n }: {\n storage?: (deps: StorageDeps) => 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\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// Re-exported for consumers that check the elicitation handler type.\nexport type { ElicitationHandler };\n","import { type Condition, type ConditionBuilder } from \"@executor-js/fumadb/query\";\nimport type { AnyColumn, AnyTable } from \"@executor-js/fumadb/schema\";\n\nimport { StorageError } from \"./fuma-runtime\";\n\n/* The v2 owner policy — successor to v1's `executor.scope` policy. Every owned\n * row carries `tenant` + `owner`('org'|'user') + `subject`; org rows use the\n * empty-string sentinel for `subject` (NOT null, so unique indexes stay portable).\n *\n * An executor binds to `{ tenant, subject }`. The policy guards storage so it can\n * only read/write rows it owns:\n * - read/update/delete → tenant matches AND (owner='org' OR subject matches)\n * - create → the written (tenant, owner, subject) must match the binding\n * No scope stack, no innermost-wins shadowing: a tool address names its owner\n * segment, so org and user rows are distinct, both visible to the acting subject. */\n\nexport const executorOwnerPolicyName = \"executor.owner\";\n/** Tenant-shared tables (the integration catalog) — partitioned by `tenant` only. */\nexport const executorTenantPolicyName = \"executor.tenant\";\n/** Truly global tables (the blob store) — isolation carried in the row namespace. */\nexport const executorUnscopedPolicyName = \"executor.unscoped\";\n\n/** Sentinel `subject` value for org-owned rows. */\nexport const ORG_SUBJECT = \"\";\n\nconst unscopedExecutorTables = new Set([\"blob\"]);\n\nexport interface ExecutorOwnerPolicyContext {\n readonly tenant: string;\n /** The acting member, or null for a pure-org executor (no `owner:\"user\"`\n * reads/writes are allowed when null). */\n readonly subject: string | null;\n}\n\ntype AnyConditionBuilder = ConditionBuilder<Record<string, AnyColumn>>;\n\nconst policyViolation = (message: string): never => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: FumaDB table policy callbacks are promise callbacks, not Effect effects\n throw new StorageError({ message, cause: undefined });\n};\n\nconst requireContext = (\n tableName: string,\n access: string,\n context: ExecutorOwnerPolicyContext | undefined,\n): ExecutorOwnerPolicyContext => {\n if (context) return context;\n return policyViolation(\n `Storage ${access} on table \"${tableName}\" is missing executor owner context.`,\n );\n};\n\n/** The rows the bound `{ tenant, subject }` may see/mutate: org rows in the\n * tenant, plus this subject's own user rows. */\nexport const ownerVisibilityCondition = (\n builder: AnyConditionBuilder,\n context: ExecutorOwnerPolicyContext,\n): Condition | boolean => {\n const orgClause = builder.and(\n builder(\"tenant\", \"=\", context.tenant),\n builder(\"owner\", \"=\", \"org\"),\n );\n if (context.subject == null) return orgClause;\n const userClause = builder.and(\n builder(\"tenant\", \"=\", context.tenant),\n builder(\"owner\", \"=\", \"user\"),\n builder(\"subject\", \"=\", context.subject),\n );\n return builder.or(orgClause, userClause);\n};\n\n/** Assert a create/upsert writes a row inside the bound partition. */\nexport const assertOwnerWritable = (\n tableName: string,\n values: Record<string, unknown>,\n context: ExecutorOwnerPolicyContext | undefined,\n): void => {\n const ctx = requireContext(tableName, \"write\", context);\n if (values.tenant !== ctx.tenant) {\n policyViolation(`Storage write on table \"${tableName}\" is outside the executor tenant.`);\n }\n if (values.owner === \"org\") {\n if (values.subject !== ORG_SUBJECT) {\n policyViolation(`Storage write on table \"${tableName}\" set a subject on an org row.`);\n }\n return;\n }\n if (values.owner === \"user\") {\n if (ctx.subject == null || values.subject !== ctx.subject) {\n policyViolation(\n `Storage write on table \"${tableName}\" targets a user row outside the bound subject.`,\n );\n }\n return;\n }\n policyViolation(\n `Storage write on table \"${tableName}\" has an invalid owner \"${String(values.owner)}\".`,\n );\n};\n\n/** Assert a patch (`set`) doesn't move a row out of the bound partition. Only\n * validates the partition columns that are actually being written. */\nexport const assertOwnerPatch = (\n tableName: string,\n patch: Record<string, unknown> | undefined,\n context: ExecutorOwnerPolicyContext | undefined,\n): void => {\n const ctx = requireContext(tableName, \"write\", context);\n if (!patch) return;\n if (patch.tenant !== undefined && patch.tenant !== ctx.tenant) {\n policyViolation(`Storage write on table \"${tableName}\" cannot move a row across tenants.`);\n }\n if (patch.owner === \"user\" && (ctx.subject == null || patch.subject !== ctx.subject)) {\n policyViolation(\n `Storage write on table \"${tableName}\" cannot move a row outside the bound subject.`,\n );\n }\n};\n\nexport const hasExecutorOwnerPolicy = (table: AnyTable): boolean =>\n table.policies.some((policy) => policy.name === executorOwnerPolicyName);\n\nexport function assertExecutorOwnerPolicyTable(table: AnyTable, tableKey?: string): void {\n const tableName = table.ormName || tableKey || table.names.sql;\n const owned = table.policies.find((policy) => policy.name === executorOwnerPolicyName);\n if (owned?.onRead && owned.onCreate && owned.onUpdate && owned.onDelete) return;\n\n const tenant = table.policies.find((policy) => policy.name === executorTenantPolicyName);\n if (tenant?.onRead && tenant.onCreate && tenant.onUpdate && tenant.onDelete) return;\n\n const unscoped = table.policies.find((policy) => policy.name === executorUnscopedPolicyName);\n if (unscoped && unscopedExecutorTables.has(tableName)) return;\n\n policyViolation(`Storage table \"${tableName}\" is missing an executor owner policy.`);\n}\n","import { column, idColumn, table, type AnyColumn, type AnyTable } from \"@executor-js/fumadb/schema\";\nimport type { Condition, ConditionBuilder } from \"@executor-js/fumadb/query\";\n\nimport { StorageError, type FumaRow } from \"./fuma-runtime\";\nimport {\n assertOwnerPatch,\n assertOwnerWritable,\n executorOwnerPolicyName,\n executorTenantPolicyName,\n executorUnscopedPolicyName,\n ownerVisibilityCondition,\n type ExecutorOwnerPolicyContext,\n} from \"./owner-policy\";\n\ntype UserColumns = Record<string, AnyColumn>;\ntype AnyConditionBuilder = ConditionBuilder<Record<string, AnyColumn>>;\n\n// Column helpers. Index-participating columns use `varchar(255)` so unique\n// indexes stay portable (TEXT can't be indexed without a prefix length on\n// MySQL); free-form columns use `string` (TEXT).\nexport const textColumn = (name: string) => column(name, \"string\");\nexport const nullableTextColumn = (name: string) => column(name, \"string\").nullable();\nexport const keyColumn = (name: string) => column(name, \"varchar(255)\");\nexport const nullableKeyColumn = (name: string) => column(name, \"varchar(255)\").nullable();\nexport const boolColumn = (name: string, defaultValue: boolean) =>\n column(name, \"bool\").defaultTo(defaultValue);\nexport const bigintColumn = (name: string) => column(name, \"bigint\");\nexport const nullableBigintColumn = (name: string) => column(name, \"bigint\").nullable();\nexport const jsonColumn = (name: string) => column(name, \"json\");\nexport const nullableJsonColumn = (name: string) => column(name, \"json\").nullable();\nexport const dateColumn = (name: string) => column(name, \"timestamp\");\n\n// The policy callback hands us a `ConditionBuilder` typed to the specific table's\n// columns; it isn't assignable to the generic `Record<string, AnyColumn>` builder\n// (column-name positions are contravariant), so accept it loosely and re-narrow.\nconst ownerVisibility = (builder: unknown, context: ExecutorOwnerPolicyContext) =>\n ownerVisibilityCondition(builder as AnyConditionBuilder, context) as Condition | boolean;\n\n/** A truly global table (the blob store). Isolation is carried in the row's\n * `namespace` (which encodes the owner partition + plugin id), not a policy. */\nconst unscopedExecutorTable = <const TColumns extends UserColumns>(\n name: string,\n columns: TColumns,\n) => {\n const out = table(name, {\n ...columns,\n row_id: idColumn(\"row_id\", \"varchar(255)\").defaultTo$(\"auto\"),\n id: keyColumn(\"id\"),\n });\n out.unique(`${name}_id_uidx`, [\"id\"]);\n return out.policy({ name: executorUnscopedPolicyName });\n};\n\n/** A tenant-shared table (catalog / blobs) — partitioned only by `tenant`. */\nconst tenantExecutorTable = <const TColumns extends UserColumns>(\n name: string,\n columns: TColumns,\n uniqueKey: readonly string[],\n) => {\n const out = table(name, {\n ...columns,\n row_id: idColumn(\"row_id\", \"varchar(255)\").defaultTo$(\"auto\"),\n tenant: keyColumn(\"tenant\"),\n });\n out.unique(`${name}_uidx`, [...uniqueKey]);\n return out.policy<ExecutorOwnerPolicyContext>({\n name: executorTenantPolicyName,\n onRead: ({ builder, context }) => builder(\"tenant\", \"=\", context.tenant),\n onCreate: ({ values, context }) => {\n if (values.tenant !== context.tenant) {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: FumaDB table policy callbacks are promise callbacks, not Effect effects\n throw new StorageError({\n message: `Storage write on table \"${name}\" is outside the executor tenant.`,\n cause: undefined,\n });\n }\n },\n onUpdate: ({ builder, context }) => builder(\"tenant\", \"=\", context.tenant),\n onDelete: ({ builder, context }) => builder(\"tenant\", \"=\", context.tenant),\n });\n};\n\n/** An owner-scoped table — partitioned by `(tenant, owner, subject)`, guarded by\n * the executor owner policy. `uniqueKey` must include those three columns. */\nconst ownedExecutorTable = <const TColumns extends UserColumns>(\n name: string,\n columns: TColumns,\n uniqueKey: readonly string[],\n) => {\n const out = table(name, {\n ...columns,\n row_id: idColumn(\"row_id\", \"varchar(255)\").defaultTo$(\"auto\"),\n tenant: keyColumn(\"tenant\"),\n owner: keyColumn(\"owner\"),\n subject: keyColumn(\"subject\"),\n });\n out.unique(`${name}_uidx`, [...uniqueKey]);\n return out.policy<ExecutorOwnerPolicyContext>({\n name: executorOwnerPolicyName,\n onRead: ({ builder, context }) => ownerVisibility(builder, context),\n onCreate: ({ values, context }) => assertOwnerWritable(name, values, context),\n onUpdate: ({ builder, set, create, context }) => {\n assertOwnerPatch(name, set, context);\n assertOwnerPatch(name, create, context);\n return ownerVisibility(builder, context);\n },\n onDelete: ({ builder, context }) => ownerVisibility(builder, context),\n });\n};\n\nconst defineTables = <const TTables extends Record<string, AnyTable>>(tables: TTables): TTables =>\n tables;\n\nexport const coreTables = defineTables({\n // The catalog — tenant-shared integration definitions. `config` is the owning\n // plugin's opaque blob (openapi auth templates + spec; mcp url). Core never\n // parses it.\n integration: tenantExecutorTable(\n \"integration\",\n {\n slug: keyColumn(\"slug\"),\n plugin_id: textColumn(\"plugin_id\"),\n // Display name. The pre-split field: `description` used to hold the\n // name, so cloud backfills `name` from it (migration 0006) and other\n // hosts fall back at read time (see rowToIntegration). Nullable because\n // SQLite boot-ensure hosts cannot add a NOT NULL column to existing\n // tables, so the column stays nullable even though it is always present\n // in practice.\n name: nullableTextColumn(\"name\"),\n // Actual prose description, now distinct from the name. Nullable: absent\n // until a user/spec supplies one (cloud clears the old duplicated title\n // to NULL in 0006).\n description: nullableTextColumn(\"description\"),\n config: nullableJsonColumn(\"config\"),\n // Epoch ms of the last tool-affecting config change (spec update, auth\n // template edit). Compared against each connection's `tools_synced_at`\n // so OTHER subjects' connections — whose tool rows the updater cannot\n // write under the owner policy — lazily rebuild on their next read.\n config_revised_at: nullableBigintColumn(\"config_revised_at\"),\n can_remove: boolColumn(\"can_remove\", true),\n can_refresh: boolColumn(\"can_refresh\", false),\n created_at: dateColumn(\"created_at\"),\n updated_at: dateColumn(\"updated_at\"),\n },\n [\"tenant\", \"slug\"],\n ),\n\n // THE saved credential, one per (owner, integration, name). Resolves each named\n // input via `provider` + the `item_ids` map (variable → provider item id). A\n // single-secret connection is `{ \"token\": <id> }`; an apiKey method with two\n // distinct inputs (e.g. Datadog) carries one entry per variable. All of a\n // connection's inputs share the one `provider`. OAuth fields null for static.\n connection: ownedExecutorTable(\n \"connection\",\n {\n integration: keyColumn(\"integration\"),\n name: keyColumn(\"name\"),\n template: textColumn(\"template\"),\n provider: textColumn(\"provider\"),\n item_ids: jsonColumn(\"item_ids\"),\n identity_label: nullableTextColumn(\"identity_label\"),\n // User-curated, agent-visible \"what is this connection for\". Settable at\n // create, editable after; never reset by OAuth re-mints.\n description: nullableTextColumn(\"description\"),\n // Epoch ms of the last tool (re)production for this connection. Stale\n // vs the integration's `config_revised_at` → re-produced on next read.\n tools_synced_at: nullableBigintColumn(\"tools_synced_at\"),\n oauth_client: nullableTextColumn(\"oauth_client\"),\n // The OWNER of `oauth_client` (a Personal connection may be minted through\n // a shared Workspace app), set together with `oauth_client`; null for\n // static creds. Stored so every deref (refresh/complete/reconnect) reads it\n // verbatim instead of re-deriving it via a sharing rule.\n oauth_client_owner: nullableTextColumn(\"oauth_client_owner\"),\n refresh_item_id: nullableTextColumn(\"refresh_item_id\"),\n expires_at: nullableBigintColumn(\"expires_at\"),\n oauth_scope: nullableTextColumn(\"oauth_scope\"),\n // Per-connection token endpoint override. Set only when the code was\n // redeemed at a region other than the oauth_client's configured token host\n // (multi-site providers like Datadog signal the org's region on the\n // callback). Null means refresh uses the oauth_client's `token_url`.\n oauth_token_url: nullableTextColumn(\"oauth_token_url\"),\n provider_state: nullableJsonColumn(\"provider_state\"),\n created_at: dateColumn(\"created_at\"),\n updated_at: dateColumn(\"updated_at\"),\n },\n [\"tenant\", \"owner\", \"subject\", \"integration\", \"name\"],\n ),\n\n // A registered OAuth app — owner-scoped (shared org app or a member's BYO app).\n // A registered OAuth app — pure app identity (id/secret + endpoints). It carries\n // NO scopes: what to request is the integration's concern, so the same app can\n // back any integration. The granted scope is recorded per-connection\n // (`connection.oauth_scope`).\n oauth_client: ownedExecutorTable(\n \"oauth_client\",\n {\n slug: keyColumn(\"slug\"),\n authorization_url: textColumn(\"authorization_url\"),\n token_url: textColumn(\"token_url\"),\n grant: textColumn(\"grant\"),\n client_id: textColumn(\"client_id\"),\n // The client secret is NOT stored inline — it's a provider `item_id` that\n // resolves to the value via the default writable credential provider\n // (WorkOS Vault on cloud, the local store on desktop). Null for public /\n // PKCE clients (no secret). Keeps secrets out of plaintext columns.\n client_secret_item_id: nullableTextColumn(\"client_secret_item_id\"),\n // RFC 8707 Resource Indicator (MCP). Sent on the refresh request so the\n // re-minted access token stays bound to the same resource. Null when the\n // provider doesn't use resource indicators.\n resource: nullableTextColumn(\"resource\"),\n // Where this oauth_client came from. Null in old databases is treated as\n // \"manual\" by the service layer.\n origin_kind: nullableTextColumn(\"origin_kind\"),\n origin_integration: nullableTextColumn(\"origin_integration\"),\n created_at: dateColumn(\"created_at\"),\n },\n [\"tenant\", \"owner\", \"subject\", \"slug\"],\n ),\n\n // In-flight OAuth authorization-code flow, keyed by the minted `state`.\n oauth_session: ownedExecutorTable(\n \"oauth_session\",\n {\n state: keyColumn(\"state\"),\n client_slug: textColumn(\"client_slug\"),\n integration: textColumn(\"integration\"),\n name: textColumn(\"name\"),\n template: textColumn(\"template\"),\n redirect_url: textColumn(\"redirect_url\"),\n pkce_verifier: nullableTextColumn(\"pkce_verifier\"),\n identity_label: nullableTextColumn(\"identity_label\"),\n payload: jsonColumn(\"payload\"),\n expires_at: bigintColumn(\"expires_at\"),\n created_at: dateColumn(\"created_at\"),\n },\n [\"tenant\", \"state\"],\n ),\n\n // Persisted, per-connection tools (option C). Address is derived from\n // (integration, owner, connection, name).\n tool: ownedExecutorTable(\n \"tool\",\n {\n integration: keyColumn(\"integration\"),\n connection: keyColumn(\"connection\"),\n plugin_id: textColumn(\"plugin_id\"),\n name: keyColumn(\"name\"),\n description: textColumn(\"description\"),\n input_schema: nullableJsonColumn(\"input_schema\"),\n output_schema: nullableJsonColumn(\"output_schema\"),\n annotations: nullableJsonColumn(\"annotations\"),\n created_at: dateColumn(\"created_at\"),\n updated_at: dateColumn(\"updated_at\"),\n },\n [\"tenant\", \"owner\", \"subject\", \"integration\", \"connection\", \"name\"],\n ),\n\n // Shared JSON-schema $defs, per-connection (mirrors `tool`).\n definition: ownedExecutorTable(\n \"definition\",\n {\n integration: keyColumn(\"integration\"),\n connection: keyColumn(\"connection\"),\n plugin_id: textColumn(\"plugin_id\"),\n name: keyColumn(\"name\"),\n schema: jsonColumn(\"schema\"),\n created_at: dateColumn(\"created_at\"),\n },\n [\"tenant\", \"owner\", \"subject\", \"integration\", \"connection\", \"name\"],\n ),\n\n // User-authored tool policies (approve / require_approval / block).\n tool_policy: ownedExecutorTable(\n \"tool_policy\",\n {\n id: keyColumn(\"id\"),\n pattern: textColumn(\"pattern\"),\n action: textColumn(\"action\"),\n position: textColumn(\"position\"),\n created_at: dateColumn(\"created_at\"),\n updated_at: dateColumn(\"updated_at\"),\n },\n [\"tenant\", \"owner\", \"subject\", \"id\"],\n ),\n\n // Host-owned plugin storage (shared `plugin_storage` table, owner-scoped).\n plugin_storage: ownedExecutorTable(\n \"plugin_storage\",\n {\n plugin_id: keyColumn(\"plugin_id\"),\n collection: keyColumn(\"collection\"),\n key: keyColumn(\"key\"),\n data: jsonColumn(\"data\"),\n created_at: dateColumn(\"created_at\"),\n updated_at: dateColumn(\"updated_at\"),\n },\n [\"tenant\", \"owner\", \"subject\", \"plugin_id\", \"collection\", \"key\"],\n ),\n\n // Opaque blob store, global. Isolation is carried in `namespace` (which\n // encodes the owner partition + plugin id), so this table is unscoped.\n blob: unscopedExecutorTable(\"blob\", {\n namespace: keyColumn(\"namespace\"),\n key: keyColumn(\"key\"),\n value: textColumn(\"value\"),\n }),\n});\n\nexport const coreSchema = coreTables;\nexport type CoreSchema = typeof coreTables;\n\nexport type IntegrationRow = FumaRow<CoreSchema[\"integration\"]>;\nexport type ConnectionRow = FumaRow<CoreSchema[\"connection\"]>;\nexport type OAuthClientRow = FumaRow<CoreSchema[\"oauth_client\"]>;\nexport type OAuthSessionRow = FumaRow<CoreSchema[\"oauth_session\"]>;\nexport type ToolRow = FumaRow<CoreSchema[\"tool\"]>;\n/** The tool-row projection the invoke/list hot paths load: everything except\n * the heavy `input_schema`/`output_schema` JSON, which only `tools.schema`\n * (describe) needs. Plugin `invokeTool` receives this shape — operation\n * details ride in plugin storage or `annotations`, not the row schemas. */\nexport type ToolInvocationRow = Omit<ToolRow, \"input_schema\" | \"output_schema\">;\n/** The columns backing {@link ToolInvocationRow}, for `select` projections. */\nexport const TOOL_INVOCATION_COLUMNS = [\n \"tenant\",\n \"owner\",\n \"subject\",\n \"integration\",\n \"connection\",\n \"plugin_id\",\n \"name\",\n \"description\",\n \"annotations\",\n \"created_at\",\n \"updated_at\",\n] as const satisfies readonly (keyof ToolRow)[];\nexport type DefinitionRow = FumaRow<CoreSchema[\"definition\"]>;\nexport type ToolPolicyRow = FumaRow<CoreSchema[\"tool_policy\"]>;\nexport type PluginStorageRow = FumaRow<CoreSchema[\"plugin_storage\"]>;\nexport type BlobRow = FumaRow<CoreSchema[\"blob\"]>;\n\nexport type ToolPolicyAction = \"approve\" | \"require_approval\" | \"block\";\n\nexport const TOOL_POLICY_ACTIONS = [\n \"approve\",\n \"require_approval\",\n \"block\",\n] as const satisfies readonly ToolPolicyAction[];\n\nexport const isToolPolicyAction = (value: unknown): value is ToolPolicyAction =>\n typeof value === \"string\" && (TOOL_POLICY_ACTIONS as readonly string[]).includes(value);\n","import { Effect } from \"effect\";\n\nimport type { StorageFailure } from \"./fuma-runtime\";\nimport type { Owner } from \"./ids\";\n\nexport type PluginStorageSchema = {\n readonly Type: object;\n};\n\nexport type PluginStorageSchemaType<TSchema extends PluginStorageSchema> = TSchema[\"Type\"];\n\nexport type PluginStorageIndexField<TData extends object> = Extract<keyof TData, string>;\n\nexport type PluginStorageIndexSpec<TData extends object> =\n | PluginStorageIndexField<TData>\n | readonly PluginStorageIndexField<TData>[];\n\nexport type PluginStorageRuntimeIndexSpec = string | readonly string[];\n\nexport interface PluginStorageRuntimeCollectionDefinition {\n readonly name: string;\n readonly schema: PluginStorageSchema;\n readonly indexes: readonly PluginStorageRuntimeIndexSpec[];\n}\n\nexport interface PluginStorageCollectionDefinition<\n TName extends string = string,\n TData extends object = Record<string, unknown>,\n TIndexes extends readonly PluginStorageIndexSpec<TData>[] =\n readonly PluginStorageIndexSpec<TData>[],\n> extends PluginStorageRuntimeCollectionDefinition {\n readonly name: TName;\n readonly schema: PluginStorageSchema;\n readonly indexes: TIndexes;\n}\n\nexport type PluginStorageConfig = Readonly<\n Record<string, PluginStorageRuntimeCollectionDefinition>\n>;\n\nexport const definePluginStorageCollection = <\n const TName extends string,\n const TSchema extends PluginStorageSchema,\n const TIndexes extends readonly PluginStorageIndexSpec<PluginStorageSchemaType<TSchema>>[] =\n readonly [],\n>(\n name: TName,\n schema: TSchema,\n options?: {\n readonly indexes?: TIndexes;\n },\n): PluginStorageCollectionDefinition<TName, PluginStorageSchemaType<TSchema>, TIndexes> => ({\n name,\n schema,\n indexes: (options?.indexes ?? []) as TIndexes,\n});\n\nexport type PluginStorageCollectionData<TDefinition> =\n TDefinition extends PluginStorageCollectionDefinition<infer _Name, infer TData, infer _Indexes>\n ? TData\n : never;\n\nexport type PluginStorageIndexFields<TIndexes> = TIndexes extends readonly (infer TIndex)[]\n ? TIndex extends readonly (infer TField)[]\n ? Extract<TField, string>\n : Extract<TIndex, string>\n : never;\n\nexport type PluginStorageCollectionIndexedField<TDefinition> =\n TDefinition extends PluginStorageCollectionDefinition<infer _Name, infer _Data, infer TIndexes>\n ? PluginStorageIndexFields<TIndexes>\n : never;\n\nexport interface PluginStorageWhereFilter<TValue> {\n readonly eq?: TValue;\n readonly in?: readonly TValue[];\n readonly gt?: TValue;\n readonly gte?: TValue;\n readonly lt?: TValue;\n readonly lte?: TValue;\n}\n\nexport type PluginStorageWhereValue<TValue> = TValue | PluginStorageWhereFilter<TValue>;\n\nexport type PluginStorageCollectionWhere<TDefinition> = {\n readonly [TField in PluginStorageCollectionIndexedField<TDefinition>]?: PluginStorageWhereValue<\n TField extends keyof PluginStorageCollectionData<TDefinition>\n ? PluginStorageCollectionData<TDefinition>[TField]\n : never\n >;\n};\n\nexport interface PluginStorageCollectionOrderBy<TDefinition> {\n readonly field: PluginStorageCollectionIndexedField<TDefinition>;\n readonly direction?: \"asc\" | \"desc\";\n}\n\nexport interface PluginStorageKeyInput {\n readonly collection: string;\n readonly key: string;\n}\n\nexport interface PluginStorageScopedKeyInput extends PluginStorageKeyInput {\n readonly owner: Owner;\n}\n\nexport interface PluginStorageListInput {\n readonly collection: string;\n readonly keyPrefix?: string;\n}\n\nexport interface PluginStoragePutInput extends PluginStorageScopedKeyInput {\n readonly data: unknown;\n}\n\nexport interface PluginStoragePutManyEntry extends PluginStorageKeyInput {\n readonly data: unknown;\n}\n\nexport interface PluginStoragePutManyInput {\n readonly owner: Owner;\n readonly entries: readonly PluginStoragePutManyEntry[];\n}\n\nexport interface PluginStorageRemoveManyInput {\n readonly owner: Owner;\n readonly entries: readonly PluginStorageKeyInput[];\n}\n\nexport interface PluginStorageCollectionKeyInput {\n readonly key: string;\n}\n\nexport interface PluginStorageCollectionScopedKeyInput extends PluginStorageCollectionKeyInput {\n readonly owner: Owner;\n}\n\nexport interface PluginStorageCollectionListInput {\n readonly keyPrefix?: string;\n}\n\nexport interface PluginStorageCollectionPutInput<\n TData extends object,\n> extends PluginStorageCollectionScopedKeyInput {\n readonly data: TData;\n}\n\nexport interface PluginStorageCollectionQueryInput<TDefinition> {\n readonly keyPrefix?: string;\n readonly where?: PluginStorageCollectionWhere<TDefinition>;\n readonly orderBy?: readonly PluginStorageCollectionOrderBy<TDefinition>[];\n readonly limit?: number;\n readonly offset?: number;\n}\n\nexport interface PluginStorageEntry<T = unknown> {\n readonly id: string;\n readonly owner: Owner;\n readonly pluginId: string;\n readonly collection: string;\n readonly key: string;\n readonly data: T;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\nexport interface PluginStorageCollectionFacade<\n TDefinition extends PluginStorageCollectionDefinition = PluginStorageCollectionDefinition,\n> {\n readonly get: (\n input: PluginStorageCollectionKeyInput,\n ) => Effect.Effect<\n PluginStorageEntry<PluginStorageCollectionData<TDefinition>> | null,\n StorageFailure\n >;\n readonly getForOwner: (\n input: PluginStorageCollectionScopedKeyInput,\n ) => Effect.Effect<\n PluginStorageEntry<PluginStorageCollectionData<TDefinition>> | null,\n StorageFailure\n >;\n readonly list: (\n input?: PluginStorageCollectionListInput,\n ) => Effect.Effect<\n readonly PluginStorageEntry<PluginStorageCollectionData<TDefinition>>[],\n StorageFailure\n >;\n readonly put: (\n input: PluginStorageCollectionPutInput<PluginStorageCollectionData<TDefinition>>,\n ) => Effect.Effect<PluginStorageEntry<PluginStorageCollectionData<TDefinition>>, StorageFailure>;\n readonly query: (\n input?: PluginStorageCollectionQueryInput<TDefinition>,\n ) => Effect.Effect<\n readonly PluginStorageEntry<PluginStorageCollectionData<TDefinition>>[],\n StorageFailure\n >;\n readonly count: (\n input?: Omit<PluginStorageCollectionQueryInput<TDefinition>, \"orderBy\" | \"limit\" | \"offset\">,\n ) => Effect.Effect<number, StorageFailure>;\n readonly remove: (\n input: PluginStorageCollectionScopedKeyInput,\n ) => Effect.Effect<void, StorageFailure>;\n}\n\nexport interface PluginStorageFacade {\n readonly collection: <const TDefinition extends PluginStorageCollectionDefinition>(\n definition: TDefinition,\n ) => PluginStorageCollectionFacade<TDefinition>;\n readonly get: <T = unknown>(\n input: PluginStorageKeyInput,\n ) => Effect.Effect<PluginStorageEntry<T> | null, StorageFailure>;\n readonly getForOwner: <T = unknown>(\n input: PluginStorageScopedKeyInput,\n ) => Effect.Effect<PluginStorageEntry<T> | null, StorageFailure>;\n readonly list: <T = unknown>(\n input: PluginStorageListInput,\n ) => Effect.Effect<readonly PluginStorageEntry<T>[], StorageFailure>;\n readonly put: <T = unknown>(\n input: PluginStoragePutInput,\n ) => Effect.Effect<PluginStorageEntry<T>, StorageFailure>;\n readonly putMany: (input: PluginStoragePutManyInput) => Effect.Effect<void, StorageFailure>;\n readonly remove: (input: PluginStorageScopedKeyInput) => Effect.Effect<void, StorageFailure>;\n readonly removeMany: (input: PluginStorageRemoveManyInput) => Effect.Effect<void, StorageFailure>;\n}\n\nexport const pluginStorageId = (input: {\n readonly pluginId: string;\n readonly collection: string;\n readonly key: string;\n}): string => JSON.stringify([input.pluginId, input.collection, input.key]);\n","// ---------------------------------------------------------------------------\n// JSON Schema $ref hoisting and re-attachment\n//\n// Core logic for deduplicating shared definitions across tools.\n// Used by any ToolRegistry implementation (in-memory, database-backed, etc.)\n//\n// Only handles standard JSON Schema formats ($defs, definitions).\n// Plugin-specific formats (e.g. OpenAPI components/schemas) must be\n// normalized by the plugin before calling registerDefinitions/register.\n// ---------------------------------------------------------------------------\n\ntype Obj = Record<string, unknown>;\n\n/** Standard JSON Schema $ref patterns. */\nconst REF_PATTERN = /^#\\/(?:\\$defs|definitions)\\/(.+)$/;\n\n/** Extract the definition name from a standard $ref pointer. */\nconst parseRefName = (ref: string): string | undefined => ref.match(REF_PATTERN)?.[1];\n\n/**\n * Recursively rewrite `#/definitions/<name>` pointers to `#/$defs/<name>`.\n * Returns the input unchanged if no rewrites are needed.\n */\nexport const normalizeRefs = (node: unknown): unknown => {\n if (node == null || typeof node !== \"object\") return node;\n if (Array.isArray(node)) {\n let changed = false;\n const out = node.map((item) => {\n const n = normalizeRefs(item);\n if (n !== item) changed = true;\n return n;\n });\n return changed ? out : node;\n }\n\n const obj = node as Obj;\n\n if (typeof obj.$ref === \"string\") {\n const name = parseRefName(obj.$ref);\n if (name) {\n const canonical = `#/$defs/${name}`;\n return canonical !== obj.$ref ? { ...obj, $ref: canonical } : obj;\n }\n return obj;\n }\n\n let changed = false;\n const result: Obj = {};\n for (const [k, v] of Object.entries(obj)) {\n const n = normalizeRefs(v);\n if (n !== v) changed = true;\n result[k] = n;\n }\n return changed ? result : obj;\n};\n\n/**\n * Extract `$defs` and `definitions` from a JSON Schema,\n * returning { stripped, defs } where `stripped` is the schema without local\n * definitions and `defs` is a flat map of definition name → schema.\n */\nexport const hoistDefinitions = (\n schema: unknown,\n): { stripped: unknown; defs: Record<string, unknown> } => {\n if (schema == null || typeof schema !== \"object\") {\n return { stripped: schema, defs: {} };\n }\n const obj = schema as Obj;\n const defs: Record<string, unknown> = {};\n\n if (obj.$defs && typeof obj.$defs === \"object\") {\n for (const [k, v] of Object.entries(obj.$defs as Obj)) {\n defs[k] = v;\n }\n }\n\n if (obj.definitions && typeof obj.definitions === \"object\") {\n for (const [k, v] of Object.entries(obj.definitions as Obj)) {\n defs[k] = v;\n }\n }\n\n const { $defs: _a, definitions: _b, ...rest } = obj;\n return { stripped: rest, defs };\n};\n\n/**\n * Walk a schema and collect all $ref target names transitively.\n * e.g. \"#/$defs/Address\" → \"Address\", and if Address references City, both.\n */\nexport const collectRefs = (\n node: unknown,\n defs: ReadonlyMap<string, unknown>,\n found: Set<string> = new Set(),\n): Set<string> => {\n if (node == null || typeof node !== \"object\") return found;\n const obj = node as Obj;\n\n if (typeof obj.$ref === \"string\") {\n const name = parseRefName(obj.$ref);\n if (name && !found.has(name)) {\n found.add(name);\n const def = defs.get(name);\n if (def) collectRefs(def, defs, found);\n }\n return found;\n }\n\n for (const v of Object.values(obj)) {\n if (v && typeof v === \"object\") {\n if (Array.isArray(v)) {\n for (const item of v) collectRefs(item, defs, found);\n } else {\n collectRefs(v, defs, found);\n }\n }\n }\n return found;\n};\n\nexport const collectReferencedDefinitions = (\n roots: readonly unknown[],\n defs: ReadonlyMap<string, unknown>,\n): Record<string, unknown> => {\n const refs = new Set<string>();\n for (const root of roots) {\n collectRefs(root, defs, refs);\n }\n\n const referenced: Record<string, unknown> = {};\n for (const name of refs) {\n const def = defs.get(name);\n if (def) referenced[name] = def;\n }\n return referenced;\n};\n\n/**\n * Re-attach only the referenced shared definitions into a schema,\n * so the caller gets a self-contained, usable JSON Schema.\n *\n * Assumes all `$ref` pointers and definitions have already been normalized\n * to `#/$defs/<name>` form at registration time.\n */\nexport const reattachDefs = (schema: unknown, defs: ReadonlyMap<string, unknown>): unknown => {\n if (schema == null || typeof schema !== \"object\") return schema;\n const attached = collectReferencedDefinitions([schema], defs);\n if (Object.keys(attached).length === 0) return schema;\n\n return { ...(schema as Record<string, unknown>), $defs: attached };\n};\n","import { Struct } from \"effect\";\n\n// Keep these helpers deliberately small and local. They preserve only the\n// upstream helper behavior this vendored compiler actually uses.\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nexport const cloneDeep = <T>(value: T): T => structuredClone(value);\n\nexport const merge = <T extends object>(\n target: T,\n ...sources: ReadonlyArray<object | undefined>\n): T => {\n const output = target as Record<string, unknown>;\n for (const source of sources) {\n if (!source) continue;\n for (const [key, value] of Object.entries(source as Record<string, unknown>)) {\n const current = output[key];\n output[key] =\n isPlainObject(current) && isPlainObject(value)\n ? merge({ ...current }, value)\n : cloneDeep(value);\n }\n }\n return target;\n};\n\nexport const findKey = <T>(\n object: Record<string, T> | undefined,\n predicate: (value: T, key: string) => boolean,\n): string | undefined => {\n if (!object) return undefined;\n for (const [key, value] of Object.entries(object)) {\n if (predicate(value, key)) return key;\n }\n return undefined;\n};\n\nexport const memoize = <F extends (arg: any, ...rest: any[]) => any>(fn: F): F => {\n const cache = new Map<Parameters<F>[0], ReturnType<F>>();\n return ((arg: Parameters<F>[0], ...rest: unknown[]) => {\n if (cache.has(arg)) return cache.get(arg);\n const value = fn(arg, ...rest);\n cache.set(arg, value);\n return value;\n }) as F;\n};\n\nexport const omit = <T extends object, K extends keyof T>(object: T, ...keys: K[]): Omit<T, K> =>\n Struct.omit(object, keys);\n\nexport const uniqBy = <T>(items: ReadonlyArray<T>, iteratee: (value: T) => string): T[] => {\n const seen = new Set<string>();\n const result: T[] = [];\n for (const item of items) {\n const key = iteratee(item);\n if (seen.has(key)) continue;\n seen.add(key);\n result.push(item);\n }\n return result;\n};\n\nexport const deburr = (value: string): string =>\n value.normalize(\"NFD\").replace(/[\\u0300-\\u036f]/g, \"\");\n\nexport const upperFirst = (value: string): string =>\n value.length === 0 ? value : value[0]!.toUpperCase() + value.slice(1);\n","import type { Options } from \"./\";\n\nexport function format(code: string, options: Options): string {\n void options;\n return code;\n}\n","import type { JSONSchema4Type } from \"./json-schema\";\n\nexport type AST_TYPE = AST[\"type\"];\n\nexport type AST =\n | TAny\n | TArray\n | TBoolean\n | TEnum\n | TInterface\n | TNamedInterface\n | TIntersection\n | TLiteral\n | TNever\n | TNumber\n | TNull\n | TObject\n | TReference\n | TString\n | TTuple\n | TUnion\n | TUnknown\n | TCustomType;\n\nexport interface AbstractAST {\n comment?: string;\n keyName?: string;\n standaloneName?: string;\n type: AST_TYPE;\n deprecated?: boolean;\n}\n\nexport type ASTWithComment = AST & { comment: string };\nexport type ASTWithName = AST & { keyName: string };\nexport type ASTWithStandaloneName = AST & { standaloneName: string };\n\nexport function hasComment(ast: AST): ast is ASTWithComment {\n return (\n (\"comment\" in ast && ast.comment != null && ast.comment !== \"\") ||\n // Compare to true because ast.deprecated might be undefined\n (\"deprecated\" in ast && ast.deprecated === true)\n );\n}\n\nexport function hasStandaloneName(ast: AST): ast is ASTWithStandaloneName {\n return \"standaloneName\" in ast && ast.standaloneName != null && ast.standaloneName !== \"\";\n}\n\n//////////////////////////////////////////// types\n\nexport interface TAny extends AbstractAST {\n type: \"ANY\";\n}\n\nexport interface TArray extends AbstractAST {\n type: \"ARRAY\";\n params: AST;\n}\n\nexport interface TBoolean extends AbstractAST {\n type: \"BOOLEAN\";\n}\n\nexport interface TEnum extends AbstractAST {\n standaloneName: string;\n type: \"ENUM\";\n params: TEnumParam[];\n}\n\nexport interface TEnumParam {\n ast: AST;\n keyName: string;\n}\n\nexport interface TInterface extends AbstractAST {\n type: \"INTERFACE\";\n params: TInterfaceParam[];\n superTypes: TNamedInterface[];\n}\n\nexport interface TNamedInterface extends AbstractAST {\n standaloneName: string;\n type: \"INTERFACE\";\n params: TInterfaceParam[];\n superTypes: TNamedInterface[];\n}\n\nexport interface TNever extends AbstractAST {\n type: \"NEVER\";\n}\n\nexport interface TInterfaceParam {\n ast: AST;\n keyName: string;\n isRequired: boolean;\n isPatternProperty: boolean;\n isUnreachableDefinition: boolean;\n}\n\nexport interface TIntersection extends AbstractAST {\n type: \"INTERSECTION\";\n params: AST[];\n}\n\nexport interface TLiteral extends AbstractAST {\n params: JSONSchema4Type;\n type: \"LITERAL\";\n}\n\nexport interface TNumber extends AbstractAST {\n type: \"NUMBER\";\n}\n\nexport interface TNull extends AbstractAST {\n type: \"NULL\";\n}\n\nexport interface TObject extends AbstractAST {\n type: \"OBJECT\";\n}\n\nexport interface TReference extends AbstractAST {\n type: \"REFERENCE\";\n params: string;\n}\n\nexport interface TString extends AbstractAST {\n type: \"STRING\";\n}\n\nexport interface TTuple extends AbstractAST {\n type: \"TUPLE\";\n params: AST[];\n spreadParam?: AST;\n minItems: number;\n maxItems?: number;\n}\n\nexport interface TUnion extends AbstractAST {\n type: \"UNION\";\n params: AST[];\n}\n\nexport interface TUnknown extends AbstractAST {\n type: \"UNKNOWN\";\n}\n\nexport interface TCustomType extends AbstractAST {\n type: \"CUSTOM_TYPE\";\n params: string;\n}\n\n//////////////////////////////////////////// literals\n\nexport const T_ANY: TAny = {\n type: \"ANY\",\n};\n\nexport const T_ANY_ADDITIONAL_PROPERTIES: TAny & ASTWithName = {\n keyName: \"[k: string]\",\n type: \"ANY\",\n};\n\nexport const T_UNKNOWN: TUnknown = {\n type: \"UNKNOWN\",\n};\n\nexport const T_UNKNOWN_ADDITIONAL_PROPERTIES: TUnknown & ASTWithName = {\n keyName: \"[k: string]\",\n type: \"UNKNOWN\",\n};\n","import type { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from \"./json-schema\";\nimport { isPlainObject, memoize } from \"../compat\";\n\nexport type SchemaType =\n | \"ALL_OF\"\n | \"UNNAMED_SCHEMA\"\n | \"ANY\"\n | \"ANY_OF\"\n | \"BOOLEAN\"\n | \"NAMED_ENUM\"\n | \"NAMED_SCHEMA\"\n | \"NEVER\"\n | \"NULL\"\n | \"NUMBER\"\n | \"STRING\"\n | \"OBJECT\"\n | \"ONE_OF\"\n | \"TYPED_ARRAY\"\n | \"REFERENCE\"\n | \"UNION\"\n | \"UNNAMED_ENUM\"\n | \"UNTYPED_ARRAY\"\n | \"CUSTOM_TYPE\";\n\nexport type JSONSchemaTypeName = JSONSchema4TypeName;\nexport type JSONSchemaType = JSONSchema4Type;\n\nexport interface JSONSchema extends JSONSchema4 {\n /**\n * schema extension to support numeric enums\n */\n tsEnumNames?: string[];\n /**\n * schema extension to support custom types\n */\n tsType?: string;\n /**\n * property exists at least in https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.3\n */\n deprecated?: boolean;\n}\n\nexport const Parent = Symbol(\"Parent\");\n\nexport interface LinkedJSONSchema extends JSONSchema {\n /**\n * A reference to this schema's parent node, for convenience.\n * `null` when this is the root schema.\n */\n [Parent]: LinkedJSONSchema | null;\n\n additionalItems?: boolean | LinkedJSONSchema;\n additionalProperties?: boolean | LinkedJSONSchema;\n items?: LinkedJSONSchema | LinkedJSONSchema[];\n definitions?: {\n [k: string]: LinkedJSONSchema;\n };\n properties?: {\n [k: string]: LinkedJSONSchema;\n };\n patternProperties?: {\n [k: string]: LinkedJSONSchema;\n };\n dependencies?: {\n [k: string]: LinkedJSONSchema | string[];\n };\n allOf?: LinkedJSONSchema[];\n anyOf?: LinkedJSONSchema[];\n oneOf?: LinkedJSONSchema[];\n not?: LinkedJSONSchema;\n}\n\nexport const Types = Symbol(\"Types\");\nexport const Intersection = Symbol(\"Intersection\");\n\n/**\n * Normalized JSON schema.\n *\n * Note: `definitions` and `id` are removed by the normalizer. Use `$defs` and `$id` instead.\n */\nexport interface NormalizedJSONSchema extends Omit<LinkedJSONSchema, \"definitions\" | \"id\"> {\n [Intersection]?: NormalizedJSONSchema;\n [Parent]: NormalizedJSONSchema | null;\n [Types]: ReadonlySet<SchemaType>;\n\n additionalItems?: boolean | NormalizedJSONSchema;\n additionalProperties: boolean | NormalizedJSONSchema;\n extends?: string[];\n items?: NormalizedJSONSchema | NormalizedJSONSchema[];\n $defs?: {\n [k: string]: NormalizedJSONSchema;\n };\n properties?: {\n [k: string]: NormalizedJSONSchema;\n };\n patternProperties?: {\n [k: string]: NormalizedJSONSchema;\n };\n dependencies?: {\n [k: string]: NormalizedJSONSchema | string[];\n };\n allOf?: NormalizedJSONSchema[];\n anyOf?: NormalizedJSONSchema[];\n oneOf?: NormalizedJSONSchema[];\n not?: NormalizedJSONSchema;\n required: string[];\n}\n\nexport interface EnumJSONSchema extends NormalizedJSONSchema {\n enum: JSONSchema4Type[];\n}\n\nexport interface NamedEnumJSONSchema extends NormalizedJSONSchema {\n tsEnumNames: string[];\n}\n\nexport interface SchemaSchema extends NormalizedJSONSchema {\n properties: {\n [k: string]: NormalizedJSONSchema;\n };\n required: string[];\n}\n\nexport interface JSONSchemaWithDefinitions extends NormalizedJSONSchema {\n $defs: {\n [k: string]: NormalizedJSONSchema;\n };\n}\n\nexport interface CustomTypeJSONSchema extends NormalizedJSONSchema {\n tsType: string;\n}\n\nexport const getRootSchema = memoize((schema: NormalizedJSONSchema): NormalizedJSONSchema => {\n const parent = schema[Parent];\n if (!parent) {\n return schema;\n }\n return getRootSchema(parent);\n});\n\nexport function isBoolean(schema: LinkedJSONSchema | JSONSchemaType): schema is boolean {\n return schema === true || schema === false;\n}\n\nexport function isPrimitive(schema: LinkedJSONSchema | JSONSchemaType): schema is JSONSchemaType {\n return !isPlainObject(schema);\n}\n\nexport function isCompound(schema: JSONSchema): boolean {\n return Array.isArray(schema.type) || \"anyOf\" in schema || \"oneOf\" in schema;\n}\n","import { deburr, isPlainObject, upperFirst } from \"./compat\";\nimport {\n Intersection,\n type JSONSchema,\n type LinkedJSONSchema,\n type NormalizedJSONSchema,\n Parent,\n} from \"./types/JSONSchema\";\n\n// keys that shouldn't be traversed by the catchall step\nconst BLACKLISTED_KEYS = new Set([\n \"id\",\n \"$defs\",\n \"$id\",\n \"$schema\",\n \"title\",\n \"description\",\n \"default\",\n \"multipleOf\",\n \"maximum\",\n \"exclusiveMaximum\",\n \"minimum\",\n \"exclusiveMinimum\",\n \"maxLength\",\n \"minLength\",\n \"pattern\",\n \"additionalItems\",\n \"items\",\n \"maxItems\",\n \"minItems\",\n \"uniqueItems\",\n \"maxProperties\",\n \"minProperties\",\n \"required\",\n \"additionalProperties\",\n \"definitions\",\n \"properties\",\n \"patternProperties\",\n \"dependencies\",\n \"enum\",\n \"type\",\n \"allOf\",\n \"anyOf\",\n \"oneOf\",\n \"not\",\n]);\n\nfunction traverseObjectKeys(\n obj: Record<string, LinkedJSONSchema>,\n callback: (schema: LinkedJSONSchema, key: string | null) => void,\n processed: Set<LinkedJSONSchema>,\n) {\n Object.keys(obj).forEach((k) => {\n if (obj[k] && typeof obj[k] === \"object\" && !Array.isArray(obj[k])) {\n traverse(obj[k], callback, processed, k);\n }\n });\n}\n\nfunction traverseArray(\n arr: LinkedJSONSchema[],\n callback: (schema: LinkedJSONSchema, key: string | null) => void,\n processed: Set<LinkedJSONSchema>,\n) {\n arr.forEach((s, k) => traverse(s, callback, processed, k.toString()));\n}\n\nfunction traverseIntersection(\n schema: LinkedJSONSchema,\n callback: (schema: LinkedJSONSchema, key: string | null) => void,\n processed: Set<LinkedJSONSchema>,\n) {\n if (typeof schema !== \"object\" || !schema) {\n return;\n }\n\n const r = schema as unknown as Record<string | symbol, unknown>;\n const intersection = r[Intersection] as NormalizedJSONSchema | undefined;\n if (!intersection) {\n return;\n }\n\n if (Array.isArray(intersection.allOf)) {\n traverseArray(intersection.allOf, callback, processed);\n }\n}\n\nexport function traverse(\n schema: LinkedJSONSchema,\n callback: (schema: LinkedJSONSchema, key: string | null) => void,\n processed = new Set<LinkedJSONSchema>(),\n key?: string,\n): void {\n // Handle recursive schemas\n if (processed.has(schema)) {\n return;\n }\n\n processed.add(schema);\n callback(schema, key ?? null);\n\n if (schema.anyOf) {\n traverseArray(schema.anyOf, callback, processed);\n }\n if (schema.allOf) {\n traverseArray(schema.allOf, callback, processed);\n }\n if (schema.oneOf) {\n traverseArray(schema.oneOf, callback, processed);\n }\n if (schema.properties) {\n traverseObjectKeys(schema.properties, callback, processed);\n }\n if (schema.patternProperties) {\n traverseObjectKeys(schema.patternProperties, callback, processed);\n }\n if (schema.additionalProperties && typeof schema.additionalProperties === \"object\") {\n traverse(schema.additionalProperties, callback, processed);\n }\n if (schema.items) {\n const { items } = schema;\n if (Array.isArray(items)) {\n traverseArray(items, callback, processed);\n } else {\n traverse(items, callback, processed);\n }\n }\n if (schema.additionalItems && typeof schema.additionalItems === \"object\") {\n traverse(schema.additionalItems, callback, processed);\n }\n if (schema.dependencies) {\n if (Array.isArray(schema.dependencies)) {\n traverseArray(schema.dependencies, callback, processed);\n } else {\n traverseObjectKeys(schema.dependencies as LinkedJSONSchema, callback, processed);\n }\n }\n if (schema.definitions) {\n traverseObjectKeys(schema.definitions as Record<string, LinkedJSONSchema>, callback, processed);\n }\n if (schema.$defs) {\n traverseObjectKeys(schema.$defs as Record<string, LinkedJSONSchema>, callback, processed);\n }\n if (schema.not) {\n traverse(schema.not, callback, processed);\n }\n traverseIntersection(schema, callback, processed);\n\n // technically you can put definitions on any key\n Object.keys(schema)\n .filter((key) => !BLACKLISTED_KEYS.has(key))\n .forEach((key) => {\n const child = schema[key];\n if (child && typeof child === \"object\") {\n traverseObjectKeys(child, callback, processed);\n }\n });\n}\n\n/**\n * Eg. `foo/bar/baz.json` => `baz`\n */\nexport function justName(filename = \"\"): string {\n return stripExtension(filename.split(/[\\\\/]/).pop() ?? \"\");\n}\n\n/**\n * Avoid appending \"js\" to top-level unnamed schemas\n */\nexport function stripExtension(filename: string): string {\n return filename.replace(/\\.[^./\\\\]*$/, \"\");\n}\n\n/**\n * Convert a string that might contain spaces or special characters to one that\n * can safely be used as a TypeScript interface or enum name.\n */\nexport function toSafeString(string: string): string {\n // identifiers in javaScript/ts:\n // First character: a-zA-Z | _ | $\n // Rest: a-zA-Z | _ | $ | 0-9\n\n return upperFirst(\n // remove accents, umlauts, ... by their basic latin letters\n deburr(string)\n // replace chars which are not valid for typescript identifiers with whitespace\n .replace(/(^\\s*[^a-zA-Z_$])|([^a-zA-Z_$\\d])/g, \" \")\n // uppercase leading underscores followed by lowercase\n .replace(/^_[a-z]/g, (match) => match.toUpperCase())\n // remove non-leading underscores followed by lowercase (convert snake_case)\n .replace(/_[a-z]/g, (match) => match.substr(1, match.length).toUpperCase())\n // uppercase letters after digits, dollars\n .replace(/([\\d$]+[a-zA-Z])/g, (match) => match.toUpperCase())\n // uppercase first letter after whitespace\n .replace(/\\s+([a-zA-Z])/g, (match) => match.toUpperCase().trim())\n // remove remaining whitespace\n .replace(/\\s/g, \"\"),\n );\n}\n\nexport function generateName(from: string, usedNames: Set<string>) {\n let name = toSafeString(from);\n if (!name) {\n name = \"NoName\";\n }\n\n // increment counter until we find a free name\n if (usedNames.has(name)) {\n let counter = 1;\n let nameWithCounter = `${name}${counter}`;\n while (usedNames.has(nameWithCounter)) {\n nameWithCounter = `${name}${counter}`;\n counter++;\n }\n name = nameWithCounter;\n }\n\n usedNames.add(name);\n return name;\n}\n\n/**\n * escape block comments in schema descriptions so that they don't unexpectedly close JSDoc comments in generated typescript interfaces\n */\nexport function escapeBlockComment(schema: JSONSchema) {\n const replacer = \"* /\";\n if (schema === null || typeof schema !== \"object\") {\n return;\n }\n for (const key of Object.keys(schema)) {\n if (key === \"description\" && typeof schema[key] === \"string\") {\n schema[key] = schema[key]!.replace(/\\*\\//g, replacer);\n }\n }\n}\n\n/**\n * Removes the schema's `default` property if it doesn't match the schema's `type` property.\n * Useful when parsing unions.\n *\n * Mutates `schema`.\n */\nexport function maybeStripDefault(schema: LinkedJSONSchema): LinkedJSONSchema {\n if (!(\"default\" in schema)) {\n return schema;\n }\n\n switch (schema.type) {\n case \"array\":\n if (Array.isArray(schema.default)) {\n return schema;\n }\n break;\n case \"boolean\":\n if (typeof schema.default === \"boolean\") {\n return schema;\n }\n break;\n case \"integer\":\n case \"number\":\n if (typeof schema.default === \"number\") {\n return schema;\n }\n break;\n case \"string\":\n if (typeof schema.default === \"string\") {\n return schema;\n }\n break;\n case \"null\":\n if (schema.default === null) {\n return schema;\n }\n break;\n case \"object\":\n if (isPlainObject(schema.default)) {\n return schema;\n }\n break;\n }\n delete schema.default;\n return schema;\n}\n\nexport function appendToDescription(\n existingDescription: string | undefined,\n ...values: string[]\n): string {\n if (existingDescription) {\n return `${existingDescription}\\n\\n${values.join(\"\\n\")}`;\n }\n return values.join(\"\\n\");\n}\n\nexport function isSchemaLike(schema: any): schema is LinkedJSONSchema {\n if (!isPlainObject(schema)) {\n return false;\n }\n\n // top-level schema\n const parent = (schema as LinkedJSONSchema)[Parent] as LinkedJSONSchema | null;\n if (parent === null) {\n return true;\n }\n\n const JSON_SCHEMA_KEYWORDS = [\n \"$defs\",\n \"allOf\",\n \"anyOf\",\n \"definitions\",\n \"dependencies\",\n \"enum\",\n \"not\",\n \"oneOf\",\n \"patternProperties\",\n \"properties\",\n \"required\",\n ];\n if (JSON_SCHEMA_KEYWORDS.some((_) => parent[_] === schema)) {\n return false;\n }\n\n return true;\n}\n","import { memoize, omit } from \"./compat\";\nimport { DEFAULT_OPTIONS, type Options } from \"./index\";\nimport { hasComment, hasStandaloneName, T_ANY, T_UNKNOWN } from \"./types/AST\";\nimport type {\n AST,\n ASTWithStandaloneName,\n TArray,\n TEnum,\n TInterface,\n TIntersection,\n TNamedInterface,\n TUnion,\n} from \"./types/AST\";\nimport { toSafeString } from \"./utils\";\n\nexport function generate(ast: AST, options = DEFAULT_OPTIONS): string {\n return (\n [\n options.bannerComment,\n declareNamedTypes(ast, options, ast.standaloneName!),\n declareNamedInterfaces(ast, options, ast.standaloneName!),\n declareEnums(ast, options),\n ]\n .filter(Boolean)\n .join(\"\\n\\n\") + \"\\n\"\n ); // trailing newline\n}\n\nfunction declareEnums(ast: AST, options: Options, processed = new Set<AST>()): string {\n if (processed.has(ast)) {\n return \"\";\n }\n\n processed.add(ast);\n let type = \"\";\n\n switch (ast.type) {\n case \"ENUM\":\n return generateStandaloneEnum(ast, options) + \"\\n\";\n case \"ARRAY\":\n return declareEnums(ast.params, options, processed);\n case \"UNION\":\n case \"INTERSECTION\":\n return ast.params.reduce((prev, ast) => prev + declareEnums(ast, options, processed), \"\");\n case \"TUPLE\":\n type = ast.params.reduce((prev, ast) => prev + declareEnums(ast, options, processed), \"\");\n if (ast.spreadParam) {\n type += declareEnums(ast.spreadParam, options, processed);\n }\n return type;\n case \"INTERFACE\":\n return getSuperTypesAndParams(ast).reduce(\n (prev, ast) => prev + declareEnums(ast, options, processed),\n \"\",\n );\n default:\n return \"\";\n }\n}\n\nfunction declareNamedInterfaces(\n ast: AST,\n options: Options,\n rootASTName: string,\n processed = new Set<AST>(),\n): string {\n if (processed.has(ast)) {\n return \"\";\n }\n\n processed.add(ast);\n let type = \"\";\n\n switch (ast.type) {\n case \"ARRAY\":\n type = declareNamedInterfaces((ast as TArray).params, options, rootASTName, processed);\n break;\n case \"INTERFACE\":\n type = [\n hasStandaloneName(ast) &&\n (ast.standaloneName === rootASTName || options.declareExternallyReferenced) &&\n generateStandaloneInterface(ast, options),\n getSuperTypesAndParams(ast)\n .map((ast) => declareNamedInterfaces(ast, options, rootASTName, processed))\n .filter(Boolean)\n .join(\"\\n\"),\n ]\n .filter(Boolean)\n .join(\"\\n\");\n break;\n case \"INTERSECTION\":\n case \"TUPLE\":\n case \"UNION\":\n type = ast.params\n .map((_) => declareNamedInterfaces(_, options, rootASTName, processed))\n .filter(Boolean)\n .join(\"\\n\");\n if (ast.type === \"TUPLE\" && ast.spreadParam) {\n type += declareNamedInterfaces(ast.spreadParam, options, rootASTName, processed);\n }\n break;\n default:\n type = \"\";\n }\n\n return type;\n}\n\nfunction declareNamedTypes(\n ast: AST,\n options: Options,\n rootASTName: string,\n processed = new Set<AST>(),\n): string {\n if (processed.has(ast)) {\n return \"\";\n }\n\n processed.add(ast);\n\n switch (ast.type) {\n case \"ARRAY\":\n return [\n declareNamedTypes(ast.params, options, rootASTName, processed),\n hasStandaloneName(ast) ? generateStandaloneType(ast, options) : undefined,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n case \"ENUM\":\n return \"\";\n case \"INTERFACE\":\n return getSuperTypesAndParams(ast)\n .map(\n (ast) =>\n (ast.standaloneName === rootASTName || options.declareExternallyReferenced) &&\n declareNamedTypes(ast, options, rootASTName, processed),\n )\n .filter(Boolean)\n .join(\"\\n\");\n case \"INTERSECTION\":\n case \"TUPLE\":\n case \"UNION\":\n return [\n hasStandaloneName(ast) ? generateStandaloneType(ast, options) : undefined,\n ast.params\n .map((ast) => declareNamedTypes(ast, options, rootASTName, processed))\n .filter(Boolean)\n .join(\"\\n\"),\n \"spreadParam\" in ast && ast.spreadParam\n ? declareNamedTypes(ast.spreadParam, options, rootASTName, processed)\n : undefined,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n default:\n if (hasStandaloneName(ast)) {\n return generateStandaloneType(ast, options);\n }\n return \"\";\n }\n}\n\nfunction generateTypeUnmemoized(ast: AST, options: Options): string {\n const type = generateRawType(ast, options);\n\n if (options.strictIndexSignatures && ast.keyName === \"[k: string]\") {\n return `${type} | undefined`;\n }\n\n return type;\n}\nexport const generateType = memoize(generateTypeUnmemoized);\n\nfunction generateRawType(ast: AST, options: Options): string {\n if (hasStandaloneName(ast)) {\n return toSafeString(ast.standaloneName);\n }\n\n switch (ast.type) {\n case \"ANY\":\n return \"any\";\n case \"ARRAY\":\n return (() => {\n const type = generateType(ast.params, options);\n return type.endsWith('\"') ? \"(\" + type + \")[]\" : type + \"[]\";\n })();\n case \"BOOLEAN\":\n return \"boolean\";\n case \"INTERFACE\":\n return generateInterface(ast, options);\n case \"INTERSECTION\":\n return generateSetOperation(ast, options);\n case \"LITERAL\":\n return JSON.stringify(ast.params);\n case \"NEVER\":\n return \"never\";\n case \"NUMBER\":\n return \"number\";\n case \"NULL\":\n return \"null\";\n case \"OBJECT\":\n return \"object\";\n case \"REFERENCE\":\n return ast.params;\n case \"STRING\":\n return \"string\";\n case \"TUPLE\":\n return (() => {\n const minItems = ast.minItems;\n const maxItems = ast.maxItems || -1;\n\n let spreadParam = ast.spreadParam;\n const astParams = [...ast.params];\n if (minItems > 0 && minItems > astParams.length && ast.spreadParam === undefined) {\n // this is a valid state, and JSONSchema doesn't care about the item type\n if (maxItems < 0) {\n // no max items and no spread param, so just spread any\n spreadParam = options.unknownAny ? T_UNKNOWN : T_ANY;\n }\n }\n if (maxItems > astParams.length && ast.spreadParam === undefined) {\n // this is a valid state, and JSONSchema doesn't care about the item type\n // fill the tuple with any elements\n for (let i = astParams.length; i < maxItems; i += 1) {\n astParams.push(options.unknownAny ? T_UNKNOWN : T_ANY);\n }\n }\n\n function addSpreadParam(params: string[]): string[] {\n if (spreadParam) {\n const spread = \"...(\" + generateType(spreadParam, options) + \")[]\";\n params.push(spread);\n }\n return params;\n }\n\n function paramsToString(params: string[]): string {\n return \"[\" + params.join(\", \") + \"]\";\n }\n\n const paramsList = astParams.map((param) => generateType(param, options));\n\n if (paramsList.length > minItems) {\n /*\n if there are more items than the min, we return a union of tuples instead of\n using the optional element operator. This is done because it is more typesafe.\n\n // optional element operator\n type A = [string, string?, string?]\n const a: A = ['a', undefined, 'c'] // no error\n\n // union of tuples\n type B = [string] | [string, string] | [string, string, string]\n const b: B = ['a', undefined, 'c'] // TS error\n */\n\n const cumulativeParamsList: string[] = paramsList.slice(0, minItems);\n const typesToUnion: string[] = [];\n\n if (cumulativeParamsList.length > 0) {\n // actually has minItems, so add the initial state\n typesToUnion.push(paramsToString(cumulativeParamsList));\n } else {\n // no minItems means it's acceptable to have an empty tuple type\n typesToUnion.push(paramsToString([]));\n }\n\n for (let i = minItems; i < paramsList.length; i += 1) {\n cumulativeParamsList.push(paramsList[i]);\n\n if (i === paramsList.length - 1) {\n // only the last item in the union should have the spread parameter\n addSpreadParam(cumulativeParamsList);\n }\n\n typesToUnion.push(paramsToString(cumulativeParamsList));\n }\n\n return typesToUnion.join(\"|\");\n }\n\n // no max items so only need to return one type\n return paramsToString(addSpreadParam(paramsList));\n })();\n case \"UNION\":\n return generateSetOperation(ast, options);\n case \"UNKNOWN\":\n return \"unknown\";\n case \"CUSTOM_TYPE\":\n return ast.params;\n }\n}\n\n/**\n * Generate a Union or Intersection\n */\nfunction generateSetOperation(ast: TIntersection | TUnion, options: Options): string {\n const members = (ast as TUnion).params.map((_) => generateType(_, options));\n const separator = ast.type === \"UNION\" ? \"|\" : \"&\";\n return members.length === 1 ? members[0] : \"(\" + members.join(\" \" + separator + \" \") + \")\";\n}\n\nfunction generateInterface(ast: TInterface, options: Options): string {\n return (\n `{` +\n \"\\n\" +\n ast.params\n .filter((_) => !_.isPatternProperty && !_.isUnreachableDefinition)\n .map(\n ({ isRequired, keyName, ast }) =>\n [isRequired, keyName, ast, generateType(ast, options)] as [boolean, string, AST, string],\n )\n .map(\n ([isRequired, keyName, ast, type]) =>\n (hasComment(ast) && !ast.standaloneName\n ? generateComment(ast.comment, ast.deprecated) + \"\\n\"\n : \"\") +\n escapeKeyName(keyName) +\n (isRequired ? \"\" : \"?\") +\n \": \" +\n type,\n )\n .join(\"\\n\") +\n \"\\n\" +\n \"}\"\n );\n}\n\nfunction generateComment(comment?: string, deprecated?: boolean): string {\n const commentLines = [\"/**\"];\n if (deprecated) {\n commentLines.push(\" * @deprecated\");\n }\n if (typeof comment !== \"undefined\") {\n commentLines.push(...comment.split(\"\\n\").map((_) => \" * \" + _));\n }\n commentLines.push(\" */\");\n return commentLines.join(\"\\n\");\n}\n\nfunction generateStandaloneEnum(ast: TEnum, options: Options): string {\n const containsSpecialCharacters = (key: string): boolean => /[^a-zA-Z0-9_]/.test(key);\n\n return (\n (hasComment(ast) ? generateComment(ast.comment, ast.deprecated) + \"\\n\" : \"\") +\n \"export \" +\n (options.enableConstEnums ? \"const \" : \"\") +\n `enum ${toSafeString(ast.standaloneName)} {` +\n \"\\n\" +\n ast.params\n .map(\n ({ ast, keyName }) =>\n (containsSpecialCharacters(keyName) ? `\"${keyName}\"` : keyName) +\n \" = \" +\n generateType(ast, options),\n )\n .join(\",\\n\") +\n \"\\n\" +\n \"}\"\n );\n}\n\nfunction generateStandaloneInterface(ast: TNamedInterface, options: Options): string {\n return (\n (hasComment(ast) ? generateComment(ast.comment, ast.deprecated) + \"\\n\" : \"\") +\n `export interface ${toSafeString(ast.standaloneName)} ` +\n (ast.superTypes.length > 0\n ? `extends ${ast.superTypes.map((superType) => toSafeString(superType.standaloneName)).join(\", \")} `\n : \"\") +\n generateInterface(ast, options)\n );\n}\n\nfunction generateStandaloneType(ast: ASTWithStandaloneName, options: Options): string {\n return (\n (hasComment(ast) ? generateComment(ast.comment) + \"\\n\" : \"\") +\n `export type ${toSafeString(ast.standaloneName)} = ${generateType(\n omit(ast, \"standaloneName\") as AST /* TODO */,\n options,\n )}`\n );\n}\n\nfunction escapeKeyName(keyName: string): string {\n if (keyName.length && /[A-Za-z_$]/.test(keyName.charAt(0)) && /^[\\w$]+$/.test(keyName)) {\n return keyName;\n }\n if (keyName === \"[k: string]\") {\n return keyName;\n }\n return JSON.stringify(keyName);\n}\n\nfunction getSuperTypesAndParams(ast: TInterface): AST[] {\n return ast.params.map((param) => param.ast).concat(ast.superTypes);\n}\n","import { isPlainObject } from \"./compat\";\nimport { isCompound } from \"./types/JSONSchema\";\nimport type { JSONSchema, SchemaType } from \"./types/JSONSchema\";\n\n/**\n * Duck types a JSONSchema schema or property to determine which kind of AST node to parse it into.\n *\n * Due to what some might say is an oversight in the JSON-Schema spec, a given schema may\n * implicitly be an *intersection* of multiple JSON-Schema directives (ie. multiple TypeScript\n * types). The spec leaves it up to implementations to decide what to do with this\n * loosely-defined behavior.\n */\nexport function typesOfSchema(schema: JSONSchema): Set<SchemaType> {\n // tsType is an escape hatch that supercedes all other directives\n if (schema.tsType) {\n return new Set([\"CUSTOM_TYPE\"]);\n }\n\n // Collect matched types\n const matchedTypes = new Set<SchemaType>();\n for (const [schemaType, f] of Object.entries(matchers)) {\n if (f(schema)) {\n matchedTypes.add(schemaType as SchemaType);\n }\n }\n\n // Default to an unnamed schema\n if (!matchedTypes.size) {\n matchedTypes.add(\"UNNAMED_SCHEMA\");\n }\n\n return matchedTypes;\n}\n\nconst matchers: Record<SchemaType, (schema: JSONSchema) => boolean> = {\n ALL_OF(schema) {\n return \"allOf\" in schema;\n },\n ANY(schema) {\n if (Object.keys(schema).length === 0) {\n // The empty schema {} validates any value\n // @see https://json-schema.org/draft-07/json-schema-core.html#rfc.section.4.3.1\n return true;\n }\n return schema.type === \"any\";\n },\n ANY_OF(schema) {\n return \"anyOf\" in schema;\n },\n BOOLEAN(schema) {\n if (\"enum\" in schema) {\n return false;\n }\n if (schema.type === \"boolean\") {\n return true;\n }\n if (!isCompound(schema) && typeof schema.default === \"boolean\") {\n return true;\n }\n return false;\n },\n CUSTOM_TYPE() {\n return false; // Explicitly handled before we try to match\n },\n NAMED_ENUM(schema) {\n return \"enum\" in schema && \"tsEnumNames\" in schema;\n },\n NAMED_SCHEMA(schema) {\n // 8.2.1. The presence of \"$id\" in a subschema indicates that the subschema constitutes a distinct schema resource within a single schema document.\n return \"$id\" in schema && (\"patternProperties\" in schema || \"properties\" in schema);\n },\n NEVER(schema: JSONSchema | boolean) {\n return schema === false;\n },\n NULL(schema) {\n return schema.type === \"null\";\n },\n NUMBER(schema) {\n if (\"enum\" in schema) {\n return false;\n }\n if (schema.type === \"integer\" || schema.type === \"number\") {\n return true;\n }\n if (!isCompound(schema) && typeof schema.default === \"number\") {\n return true;\n }\n return false;\n },\n OBJECT(schema) {\n return (\n schema.type === \"object\" &&\n !isPlainObject(schema.additionalProperties) &&\n !schema.allOf &&\n !schema.anyOf &&\n !schema.oneOf &&\n !schema.patternProperties &&\n !schema.properties &&\n !schema.required\n );\n },\n ONE_OF(schema) {\n return \"oneOf\" in schema;\n },\n REFERENCE(schema) {\n return \"$ref\" in schema;\n },\n STRING(schema) {\n if (\"enum\" in schema) {\n return false;\n }\n if (schema.type === \"string\") {\n return true;\n }\n if (!isCompound(schema) && typeof schema.default === \"string\") {\n return true;\n }\n return false;\n },\n TYPED_ARRAY(schema) {\n if (schema.type && schema.type !== \"array\") {\n return false;\n }\n return \"items\" in schema;\n },\n UNION(schema) {\n return Array.isArray(schema.type);\n },\n UNNAMED_ENUM(schema) {\n if (\"tsEnumNames\" in schema) {\n return false;\n }\n if (\n schema.type &&\n schema.type !== \"boolean\" &&\n schema.type !== \"integer\" &&\n schema.type !== \"number\" &&\n schema.type !== \"string\"\n ) {\n return false;\n }\n return \"enum\" in schema;\n },\n UNNAMED_SCHEMA() {\n return false; // Explicitly handled as the default case\n },\n UNTYPED_ARRAY(schema) {\n return schema.type === \"array\" && !(\"items\" in schema);\n },\n};\n","import type { LinkedJSONSchema } from \"./types/JSONSchema\";\nimport { Intersection, Parent, Types } from \"./types/JSONSchema\";\nimport { typesOfSchema } from \"./typesOfSchema\";\n\nexport function applySchemaTyping(schema: LinkedJSONSchema) {\n const types = typesOfSchema(schema);\n\n Object.defineProperty(schema, Types, {\n enumerable: false,\n value: types,\n writable: false,\n });\n\n if (types.size === 1) {\n return;\n }\n\n // Some schemas can be understood as multiple possible types (see related\n // comment in `typesOfSchema.ts`). In such cases, we generate an `ALL_OF`\n // intersection that will ultimately be used to generate a union type.\n //\n // The original schema's name, title, and description are hoisted to the\n // new intersection schema to prevent duplication.\n //\n // If the original schema also contained its own `ALL_OF` property, it is\n // also hoiested to the new intersection schema.\n const intersection = {\n [Parent]: schema,\n [Types]: new Set([\"ALL_OF\"]),\n $id: schema.$id,\n description: schema.description,\n name: schema.name,\n title: schema.title,\n allOf: schema.allOf ?? [],\n required: [],\n additionalProperties: false,\n };\n\n types.delete(\"ALL_OF\");\n delete schema.allOf;\n delete schema.$id;\n delete schema.description;\n delete schema.name;\n delete schema.title;\n\n Object.defineProperty(schema, Intersection, {\n enumerable: false,\n value: intersection,\n writable: false,\n });\n}\n","import { Parent } from \"./types/JSONSchema\";\nimport type {\n JSONSchemaTypeName,\n LinkedJSONSchema,\n NormalizedJSONSchema,\n} from \"./types/JSONSchema\";\nimport {\n appendToDescription,\n escapeBlockComment,\n isSchemaLike,\n justName,\n toSafeString,\n traverse,\n} from \"./utils\";\nimport type { Options } from \"./\";\nimport { applySchemaTyping } from \"./applySchemaTyping\";\nimport type { DereferencedPaths } from \"./resolver\";\n\nconst isJsonEqual = (left: unknown, right: unknown): boolean => {\n if (left === right) return true;\n if (typeof left !== typeof right) return false;\n if (left === null || right === null) return false;\n if (typeof left !== \"object\" || typeof right !== \"object\") return false;\n\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => isJsonEqual(value, right[index]));\n }\n\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const leftKeys = Object.keys(leftRecord);\n const rightKeys = Object.keys(rightRecord);\n if (leftKeys.length !== rightKeys.length) return false;\n\n return leftKeys.every(\n (key) => Object.hasOwn(rightRecord, key) && isJsonEqual(leftRecord[key], rightRecord[key]),\n );\n};\n\ntype Rule = (\n schema: LinkedJSONSchema,\n fileName: string,\n options: Options,\n key: string | null,\n dereferencedPaths: DereferencedPaths,\n) => void;\nconst rules = new Map<string, Rule>();\n\nfunction hasType(schema: LinkedJSONSchema, type: JSONSchemaTypeName) {\n return schema.type === type || (Array.isArray(schema.type) && schema.type.includes(type));\n}\nfunction isObjectType(schema: LinkedJSONSchema) {\n return schema.properties !== undefined || hasType(schema, \"object\") || hasType(schema, \"any\");\n}\nfunction isArrayType(schema: LinkedJSONSchema) {\n return schema.items !== undefined || hasType(schema, \"array\") || hasType(schema, \"any\");\n}\nfunction isEnumTypeWithoutTsEnumNames(schema: LinkedJSONSchema) {\n return schema.type === \"string\" && schema.enum !== undefined && schema.tsEnumNames === undefined;\n}\n\nrules.set('Remove `type=[\"null\"]` if `enum=[null]`', (schema) => {\n if (\n Array.isArray(schema.enum) &&\n schema.enum.some((e) => e === null) &&\n Array.isArray(schema.type) &&\n schema.type.includes(\"null\")\n ) {\n schema.type = schema.type.filter((type) => type !== \"null\");\n }\n});\n\nrules.set(\"Destructure unary types\", (schema) => {\n if (schema.type && Array.isArray(schema.type) && schema.type.length === 1) {\n schema.type = schema.type[0];\n }\n});\n\nrules.set(\"Add empty `required` property if none is defined\", (schema) => {\n if (isObjectType(schema) && !(\"required\" in schema)) {\n schema.required = [];\n }\n});\n\nrules.set(\"Transform `required`=false to `required`=[]\", (schema) => {\n if (schema.required === false) {\n schema.required = [];\n }\n});\n\nrules.set(\"Default additionalProperties\", (schema, _, options) => {\n if (\n isObjectType(schema) &&\n !(\"additionalProperties\" in schema) &&\n schema.patternProperties === undefined\n ) {\n schema.additionalProperties = options.additionalProperties;\n }\n});\n\nrules.set(\"Transform id to $id\", (schema, fileName) => {\n if (!isSchemaLike(schema)) {\n return;\n }\n if (schema.id && schema.$id && schema.id !== schema.$id) {\n throw ReferenceError(\n `Schema must define either id or $id, not both. Given id=${schema.id}, $id=${schema.$id} in ${fileName}`,\n );\n }\n if (schema.id) {\n schema.$id = schema.id;\n delete schema.id;\n }\n});\n\nrules.set(\n \"Add an $id to anything that needs it\",\n (schema, fileName, _options, _key, dereferencedPaths) => {\n if (!isSchemaLike(schema)) {\n return;\n }\n\n // Top-level schema\n if (!schema.$id && !schema[Parent]) {\n schema.$id = toSafeString(justName(fileName));\n return;\n }\n\n // Sub-schemas with references\n if (!isArrayType(schema) && !isObjectType(schema)) {\n return;\n }\n\n // We'll infer from $id and title downstream\n // TODO: Normalize upstream\n const dereferencedName = dereferencedPaths.get(schema);\n if (!schema.$id && !schema.title && dereferencedName) {\n schema.$id = toSafeString(justName(dereferencedName));\n }\n\n if (dereferencedName) {\n dereferencedPaths.delete(schema);\n }\n },\n);\n\nrules.set(\"Escape closing JSDoc comment\", (schema) => {\n escapeBlockComment(schema);\n});\n\nrules.set(\"Add JSDoc comments for minItems and maxItems\", (schema) => {\n if (!isArrayType(schema)) {\n return;\n }\n const commentsToAppend = [\n \"minItems\" in schema ? `@minItems ${schema.minItems}` : \"\",\n \"maxItems\" in schema ? `@maxItems ${schema.maxItems}` : \"\",\n ].filter(Boolean);\n if (commentsToAppend.length) {\n schema.description = appendToDescription(schema.description, ...commentsToAppend);\n }\n});\n\nrules.set(\"Optionally remove maxItems and minItems\", (schema, _fileName, options) => {\n if (!isArrayType(schema)) {\n return;\n }\n if (\"minItems\" in schema && options.ignoreMinAndMaxItems) {\n delete schema.minItems;\n }\n if (\"maxItems\" in schema && (options.ignoreMinAndMaxItems || options.maxItems === -1)) {\n delete schema.maxItems;\n }\n});\n\nrules.set(\"Normalize schema.minItems\", (schema, _fileName, options) => {\n if (options.ignoreMinAndMaxItems) {\n return;\n }\n // make sure we only add the props onto array types\n if (!isArrayType(schema)) {\n return;\n }\n const { minItems } = schema;\n schema.minItems = typeof minItems === \"number\" ? minItems : 0;\n // cannot normalize maxItems because maxItems = 0 has an actual meaning\n});\n\nrules.set(\n \"Remove maxItems if it is big enough to likely cause OOMs\",\n (schema, _fileName, options) => {\n if (options.ignoreMinAndMaxItems || options.maxItems === -1) {\n return;\n }\n if (!isArrayType(schema)) {\n return;\n }\n const { maxItems, minItems } = schema;\n // minItems is guaranteed to be a number after the previous rule runs\n if (maxItems !== undefined && maxItems - (minItems as number) > options.maxItems) {\n delete schema.maxItems;\n }\n },\n);\n\nrules.set(\"Normalize schema.items\", (schema, _fileName, options) => {\n if (options.ignoreMinAndMaxItems) {\n return;\n }\n const { maxItems, minItems } = schema;\n const hasMaxItems = typeof maxItems === \"number\" && maxItems >= 0;\n const hasMinItems = typeof minItems === \"number\" && minItems > 0;\n\n if (schema.items && !Array.isArray(schema.items) && (hasMaxItems || hasMinItems)) {\n const items = schema.items;\n // create a tuple of length N\n const newItems = Array(maxItems || minItems || 0).fill(items);\n if (!hasMaxItems) {\n // if there is no maximum, then add a spread item to collect the rest\n schema.additionalItems = items;\n }\n schema.items = newItems;\n }\n\n if (Array.isArray(schema.items) && hasMaxItems && maxItems! < schema.items.length) {\n // it's perfectly valid to provide 5 item defs but require maxItems 1\n // obviously we shouldn't emit a type for items that aren't expected\n schema.items = schema.items.slice(0, maxItems);\n }\n\n return schema;\n});\n\nrules.set(\"Remove extends, if it is empty\", (schema) => {\n if (!schema.hasOwnProperty(\"extends\")) {\n return;\n }\n if (schema.extends == null || (Array.isArray(schema.extends) && schema.extends.length === 0)) {\n delete schema.extends;\n }\n});\n\nrules.set(\"Make extends always an array, if it is defined\", (schema) => {\n if (schema.extends == null) {\n return;\n }\n if (!Array.isArray(schema.extends)) {\n schema.extends = [schema.extends];\n }\n});\n\nrules.set(\"Transform definitions to $defs\", (schema, fileName) => {\n if (schema.definitions && schema.$defs && !isJsonEqual(schema.definitions, schema.$defs)) {\n throw ReferenceError(\n `Schema must define either definitions or $defs, not both. Given id=${schema.id} in ${fileName}`,\n );\n }\n if (schema.definitions) {\n schema.$defs = schema.definitions;\n delete schema.definitions;\n }\n});\n\nrules.set(\"Transform const to singleton enum\", (schema) => {\n if (schema.const !== undefined) {\n schema.enum = [schema.const];\n delete schema.const;\n }\n});\n\nrules.set(\"Add tsEnumNames to enum types\", (schema, _, options) => {\n if (isEnumTypeWithoutTsEnumNames(schema) && options.inferStringEnumKeysFromValues) {\n schema.tsEnumNames = schema.enum?.map(String);\n }\n});\n\n// Precalculation of the schema types is necessary because the ALL_OF type\n// is implemented in a way that mutates the schema object. Detection of the\n// NAMED_SCHEMA type relies on the presence of the $id property, which is\n// hoisted to a parent schema object during the ALL_OF type implementation,\n// and becomes unavailable if the same schema is used in multiple places.\n//\n// Precalculation of the `ALL_OF` intersection schema is necessary because\n// the intersection schema needs to participate in the schema cache during\n// the parsing step, so it cannot be re-calculated every time the schema\n// is encountered.\nrules.set(\"Pre-calculate schema types and intersections\", (schema) => {\n if (schema !== null && typeof schema === \"object\") {\n applySchemaTyping(schema);\n }\n});\n\nexport function normalize(\n rootSchema: LinkedJSONSchema,\n dereferencedPaths: DereferencedPaths,\n filename: string,\n options: Options,\n): NormalizedJSONSchema {\n rules.forEach((rule) =>\n traverse(rootSchema, (schema, key) => rule(schema, filename, options, key, dereferencedPaths)),\n );\n return rootSchema as NormalizedJSONSchema;\n}\n","import { uniqBy } from \"./compat\";\nimport type { Options } from \".\";\nimport { generateType } from \"./generator\";\nimport { T_ANY, T_UNKNOWN } from \"./types/AST\";\nimport type { AST } from \"./types/AST\";\n\nexport function optimize(ast: AST, options: Options, processed = new Set<AST>()): AST {\n if (processed.has(ast)) {\n return ast;\n }\n\n processed.add(ast);\n\n switch (ast.type) {\n case \"ARRAY\":\n return Object.assign(ast, {\n params: optimize(ast.params, options, processed),\n });\n case \"INTERFACE\":\n return Object.assign(ast, {\n params: ast.params.map((_) =>\n Object.assign(_, { ast: optimize(_.ast, options, processed) }),\n ),\n });\n case \"INTERSECTION\":\n case \"UNION\":\n // Start with the leaves...\n const optimizedAST = Object.assign(ast, {\n params: ast.params.map((_) => optimize(_, options, processed)),\n });\n\n // [A, B, C, Any] -> Any\n if (optimizedAST.params.some((_) => _.type === \"ANY\")) {\n return T_ANY;\n }\n\n // [A, B, C, Unknown] -> Unknown\n if (optimizedAST.params.some((_) => _.type === \"UNKNOWN\")) {\n return T_UNKNOWN;\n }\n\n // [A (named), A] -> [A (named)]\n if (\n optimizedAST.params.every((_) => {\n const a = generateType(omitStandaloneName(_), options);\n const b = generateType(omitStandaloneName(optimizedAST.params[0]), options);\n return a === b;\n }) &&\n optimizedAST.params.some((_) => _.standaloneName !== undefined)\n ) {\n optimizedAST.params = optimizedAST.params.filter((_) => _.standaloneName !== undefined);\n }\n\n // [A, B, B] -> [A, B]\n const params = uniqBy(optimizedAST.params, (_) => generateType(_, options));\n if (params.length !== optimizedAST.params.length) {\n optimizedAST.params = params;\n }\n\n return Object.assign(optimizedAST, {\n params: optimizedAST.params.map((_) => optimize(_, options, processed)),\n });\n default:\n return ast;\n }\n}\n\n// TODO: More clearly disambiguate standalone names vs. aliased names instead.\nfunction omitStandaloneName<A extends AST>(ast: A): A {\n switch (ast.type) {\n case \"ENUM\":\n return ast;\n default:\n return { ...ast, standaloneName: undefined };\n }\n}\n","import type { JSONSchema4Type, JSONSchema4TypeName } from \"./types/json-schema\";\nimport { findKey, isPlainObject, memoize, omit } from \"./compat\";\nimport type { Options } from \"./\";\nimport { applySchemaTyping } from \"./applySchemaTyping\";\nimport type {\n AST,\n TInterface,\n TInterfaceParam,\n TIntersection,\n TNamedInterface,\n TTuple,\n} from \"./types/AST\";\nimport {\n T_ANY,\n T_ANY_ADDITIONAL_PROPERTIES,\n T_UNKNOWN,\n T_UNKNOWN_ADDITIONAL_PROPERTIES,\n} from \"./types/AST\";\nimport type {\n EnumJSONSchema,\n JSONSchemaWithDefinitions,\n LinkedJSONSchema,\n NormalizedJSONSchema,\n SchemaSchema,\n SchemaType,\n} from \"./types/JSONSchema\";\nimport { Intersection, Types, getRootSchema, isBoolean, isPrimitive } from \"./types/JSONSchema\";\nimport { generateName, maybeStripDefault } from \"./utils\";\n\nexport type Processed = Map<NormalizedJSONSchema, Map<SchemaType, AST>>;\n\nexport type UsedNames = Set<string>;\n\nexport function parse(\n schema: NormalizedJSONSchema | JSONSchema4Type,\n options: Options,\n keyName?: string,\n processed: Processed = new Map(),\n usedNames = new Set<string>(),\n): AST {\n if (isPrimitive(schema)) {\n if (isBoolean(schema)) {\n return parseBooleanSchema(schema, keyName, options);\n }\n\n return parseLiteral(schema, keyName);\n }\n\n const normalizedSchema = schema as NormalizedJSONSchema;\n const intersection = normalizedSchema[Intersection];\n const types = normalizedSchema[Types];\n\n if (intersection) {\n const ast = parseAsTypeWithCache(\n intersection,\n \"ALL_OF\",\n options,\n keyName,\n processed,\n usedNames,\n ) as TIntersection;\n\n types.forEach((type) => {\n ast.params.push(\n parseAsTypeWithCache(normalizedSchema, type, options, keyName, processed, usedNames),\n );\n });\n\n return ast;\n }\n\n if (types.size === 1) {\n const type = [...types][0];\n const ast = parseAsTypeWithCache(\n normalizedSchema,\n type,\n options,\n keyName,\n processed,\n usedNames,\n );\n return ast;\n }\n\n throw new ReferenceError(\"Expected intersection schema. Please file an issue on GitHub.\");\n}\n\nfunction parseAsTypeWithCache(\n schema: NormalizedJSONSchema,\n type: SchemaType,\n options: Options,\n keyName?: string,\n processed: Processed = new Map(),\n usedNames = new Set<string>(),\n): AST {\n // If we've seen this node before, return it.\n let cachedTypeMap = processed.get(schema);\n if (!cachedTypeMap) {\n cachedTypeMap = new Map();\n processed.set(schema, cachedTypeMap);\n }\n const cachedAST = cachedTypeMap.get(type);\n if (cachedAST) {\n return cachedAST;\n }\n\n // Cache processed ASTs before they are actually computed, then update\n // them in place using set(). This is to avoid cycles.\n // TODO: Investigate alternative approaches (lazy-computing nodes, etc.)\n const ast = {} as AST;\n cachedTypeMap.set(type, ast);\n\n // Update the AST in place. This updates the `processed` cache, as well\n // as any nodes that directly reference the node.\n return Object.assign(ast, parseNonLiteral(schema, type, options, keyName, processed, usedNames));\n}\n\nfunction parseBooleanSchema(schema: boolean, keyName: string | undefined, options: Options): AST {\n if (schema) {\n return {\n keyName,\n type: options.unknownAny ? \"UNKNOWN\" : \"ANY\",\n };\n }\n\n return {\n keyName,\n type: \"NEVER\",\n };\n}\n\nfunction parseLiteral(schema: JSONSchema4Type, keyName: string | undefined): AST {\n return {\n keyName,\n params: schema,\n type: \"LITERAL\",\n };\n}\n\nfunction parseNonLiteral(\n schema: NormalizedJSONSchema,\n type: SchemaType,\n options: Options,\n keyName: string | undefined,\n processed: Processed,\n usedNames: UsedNames,\n): AST {\n const definitions = getDefinitionsMemoized(getRootSchema(schema as any)); // TODO\n const keyNameFromDefinition = findKey(definitions, (_) => _ === schema);\n\n switch (type) {\n case \"ALL_OF\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n params: schema.allOf!.map((_) => parse(_, options, undefined, processed, usedNames)),\n type: \"INTERSECTION\",\n };\n case \"ANY\":\n return {\n ...(options.unknownAny ? T_UNKNOWN : T_ANY),\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n };\n case \"ANY_OF\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n params: schema.anyOf!.map((_) => parse(_, options, undefined, processed, usedNames)),\n type: \"UNION\",\n };\n case \"BOOLEAN\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"BOOLEAN\",\n };\n case \"CUSTOM_TYPE\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n params: schema.tsType!,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"CUSTOM_TYPE\",\n };\n case \"NAMED_ENUM\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(\n schema,\n keyNameFromDefinition ?? keyName,\n usedNames,\n options,\n )!,\n params: (schema as EnumJSONSchema).enum!.map((_, n) => ({\n ast: parseLiteral(_, undefined),\n keyName: schema.tsEnumNames![n],\n })),\n type: \"ENUM\",\n };\n case \"NAMED_SCHEMA\":\n return newInterface(schema as SchemaSchema, options, processed, usedNames, keyName);\n case \"NEVER\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"NEVER\",\n };\n case \"NULL\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"NULL\",\n };\n case \"NUMBER\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"NUMBER\",\n };\n case \"OBJECT\":\n return {\n comment: schema.description,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"OBJECT\",\n deprecated: schema.deprecated,\n };\n case \"ONE_OF\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n params: schema.oneOf!.map((_) => parse(_, options, undefined, processed, usedNames)),\n type: \"UNION\",\n };\n case \"REFERENCE\":\n throw Error(\"Refs should have been resolved by the resolver.\");\n case \"STRING\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"STRING\",\n };\n case \"TYPED_ARRAY\":\n if (Array.isArray(schema.items)) {\n // normalised to not be undefined\n const minItems = schema.minItems!;\n const maxItems = schema.maxItems!;\n const arrayType: TTuple = {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n maxItems,\n minItems,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n params: schema.items.map((_) => parse(_, options, undefined, processed, usedNames)),\n type: \"TUPLE\",\n };\n if (schema.additionalItems === true) {\n arrayType.spreadParam = options.unknownAny ? T_UNKNOWN : T_ANY;\n } else if (schema.additionalItems) {\n arrayType.spreadParam = parse(\n schema.additionalItems,\n options,\n undefined,\n processed,\n usedNames,\n );\n }\n return arrayType;\n } else {\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n params: parse(\n schema.items!,\n options,\n `{keyNameFromDefinition}Items`,\n processed,\n usedNames,\n ),\n type: \"ARRAY\",\n };\n }\n case \"UNION\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n params: (schema.type as JSONSchema4TypeName[]).map((type) => {\n const member: LinkedJSONSchema = { ...omit(schema, \"$id\", \"description\", \"title\"), type };\n maybeStripDefault(member);\n applySchemaTyping(member);\n return parse(member, options, undefined, processed, usedNames);\n }),\n type: \"UNION\",\n };\n case \"UNNAMED_ENUM\":\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n params: (schema as EnumJSONSchema).enum!.map((_) => parseLiteral(_, undefined)),\n type: \"UNION\",\n };\n case \"UNNAMED_SCHEMA\":\n return newInterface(\n schema as SchemaSchema,\n options,\n processed,\n usedNames,\n keyName,\n keyNameFromDefinition,\n );\n case \"UNTYPED_ARRAY\":\n // normalised to not be undefined\n const minItems = schema.minItems!;\n const maxItems = typeof schema.maxItems === \"number\" ? schema.maxItems : -1;\n const params = options.unknownAny ? T_UNKNOWN : T_ANY;\n if (minItems > 0 || maxItems >= 0) {\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n maxItems: schema.maxItems,\n minItems,\n // create a tuple of length N\n params: Array(Math.max(maxItems, minItems) || 0).fill(params),\n // if there is no maximum, then add a spread item to collect the rest\n spreadParam: maxItems >= 0 ? undefined : params,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"TUPLE\",\n };\n }\n\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n params,\n standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),\n type: \"ARRAY\",\n };\n }\n}\n\n/**\n * Compute a schema name using a series of fallbacks\n */\nfunction standaloneName(\n schema: NormalizedJSONSchema,\n keyNameFromDefinition: string | undefined,\n usedNames: UsedNames,\n options: Options,\n): string | undefined {\n const name =\n options.customName?.(schema, keyNameFromDefinition) ||\n schema.title ||\n schema.$id ||\n keyNameFromDefinition;\n if (name) {\n return generateName(name, usedNames);\n }\n}\n\nfunction newInterface(\n schema: SchemaSchema,\n options: Options,\n processed: Processed,\n usedNames: UsedNames,\n keyName?: string,\n keyNameFromDefinition?: string,\n): TInterface {\n const name = standaloneName(schema, keyNameFromDefinition, usedNames, options)!;\n return {\n comment: schema.description,\n deprecated: schema.deprecated,\n keyName,\n params: parseSchema(schema, options, processed, usedNames, name),\n standaloneName: name,\n superTypes: parseSuperTypes(schema, options, processed, usedNames),\n type: \"INTERFACE\",\n };\n}\n\nfunction parseSuperTypes(\n schema: SchemaSchema,\n options: Options,\n processed: Processed,\n usedNames: UsedNames,\n): TNamedInterface[] {\n // Type assertion needed because of dereferencing step\n // TODO: Type it upstream\n const superTypes = schema.extends as SchemaSchema[] | undefined;\n if (!superTypes) {\n return [];\n }\n return superTypes.map(\n (_) => parse(_, options, undefined, processed, usedNames) as TNamedInterface,\n );\n}\n\n/**\n * Helper to parse schema properties into params on the parent schema's type\n */\nfunction parseSchema(\n schema: SchemaSchema,\n options: Options,\n processed: Processed,\n usedNames: UsedNames,\n parentSchemaName: string,\n): TInterfaceParam[] {\n const required = new Set(schema.required ?? []);\n let asts: TInterfaceParam[] = Object.entries(schema.properties ?? {}).map(([key, value]) => ({\n ast: parse(value, options, key, processed, usedNames),\n isPatternProperty: false,\n isRequired: required.has(key),\n isUnreachableDefinition: false,\n keyName: key,\n }));\n\n let singlePatternProperty = false;\n if (schema.patternProperties) {\n // partially support patternProperties. in the case that\n // additionalProperties is not set, and there is only a single\n // value definition, we can validate against that.\n singlePatternProperty =\n !schema.additionalProperties && Object.keys(schema.patternProperties).length === 1;\n\n asts = asts.concat(\n Object.entries(schema.patternProperties).map(([key, value]) => {\n const ast = parse(value, options, key, processed, usedNames);\n const comment = `This interface was referenced by \\`${parentSchemaName}\\`'s JSON-Schema definition\nvia the \\`patternProperty\\` \"${key.replace(\"*/\", \"*\\\\/\")}\".`;\n ast.comment = ast.comment ? `${ast.comment}\\n\\n${comment}` : comment;\n return {\n ast,\n isPatternProperty: !singlePatternProperty,\n isRequired: singlePatternProperty || required.has(key),\n isUnreachableDefinition: false,\n keyName: singlePatternProperty ? \"[k: string]\" : key,\n };\n }),\n );\n }\n\n if (options.unreachableDefinitions) {\n asts = asts.concat(\n Object.entries(schema.$defs ?? {}).map(([key, value]) => {\n const ast = parse(value, options, key, processed, usedNames);\n const comment = `This interface was referenced by \\`${parentSchemaName}\\`'s JSON-Schema\nvia the \\`definition\\` \"${key}\".`;\n ast.comment = ast.comment ? `${ast.comment}\\n\\n${comment}` : comment;\n return {\n ast,\n isPatternProperty: false,\n isRequired: required.has(key),\n isUnreachableDefinition: true,\n keyName: key,\n };\n }),\n );\n }\n\n // handle additionalProperties\n switch (schema.additionalProperties) {\n case undefined:\n case true:\n if (singlePatternProperty) {\n return asts;\n }\n return asts.concat({\n ast: options.unknownAny ? T_UNKNOWN_ADDITIONAL_PROPERTIES : T_ANY_ADDITIONAL_PROPERTIES,\n isPatternProperty: false,\n isRequired: true,\n isUnreachableDefinition: false,\n keyName: \"[k: string]\",\n });\n\n case false:\n return asts;\n\n // pass \"true\" as the last param because in TS, properties\n // defined via index signatures are already optional\n default:\n return asts.concat({\n ast: parse(schema.additionalProperties, options, \"[k: string]\", processed, usedNames),\n isPatternProperty: false,\n isRequired: true,\n isUnreachableDefinition: false,\n keyName: \"[k: string]\",\n });\n }\n}\n\ntype Definitions = { [k: string]: NormalizedJSONSchema };\n\nfunction getDefinitions(\n schema: NormalizedJSONSchema,\n isSchema = true,\n processed = new Set<NormalizedJSONSchema>(),\n): Definitions {\n if (processed.has(schema)) {\n return {};\n }\n processed.add(schema);\n if (Array.isArray(schema)) {\n return schema.reduce(\n (prev, cur) => ({\n ...prev,\n ...getDefinitions(cur, false, processed),\n }),\n {},\n );\n }\n if (isPlainObject(schema)) {\n return {\n ...(isSchema && hasDefinitions(schema) ? schema.$defs : {}),\n ...Object.keys(schema).reduce<Definitions>(\n (prev, cur) => ({\n ...prev,\n ...getDefinitions(schema[cur], false, processed),\n }),\n {},\n ),\n };\n }\n return {};\n}\n\nconst getDefinitionsMemoized = memoize(getDefinitions);\n\n/**\n * TODO: Reduce rate of false positives\n */\nfunction hasDefinitions(schema: NormalizedJSONSchema): schema is JSONSchemaWithDefinitions {\n return \"$defs\" in schema;\n}\n","import type { JSONSchema } from \"./types/JSONSchema\";\n\nexport type DereferencedPaths = WeakMap<JSONSchema, string>;\n\ntype RefCache = Map<string, unknown>;\ntype SeenCache = WeakMap<object, unknown>;\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\";\n\nconst decodePointerSegment = (segment: string): string => {\n try {\n return decodeURIComponent(segment).replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n } catch {\n throw new ReferenceError(`Invalid JSON Pointer segment \"${segment}\" in $ref`);\n }\n};\n\nconst encodePointerSegment = (segment: string): string =>\n segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n\nconst childPointer = (parent: string, key: string): string =>\n parent === \"#\" ? `#/${encodePointerSegment(key)}` : `${parent}/${encodePointerSegment(key)}`;\n\nconst normalizeLocalRef = (ref: string): string => {\n if (ref === \"#\") return ref;\n if (!ref.startsWith(\"#/\")) {\n throw new ReferenceError(\n `Unsupported $ref \"${ref}\". Only same-document JSON Pointer refs are supported.`,\n );\n }\n return `#/${ref\n .slice(2)\n .split(\"/\")\n .map(decodePointerSegment)\n .map(encodePointerSegment)\n .join(\"/\")}`;\n};\n\nconst resolvePointer = (root: unknown, ref: string): unknown => {\n const pointer = normalizeLocalRef(ref);\n if (pointer === \"#\") return root;\n\n let current = root;\n for (const rawSegment of pointer.slice(2).split(\"/\")) {\n const segment = decodePointerSegment(rawSegment);\n if (!isObject(current) || !(segment in current)) {\n throw new ReferenceError(`Unable to resolve $ref \"${ref}\"`);\n }\n current = current[segment];\n }\n return current;\n};\n\nconst dereferenceNode = (\n root: JSONSchema,\n node: unknown,\n pointer: string,\n dereferencedPaths: DereferencedPaths,\n refCache: RefCache,\n seenCache: SeenCache,\n): unknown => {\n if (!isObject(node)) return node;\n\n if (typeof node.$ref === \"string\") {\n const ref = normalizeLocalRef(node.$ref);\n const cached = refCache.get(ref);\n if (cached) {\n if (isObject(cached)) {\n dereferencedPaths.set(cached as JSONSchema, ref);\n }\n return cached;\n }\n\n const target = resolvePointer(root, ref);\n if (!isObject(target)) return target;\n\n const targetClone: Record<string, unknown> | unknown[] = Array.isArray(target) ? [] : {};\n refCache.set(ref, targetClone);\n seenCache.set(target, targetClone);\n dereferencedPaths.set(targetClone as JSONSchema, ref);\n\n const targetPointer = ref;\n for (const [key, value] of Object.entries(target)) {\n (targetClone as Record<string, unknown>)[key] = dereferenceNode(\n root,\n value,\n childPointer(targetPointer, key),\n dereferencedPaths,\n refCache,\n seenCache,\n );\n }\n return targetClone;\n }\n\n const seen = seenCache.get(node);\n if (seen) return seen;\n\n const clone: Record<string, unknown> | unknown[] = Array.isArray(node) ? [] : {};\n seenCache.set(node, clone);\n refCache.set(pointer, clone);\n\n if (Array.isArray(node)) {\n node.forEach((value, index) => {\n (clone as unknown[])[index] = dereferenceNode(\n root,\n value,\n childPointer(pointer, String(index)),\n dereferencedPaths,\n refCache,\n seenCache,\n );\n });\n return clone;\n }\n\n for (const [key, value] of Object.entries(node)) {\n (clone as Record<string, unknown>)[key] = dereferenceNode(\n root,\n value,\n childPointer(pointer, key),\n dereferencedPaths,\n refCache,\n seenCache,\n );\n }\n\n return clone;\n};\n\nexport function dereference(schema: JSONSchema): {\n dereferencedPaths: DereferencedPaths;\n dereferencedSchema: JSONSchema;\n} {\n const dereferencedPaths: DereferencedPaths = new WeakMap();\n const dereferencedSchema = dereferenceNode(\n schema,\n schema,\n \"#\",\n dereferencedPaths,\n new Map(),\n new WeakMap(),\n ) as JSONSchema;\n return { dereferencedPaths, dereferencedSchema };\n}\n","import type { JSONSchema, LinkedJSONSchema } from \"./types/JSONSchema\";\nimport { traverse } from \"./utils\";\n\ntype Rule = (schema: JSONSchema) => boolean | void;\nconst rules = new Map<string, Rule>();\n\nrules.set(\"Enum members and tsEnumNames must be of the same length\", (schema) => {\n if (schema.enum && schema.tsEnumNames && schema.enum.length !== schema.tsEnumNames.length) {\n return false;\n }\n});\n\nrules.set(\"tsEnumNames must be an array of strings\", (schema) => {\n if (schema.tsEnumNames && schema.tsEnumNames.some((_) => typeof _ !== \"string\")) {\n return false;\n }\n});\n\nrules.set(\"When both maxItems and minItems are present, maxItems >= minItems\", (schema) => {\n const { maxItems, minItems } = schema;\n if (typeof maxItems === \"number\" && typeof minItems === \"number\") {\n return maxItems >= minItems;\n }\n});\n\nrules.set(\"When maxItems exists, maxItems >= 0\", (schema) => {\n const { maxItems } = schema;\n if (typeof maxItems === \"number\") {\n return maxItems >= 0;\n }\n});\n\nrules.set(\"When minItems exists, minItems >= 0\", (schema) => {\n const { minItems } = schema;\n if (typeof minItems === \"number\") {\n return minItems >= 0;\n }\n});\n\nrules.set(\"deprecated must be a boolean\", (schema) => {\n const typeOfDeprecated = typeof schema.deprecated;\n return typeOfDeprecated === \"boolean\" || typeOfDeprecated === \"undefined\";\n});\n\nexport function validate(schema: LinkedJSONSchema, filename: string): string[] {\n const errors: string[] = [];\n rules.forEach((rule, ruleName) => {\n traverse(schema, (schema, key) => {\n if (rule(schema) === false) {\n errors.push(`Error at key \"${key}\" in file \"${filename}\": ${ruleName}`);\n }\n return schema;\n });\n });\n return errors;\n}\n","import { Parent } from \"./types/JSONSchema\";\nimport type { JSONSchema, LinkedJSONSchema } from \"./types/JSONSchema\";\nimport { isPlainObject } from \"./compat\";\nimport type { JSONSchema4Type } from \"./types/json-schema\";\n\n/**\n * Traverses over the schema, giving each node a reference to its\n * parent node. We need this for downstream operations.\n */\nexport function link(\n schema: JSONSchema4Type | JSONSchema,\n parent: JSONSchema4Type | null = null,\n): LinkedJSONSchema {\n if (!Array.isArray(schema) && !isPlainObject(schema)) {\n return schema as LinkedJSONSchema;\n }\n\n // Handle cycles\n if ((schema as JSONSchema).hasOwnProperty(Parent)) {\n return schema as LinkedJSONSchema;\n }\n\n // Add a reference to this schema's parent\n Object.defineProperty(schema, Parent, {\n enumerable: false,\n value: parent,\n writable: false,\n });\n\n // Arrays\n if (Array.isArray(schema)) {\n schema.forEach((child) => link(child, schema));\n }\n\n // Objects\n for (const key in schema as JSONSchema) {\n link((schema as JSONSchema)[key], schema);\n }\n\n return schema as LinkedJSONSchema;\n}\n","import type { Options } from \".\";\n\nexport function validateOptions({ maxItems }: Partial<Options>): void {\n if (maxItems !== undefined && maxItems < -1) {\n throw RangeError(`Expected options.maxItems to be >= -1, but was given ${maxItems}.`);\n }\n}\n","import type { JSONSchema4 } from \"./types/json-schema\";\nimport { cloneDeep, merge } from \"./compat\";\nimport { format } from \"./formatter\";\nimport { generate } from \"./generator\";\nimport { normalize } from \"./normalizer\";\nimport { optimize } from \"./optimizer\";\nimport { parse } from \"./parser\";\nimport { dereference } from \"./resolver\";\nimport { validate } from \"./validator\";\nimport { link } from \"./linker\";\nimport { validateOptions } from \"./optionValidator\";\nimport type { JSONSchema as LinkedJSONSchema } from \"./types/JSONSchema\";\n\nexport type {\n EnumJSONSchema,\n JSONSchema,\n NamedEnumJSONSchema,\n CustomTypeJSONSchema,\n} from \"./types/JSONSchema\";\n\nexport interface FormatOptions {\n bracketSpacing?: boolean;\n printWidth?: number;\n semi?: boolean;\n singleQuote?: boolean;\n tabWidth?: number;\n trailingComma?: \"none\" | \"es5\" | \"all\";\n useTabs?: boolean;\n}\n\nexport type RefOptions = Record<string, unknown>;\n\nexport interface Options {\n /**\n * Preserved for upstream API compatibility.\n *\n * Executor's vendored compiler only resolves same-document JSON Pointer\n * `$ref`s and never fetches or reads external references, so this option is\n * accepted but ignored.\n */\n $refOptions: RefOptions;\n /**\n * Default value for additionalProperties, when it is not explicitly set.\n */\n additionalProperties: boolean;\n /**\n * Disclaimer comment prepended to the top of each generated file.\n */\n bannerComment: string;\n /**\n * Custom function to provide a type name for a given schema\n */\n customName?: (\n schema: LinkedJSONSchema,\n keyNameFromDefinition: string | undefined,\n ) => string | undefined;\n /**\n * Preserved for upstream API compatibility. External refs are not resolved,\n * so this option is accepted but ignored.\n */\n cwd: string;\n /**\n * Declare external schemas referenced via `$ref`?\n */\n declareExternallyReferenced: boolean;\n /**\n * Prepend enums with [`const`](https://www.typescriptlang.org/docs/handbook/enums.html#computed-and-constant-members)?\n */\n enableConstEnums: boolean;\n /**\n * Create enums from JSON enums with eponymous keys\n */\n inferStringEnumKeysFromValues: boolean;\n /**\n * Format code? Preserved for upstream API compatibility.\n *\n * Executor's vendored compiler does not bundle a formatter, so this option is\n * accepted but does not change output.\n */\n format: boolean;\n /**\n * Ignore maxItems and minItems for `array` types, preventing tuples being generated.\n */\n ignoreMinAndMaxItems: boolean;\n /**\n * Maximum number of unioned tuples to emit when representing bounded-size array types,\n * before falling back to emitting unbounded arrays. Increase this to improve precision\n * of emitted types, decrease it to improve performance, or set it to `-1` to ignore\n * `minItems` and `maxItems`.\n */\n maxItems: number;\n /**\n * Append all index signatures with `| undefined` so that they are strictly typed.\n *\n * This is required to be compatible with `strictNullChecks`.\n */\n strictIndexSignatures: boolean;\n /**\n * Formatting configuration. Preserved for upstream API compatibility.\n */\n style: FormatOptions;\n /**\n * Generate code for `definitions` that aren't referenced by the schema?\n */\n unreachableDefinitions: boolean;\n /**\n * Generate unknown type instead of any\n */\n unknownAny: boolean;\n}\n\nexport const DEFAULT_OPTIONS: Options = {\n $refOptions: {},\n additionalProperties: true, // TODO: default to empty schema (as per spec) instead\n bannerComment: `/* eslint-disable */\n/**\n* This file was automatically generated by json-schema-to-typescript.\n* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,\n* and run json-schema-to-typescript to regenerate this file.\n*/`,\n cwd: \"\",\n declareExternallyReferenced: true,\n enableConstEnums: true,\n inferStringEnumKeysFromValues: false,\n format: false,\n ignoreMinAndMaxItems: false,\n maxItems: 20,\n strictIndexSignatures: false,\n style: {\n bracketSpacing: false,\n printWidth: 120,\n semi: true,\n singleQuote: false,\n tabWidth: 2,\n trailingComma: \"none\",\n useTabs: false,\n },\n unreachableDefinitions: false,\n unknownAny: true,\n};\n\nexport function compile(schema: JSONSchema4, name: string, options: Partial<Options> = {}): string {\n validateOptions(options);\n\n const _options = merge({} as Options, DEFAULT_OPTIONS, options);\n\n // Initial clone to avoid mutating the input\n const _schema = cloneDeep(schema);\n\n const { dereferencedPaths, dereferencedSchema } = dereference(_schema);\n const linked = link(dereferencedSchema);\n const errors = validate(linked, name);\n if (errors.length) {\n throw new ValidationError(errors.join(\"\\n\"));\n }\n\n const normalized = normalize(linked, dereferencedPaths, name, _options);\n const parsed = parse(normalized, _options);\n const optimized = optimize(parsed, _options);\n const generated = generate(optimized, _options);\n const formatted = format(generated, _options);\n\n return formatted;\n}\n\nexport class ValidationError extends Error {}\n","import { hoistDefinitions, normalizeRefs } from \"./schema-refs\";\nimport { compile } from \"./vendor/json-schema-to-typescript\";\n\ntype JsonSchemaRecord = Record<string, unknown>;\ntype CompilerJsonSchema = JsonSchemaRecord | boolean;\ntype CompilerFormatOptions = {\n [key: string]: unknown;\n printWidth?: number;\n semi?: boolean;\n singleQuote?: boolean;\n trailingComma?: \"none\" | \"es5\" | \"all\";\n};\ntype SchemaCompilerOptions = {\n [key: string]: unknown;\n additionalProperties?: boolean;\n bannerComment?: string;\n enableConstEnums?: boolean;\n format?: boolean;\n style?: CompilerFormatOptions;\n unknownAny?: boolean;\n unreachableDefinitions?: boolean;\n};\n\nexport type TypeScriptRenderOptions = {\n compilerOptions?: Partial<SchemaCompilerOptions>;\n};\n\nexport type TypeScriptSchemaPreview = {\n readonly type: string;\n readonly definitions: Record<string, string>;\n};\n\nconst ROOT_WRAPPER_NAME = \"SchemaPreview\";\nconst ROOT_PROPERTY_NAME = \"__root\";\nconst TOOL_INPUT_PROPERTY_NAME = \"__input\";\nconst TOOL_OUTPUT_PROPERTY_NAME = \"__output\";\n\nconst DEFAULT_COMPILER_OPTIONS = {\n additionalProperties: false,\n bannerComment: \"\",\n enableConstEnums: false,\n format: false,\n unknownAny: true,\n unreachableDefinitions: false,\n style: {\n printWidth: 120,\n semi: true,\n singleQuote: false,\n trailingComma: \"none\",\n },\n} satisfies Partial<SchemaCompilerOptions>;\n\nconst DEFINITION_REF_PATTERN = /^#\\/definitions\\/(.+)$/;\nconst IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nconst asRecord = (value: unknown): JsonSchemaRecord =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as JsonSchemaRecord)\n : {};\n\nconst asCompilerSchema = (value: unknown): CompilerJsonSchema => {\n if (typeof value === \"boolean\") {\n return value;\n }\n\n if (value !== null && typeof value === \"object\") {\n return value as JsonSchemaRecord;\n }\n\n return {};\n};\n\nconst isNullSchema = (value: unknown): boolean => {\n if (value === false) {\n return false;\n }\n\n const schema = asRecord(value);\n return schema.type === \"null\" || schema.const === null;\n};\n\nconst appendNullSchema = (schemas: ReadonlyArray<unknown>): Array<unknown> =>\n schemas.some(isNullSchema) ? [...schemas] : [...schemas, { type: \"null\" }];\n\nconst schemaAlreadyAllowsNull = (schema: JsonSchemaRecord): boolean => {\n if (schema.type === \"null\" || schema.const === null) {\n return true;\n }\n\n if (Array.isArray(schema.type) && schema.type.includes(\"null\")) {\n return true;\n }\n\n if (Array.isArray(schema.enum) && schema.enum.includes(null)) {\n return true;\n }\n\n const compositeSchemas = [\n ...(Array.isArray(schema.anyOf) ? schema.anyOf : []),\n ...(Array.isArray(schema.oneOf) ? schema.oneOf : []),\n ];\n return compositeSchemas.some(isNullSchema);\n};\n\nconst normalizeNullable = (schema: JsonSchemaRecord): JsonSchemaRecord => {\n if (schema.nullable !== true) {\n return schema;\n }\n\n const { nullable: _nullable, ...base } = schema;\n if (schemaAlreadyAllowsNull(base)) {\n return base;\n }\n\n if (\"const\" in base) {\n const { const: constValue, type: _type, ...rest } = base;\n return { ...rest, enum: [constValue, null] };\n }\n\n if (Array.isArray(base.enum)) {\n return { ...base, enum: [...base.enum, null] };\n }\n\n if (typeof base.type === \"string\") {\n return { ...base, type: [base.type, \"null\"] };\n }\n\n if (Array.isArray(base.type)) {\n const types = base.type.filter((value): value is string => typeof value === \"string\");\n return types.length > 0\n ? { ...base, type: [...types, \"null\"] }\n : { anyOf: [base, { type: \"null\" }] };\n }\n\n if (Array.isArray(base.oneOf)) {\n return { ...base, oneOf: appendNullSchema(base.oneOf) };\n }\n\n if (Array.isArray(base.anyOf)) {\n return { ...base, anyOf: appendNullSchema(base.anyOf) };\n }\n\n return { anyOf: [base, { type: \"null\" }] };\n};\n\nconst normalizeSchema = (node: unknown): unknown => {\n if (node === null || typeof node !== \"object\") {\n return node;\n }\n\n if (Array.isArray(node)) {\n return node.map((item) => normalizeSchema(item));\n }\n\n const schema = node as JsonSchemaRecord;\n const normalized: JsonSchemaRecord = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (key === \"$ref\" && typeof value === \"string\") {\n const definitionName = value.match(DEFINITION_REF_PATTERN)?.[1];\n normalized[key] = definitionName ? `#/$defs/${definitionName}` : value;\n continue;\n }\n\n normalized[key] = normalizeSchema(value);\n }\n\n const nullable = normalizeNullable(normalized);\n if (\n nullable.type === \"object\" &&\n nullable.properties === undefined &&\n nullable.additionalProperties === undefined\n ) {\n return { ...nullable, additionalProperties: {} };\n }\n return nullable;\n};\n\nconst mergeDefinitions = (\n externalDefs: ReadonlyMap<string, unknown>,\n localDefs: Record<string, unknown>,\n): Record<string, unknown> => {\n const merged: Record<string, unknown> = {};\n\n for (const [name, schema] of externalDefs) {\n merged[name] = normalizeSchema(normalizeRefs(asCompilerSchema(schema)));\n }\n\n for (const [name, schema] of Object.entries(localDefs)) {\n merged[name] = normalizeSchema(normalizeRefs(asCompilerSchema(schema)));\n }\n\n return merged;\n};\n\nconst buildWrappedObjectSchema = (\n properties: ReadonlyArray<readonly [string, unknown]>,\n defs: ReadonlyMap<string, unknown>,\n): JsonSchemaRecord => {\n const normalizedProperties: Record<string, unknown> = {};\n const localDefs: Record<string, unknown> = {};\n\n for (const [name, schema] of properties) {\n const normalizedSchema = normalizeSchema(normalizeRefs(asCompilerSchema(schema)));\n const { stripped, defs: schemaDefs } = hoistDefinitions(normalizedSchema);\n normalizedProperties[name] = asCompilerSchema(stripped);\n Object.assign(localDefs, schemaDefs);\n }\n\n const mergedDefs = mergeDefinitions(defs, localDefs);\n const wrappedSchema: JsonSchemaRecord = {\n type: \"object\",\n properties: normalizedProperties,\n required: properties.map(([name]) => name),\n additionalProperties: false,\n };\n\n if (Object.keys(mergedDefs).length > 0) {\n wrappedSchema.$defs = mergedDefs;\n }\n\n return wrappedSchema;\n};\n\nconst buildWrappedSchema = (\n schema: unknown,\n defs: ReadonlyMap<string, unknown>,\n): JsonSchemaRecord => buildWrappedObjectSchema([[ROOT_PROPERTY_NAME, schema]], defs);\n\nconst compilerOptionsFrom = (options: TypeScriptRenderOptions): Partial<SchemaCompilerOptions> => ({\n ...DEFAULT_COMPILER_OPTIONS,\n ...options.compilerOptions,\n bannerComment: \"\",\n format: false,\n style: {\n ...DEFAULT_COMPILER_OPTIONS.style,\n ...options.compilerOptions?.style,\n },\n});\n\ntype GeneratedDeclaration = {\n readonly kind: \"interface\" | \"type\";\n readonly name: string;\n readonly body: string;\n};\n\ntype ScanState = {\n quote: '\"' | \"'\" | \"`\" | null;\n escaping: boolean;\n lineComment: boolean;\n blockComment: boolean;\n};\n\nconst emptyScanState = (): ScanState => ({\n quote: null,\n escaping: false,\n lineComment: false,\n blockComment: false,\n});\n\nconst stepScanState = (state: ScanState, current: string, next: string): { skipNext: boolean } => {\n if (state.lineComment) {\n if (current === \"\\n\" || current === \"\\r\") {\n state.lineComment = false;\n }\n return { skipNext: false };\n }\n\n if (state.blockComment) {\n if (current === \"*\" && next === \"/\") {\n state.blockComment = false;\n return { skipNext: true };\n }\n return { skipNext: false };\n }\n\n if (state.quote) {\n if (state.escaping) {\n state.escaping = false;\n return { skipNext: false };\n }\n\n if (current === \"\\\\\") {\n state.escaping = true;\n return { skipNext: false };\n }\n\n if (current === state.quote) {\n state.quote = null;\n }\n return { skipNext: false };\n }\n\n if (current === \"/\" && next === \"/\") {\n state.lineComment = true;\n return { skipNext: true };\n }\n\n if (current === \"/\" && next === \"*\") {\n state.blockComment = true;\n return { skipNext: true };\n }\n\n if (current === '\"' || current === \"'\" || current === \"`\") {\n state.quote = current;\n }\n\n return { skipNext: false };\n};\n\nconst findMatchingBrace = (source: string, start: number): number => {\n const state = emptyScanState();\n let depth = 0;\n\n for (let index = start; index < source.length; index += 1) {\n const current = source[index] ?? \"\";\n const next = source[index + 1] ?? \"\";\n const wasCode = !state.quote && !state.lineComment && !state.blockComment;\n const { skipNext } = stepScanState(state, current, next);\n\n if (wasCode && !state.quote && !state.lineComment && !state.blockComment) {\n if (current === \"{\") {\n depth += 1;\n } else if (current === \"}\") {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n\n if (skipNext) {\n index += 1;\n }\n }\n\n return -1;\n};\n\nconst findMatchingParen = (source: string, start: number): number => {\n const state = emptyScanState();\n let depth = 0;\n\n for (let index = start; index < source.length; index += 1) {\n const current = source[index] ?? \"\";\n const next = source[index + 1] ?? \"\";\n const wasCode = !state.quote && !state.lineComment && !state.blockComment;\n const { skipNext } = stepScanState(state, current, next);\n\n if (wasCode && !state.quote && !state.lineComment && !state.blockComment) {\n if (current === \"(\") {\n depth += 1;\n } else if (current === \")\") {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n\n if (skipNext) {\n index += 1;\n }\n }\n\n return -1;\n};\n\nconst findTypeAliasEnd = (source: string, start: number): number => {\n const state = emptyScanState();\n let braceDepth = 0;\n let bracketDepth = 0;\n let parenDepth = 0;\n let seenToken = false;\n\n for (let index = start; index < source.length; index += 1) {\n const current = source[index] ?? \"\";\n const next = source[index + 1] ?? \"\";\n const wasCode = !state.quote && !state.lineComment && !state.blockComment;\n const { skipNext } = stepScanState(state, current, next);\n\n if (wasCode && !state.quote && !state.lineComment && !state.blockComment) {\n if (current === \"{\") {\n braceDepth += 1;\n } else if (current === \"}\") {\n braceDepth = Math.max(0, braceDepth - 1);\n } else if (current === \"[\") {\n bracketDepth += 1;\n } else if (current === \"]\") {\n bracketDepth = Math.max(0, bracketDepth - 1);\n } else if (current === \"(\") {\n parenDepth += 1;\n } else if (current === \")\") {\n parenDepth = Math.max(0, parenDepth - 1);\n }\n\n if (!/\\s/.test(current)) {\n seenToken = true;\n }\n\n if (\n seenToken &&\n (current === \";\" || current === \"\\n\" || current === \"\\r\") &&\n braceDepth === 0 &&\n bracketDepth === 0 &&\n parenDepth === 0\n ) {\n return index;\n }\n }\n\n if (skipNext) {\n index += 1;\n }\n }\n\n return -1;\n};\n\nconst parseGeneratedDeclarations = (source: string): Array<GeneratedDeclaration> => {\n const declarations: Array<GeneratedDeclaration> = [];\n const pattern = /export\\s+(interface|type)\\s+([A-Za-z_$][A-Za-z0-9_$]*)/g;\n\n for (let match = pattern.exec(source); match; match = pattern.exec(source)) {\n const kind = match[1] as \"interface\" | \"type\";\n const name = match[2] ?? \"\";\n\n if (!IDENTIFIER_PATTERN.test(name)) {\n continue;\n }\n\n if (kind === \"interface\") {\n const braceStart = source.indexOf(\"{\", pattern.lastIndex);\n if (braceStart < 0) {\n continue;\n }\n\n const braceEnd = findMatchingBrace(source, braceStart);\n if (braceEnd < 0) {\n continue;\n }\n\n declarations.push({\n kind,\n name,\n body: source.slice(braceStart, braceEnd + 1),\n });\n pattern.lastIndex = braceEnd + 1;\n continue;\n }\n\n const equalsIndex = source.indexOf(\"=\", pattern.lastIndex);\n if (equalsIndex < 0) {\n continue;\n }\n\n const end = findTypeAliasEnd(source, equalsIndex + 1);\n if (end < 0) {\n continue;\n }\n\n declarations.push({\n kind,\n name,\n body: source.slice(equalsIndex + 1, end).trim(),\n });\n pattern.lastIndex = end + 1;\n }\n\n return declarations;\n};\n\nconst extractPropertyType = (interfaceBody: string, propertyName: string): string | null => {\n const propertyIndex = interfaceBody.indexOf(propertyName);\n if (propertyIndex < 0) {\n return null;\n }\n\n const colonIndex = interfaceBody.indexOf(\":\", propertyIndex + propertyName.length);\n if (colonIndex < 0) {\n return null;\n }\n\n const end = findTypeAliasEnd(interfaceBody, colonIndex + 1);\n if (end < 0) {\n return null;\n }\n\n return interfaceBody.slice(colonIndex + 1, end).trim();\n};\n\nconst containsTopLevelUnion = (source: string): boolean => {\n const state = emptyScanState();\n let braceDepth = 0;\n let bracketDepth = 0;\n let parenDepth = 0;\n\n for (let index = 0; index < source.length; index += 1) {\n const current = source[index] ?? \"\";\n const next = source[index + 1] ?? \"\";\n const wasCode = !state.quote && !state.lineComment && !state.blockComment;\n const { skipNext } = stepScanState(state, current, next);\n\n if (wasCode && !state.quote && !state.lineComment && !state.blockComment) {\n if (current === \"{\") {\n braceDepth += 1;\n } else if (current === \"}\") {\n braceDepth = Math.max(0, braceDepth - 1);\n } else if (current === \"[\") {\n bracketDepth += 1;\n } else if (current === \"]\") {\n bracketDepth = Math.max(0, bracketDepth - 1);\n } else if (current === \"(\") {\n parenDepth += 1;\n } else if (current === \")\") {\n parenDepth = Math.max(0, parenDepth - 1);\n } else if (current === \"|\" && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) {\n return true;\n }\n }\n\n if (skipNext) {\n index += 1;\n }\n }\n\n return false;\n};\n\nconst significantBefore = (source: string, start: number): string => {\n for (let index = start; index >= 0; index -= 1) {\n const char = source[index] ?? \"\";\n if (!/\\s/.test(char)) {\n return char;\n }\n }\n return \"\";\n};\n\nconst significantAfter = (source: string, start: number): string => {\n for (let index = start; index < source.length; index += 1) {\n const char = source[index] ?? \"\";\n if (!/\\s/.test(char)) {\n return char;\n }\n }\n return \"\";\n};\n\nconst stripRedundantUnionParens = (source: string): string => {\n let output = \"\";\n\n for (let index = 0; index < source.length; index += 1) {\n const current = source[index] ?? \"\";\n if (current !== \"(\") {\n output += current;\n continue;\n }\n\n const end = findMatchingParen(source, index);\n if (end < 0) {\n output += current;\n continue;\n }\n\n const previous = significantBefore(source, index - 1);\n const next = significantAfter(source, end + 1);\n const inner = source.slice(index + 1, end);\n const keepParens =\n !containsTopLevelUnion(inner) ||\n /[A-Za-z0-9_$]/.test(previous) ||\n next === \"[\" ||\n next === \".\" ||\n next === \"<\";\n\n if (keepParens) {\n output += source.slice(index, end + 1);\n } else {\n output += stripRedundantUnionParens(inner);\n }\n index = end;\n }\n\n return output;\n};\n\nconst compactTypeScript = (value: string): string => {\n const state = emptyScanState();\n let output = \"\";\n let pendingWhitespace = false;\n let braceDepth = 0;\n\n const emitWhitespace = () => {\n if (output.length > 0) {\n pendingWhitespace = true;\n }\n };\n\n const previousSignificant = (): string => output.trimEnd().at(-1) ?? \"\";\n\n const nextSignificant = (start: number): string => {\n for (let index = start; index < value.length; index += 1) {\n const char = value[index] ?? \"\";\n if (!/\\s/.test(char)) {\n return char;\n }\n }\n return \"\";\n };\n\n const terminateMemberAtNewline = (index: number): void => {\n if (braceDepth <= 0) {\n return;\n }\n\n const previous = previousSignificant();\n if (!previous || previous === \"{\" || previous === \";\" || previous === \"|\" || previous === \"&\") {\n return;\n }\n\n const next = nextSignificant(index + 1);\n if (!next || next === \"|\" || next === \"&\" || next === \")\" || next === \"]\" || next === \",\") {\n return;\n }\n\n output = output.trimEnd() + \";\";\n pendingWhitespace = true;\n };\n\n for (let index = 0; index < value.length; index += 1) {\n const current = value[index] ?? \"\";\n const next = value[index + 1] ?? \"\";\n\n if (!state.quote && !state.lineComment && !state.blockComment) {\n if (current === \"/\" && next === \"/\") {\n emitWhitespace();\n index += 1;\n state.lineComment = true;\n continue;\n }\n\n if (current === \"/\" && next === \"*\") {\n emitWhitespace();\n index += 1;\n state.blockComment = true;\n continue;\n }\n\n if (/\\s/.test(current)) {\n if (current === \"\\n\" || current === \"\\r\") {\n terminateMemberAtNewline(index);\n }\n emitWhitespace();\n continue;\n }\n }\n\n if (state.lineComment) {\n if (current === \"\\n\" || current === \"\\r\") {\n state.lineComment = false;\n }\n continue;\n }\n\n if (state.blockComment) {\n if (current === \"*\" && next === \"/\") {\n state.blockComment = false;\n index += 1;\n }\n continue;\n }\n\n if (pendingWhitespace && output.length > 0) {\n output += \" \";\n }\n pendingWhitespace = false;\n output += current;\n\n if (state.quote) {\n if (state.escaping) {\n state.escaping = false;\n } else if (current === \"\\\\\") {\n state.escaping = true;\n } else if (current === state.quote) {\n state.quote = null;\n }\n continue;\n }\n\n if (current === '\"' || current === \"'\" || current === \"`\") {\n state.quote = current;\n continue;\n }\n\n if (current === \"{\") {\n braceDepth += 1;\n } else if (current === \"}\") {\n braceDepth = Math.max(0, braceDepth - 1);\n }\n }\n\n return stripRedundantUnionParens(output.trim());\n};\n\nconst getDefinitionsFromDeclarations = (\n declarations: ReadonlyArray<GeneratedDeclaration>,\n): Record<string, string> =>\n Object.fromEntries(\n declarations\n .filter((declaration) => declaration.name !== ROOT_WRAPPER_NAME)\n .map((declaration) => [declaration.name, compactTypeScript(declaration.body)])\n .sort(([left], [right]) => left.localeCompare(right)),\n );\n\nconst previewFromCompiledTypeScript = (source: string): TypeScriptSchemaPreview => {\n const declarations = parseGeneratedDeclarations(source);\n const rootDeclaration = declarations.find(\n (declaration) => declaration.name === ROOT_WRAPPER_NAME,\n );\n const rootType =\n rootDeclaration?.kind === \"interface\"\n ? extractPropertyType(rootDeclaration.body, ROOT_PROPERTY_NAME)\n : null;\n\n return {\n type: compactTypeScript(rootType ?? \"unknown\"),\n definitions: getDefinitionsFromDeclarations(declarations),\n };\n};\n\nconst previewToolFromCompiledTypeScript = (source: string): ToolTypeScriptPreview => {\n const declarations = parseGeneratedDeclarations(source);\n const rootDeclaration = declarations.find(\n (declaration) => declaration.name === ROOT_WRAPPER_NAME,\n );\n const inputType =\n rootDeclaration?.kind === \"interface\"\n ? extractPropertyType(rootDeclaration.body, TOOL_INPUT_PROPERTY_NAME)\n : null;\n const outputType =\n rootDeclaration?.kind === \"interface\"\n ? extractPropertyType(rootDeclaration.body, TOOL_OUTPUT_PROPERTY_NAME)\n : null;\n const definitions = getDefinitionsFromDeclarations(declarations);\n\n return {\n ...(inputType ? { inputTypeScript: compactTypeScript(inputType) } : {}),\n ...(outputType ? { outputTypeScript: compactTypeScript(outputType) } : {}),\n ...(Object.keys(definitions).length > 0 ? { typeScriptDefinitions: definitions } : {}),\n };\n};\n\nconst compileSchemaPreview = async (\n schema: unknown,\n defs: ReadonlyMap<string, unknown>,\n options: TypeScriptRenderOptions,\n): Promise<TypeScriptSchemaPreview> => {\n const wrappedSchema = buildWrappedSchema(schema, defs);\n const source = compile(wrappedSchema, ROOT_WRAPPER_NAME, compilerOptionsFrom(options));\n return previewFromCompiledTypeScript(source);\n};\n\nexport const schemaToTypeScriptPreview = (\n schema: unknown,\n options: TypeScriptRenderOptions = {},\n): Promise<TypeScriptSchemaPreview> => {\n const localDefs = new Map<string, unknown>(\n Object.entries(hoistDefinitions(asCompilerSchema(schema)).defs),\n );\n return schemaToTypeScriptPreviewWithDefs(schema, localDefs, options);\n};\n\nexport const schemaToTypeScriptPreviewWithDefs = (\n schema: unknown,\n defs: ReadonlyMap<string, unknown>,\n options: TypeScriptRenderOptions = {},\n): Promise<TypeScriptSchemaPreview> =>\n compileSchemaPreview(schema, defs, options).then(\n (preview) => preview,\n () => ({\n type: \"unknown\",\n definitions: {},\n }),\n );\n\nexport type ToolTypeScriptPreview = {\n inputTypeScript?: string;\n outputTypeScript?: string;\n typeScriptDefinitions?: Record<string, string>;\n};\n\nexport const buildToolTypeScriptPreview = async (input: {\n inputSchema?: unknown;\n outputSchema?: unknown;\n defs: ReadonlyMap<string, unknown>;\n options?: TypeScriptRenderOptions;\n}): Promise<ToolTypeScriptPreview> => {\n const properties: Array<readonly [string, unknown]> = [];\n if (input.inputSchema !== undefined) {\n properties.push([TOOL_INPUT_PROPERTY_NAME, input.inputSchema]);\n }\n if (input.outputSchema !== undefined) {\n properties.push([TOOL_OUTPUT_PROPERTY_NAME, input.outputSchema]);\n }\n if (properties.length === 0) {\n return {};\n }\n\n const wrappedSchema = buildWrappedObjectSchema(properties, input.defs);\n return Promise.resolve()\n .then(() => compile(wrappedSchema, ROOT_WRAPPER_NAME, compilerOptionsFrom(input.options ?? {})))\n .then(\n (source) => previewToolFromCompiledTypeScript(source),\n () => ({\n ...(input.inputSchema !== undefined ? { inputTypeScript: \"unknown\" } : {}),\n ...(input.outputSchema !== undefined ? { outputTypeScript: \"unknown\" } : {}),\n }),\n );\n};\n","// ---------------------------------------------------------------------------\n// ToolResult — typed value-based discriminated union returned by tool\n// handlers and `invokeTool`. Domain success and expected failure both\n// resolve through Effect's success channel; only true infra defects use\n// the Effect failure channel.\n// ---------------------------------------------------------------------------\n\nimport { Effect, Schema } from \"effect\";\n\nexport const ToolErrorSchema = Schema.Struct({\n code: Schema.String,\n message: Schema.String,\n status: Schema.optional(Schema.Number),\n details: Schema.optional(Schema.Unknown),\n retryable: Schema.optional(Schema.Boolean),\n});\n\nexport type ToolError = typeof ToolErrorSchema.Type;\n\nexport const ToolHttpMetaSchema = Schema.Struct({\n status: Schema.Number,\n headers: Schema.Record(Schema.String, Schema.String),\n});\n\n/**\n * Transport metadata for HTTP-backed tools (OpenAPI). Kept beside `data`\n * rather than wrapped around it: `data` stays the upstream payload, while\n * cross-cutting transport facts (pagination Link headers, rate-limit\n * headers) remain reachable for callers that need them.\n */\nexport type ToolHttpMeta = typeof ToolHttpMetaSchema.Type;\n\nexport const ToolFileSchema = Schema.TaggedStruct(\"ToolFile\", {\n name: Schema.optional(Schema.String),\n mimeType: Schema.String,\n encoding: Schema.Literal(\"base64\"),\n data: Schema.String.annotate({\n description: \"Base64-encoded file bytes.\",\n contentEncoding: \"base64\",\n }),\n byteLength: Schema.Int.annotate({\n description: \"Raw file size in bytes before base64 encoding.\",\n }),\n});\n\nexport type ToolFile = typeof ToolFileSchema.Type;\n\nexport const ToolFileJsonSchema = Schema.toJsonSchemaDocument(ToolFileSchema).schema;\n\nconst matchesToolFileSchema = Schema.is(ToolFileSchema);\n\nexport const isToolFile = (value: unknown): value is ToolFile => matchesToolFileSchema(value);\n\nexport type ToolResult<T> =\n | { readonly ok: true; readonly data: T; readonly http?: ToolHttpMeta }\n | { readonly ok: false; readonly error: ToolError };\n\nexport const ToolResult = {\n ok: <T>(data: T, meta?: { readonly http?: ToolHttpMeta }): ToolResult<T> => ({\n ok: true,\n data,\n ...(meta?.http ? { http: meta.http } : {}),\n }),\n fail: <T = never>(error: ToolError): ToolResult<T> => ({ ok: false, error }),\n} as const;\n\nconst ToolResultSchema = Schema.Union([\n Schema.Struct({\n ok: Schema.Literal(true),\n data: Schema.Unknown,\n http: Schema.optional(ToolHttpMetaSchema),\n }),\n Schema.Struct({ ok: Schema.Literal(false), error: ToolErrorSchema }),\n]);\n\nconst isUnknownToolResult = Schema.is(ToolResultSchema);\n\nexport const isToolResult = (value: unknown): value is ToolResult<unknown> =>\n isUnknownToolResult(value);\n\n/**\n * Annotate the current span with the outcome of a tool invocation.\n *\n * `ToolResult.fail` rides the Effect *success* channel by design (expected\n * failures are values, not defects), which means the tracer records those\n * spans as healthy. Without this, \"user keeps hitting 4xx walls\" is invisible\n * to telemetry — the exact class of signal that lets us catch product issues\n * before they're reported. Stamped attributes:\n *\n * - `executor.tool.outcome` — \"ok\" | \"fail\" (always, on ToolResults)\n * - `executor.tool.error_code` — ToolError.code (fail only)\n * - `executor.tool.error_status` — upstream HTTP status (fail, when present)\n *\n * Codes/statuses are enumerable identifiers, never user content — safe span\n * attributes. Non-ToolResult values (raw success payloads) annotate \"ok\".\n */\nexport const annotateToolResultOutcome = (value: unknown): Effect.Effect<void> => {\n if (isToolResult(value) && !value.ok) {\n return Effect.annotateCurrentSpan({\n \"executor.tool.outcome\": \"fail\",\n \"executor.tool.error_code\": value.error.code,\n ...(value.error.status != null ? { \"executor.tool.error_status\": value.error.status } : {}),\n });\n }\n return Effect.annotateCurrentSpan({ \"executor.tool.outcome\": \"ok\" });\n};\n","import { Effect, Inspectable, Layer, Option, Predicate, Schema } from \"effect\";\nimport { FetchHttpClient, type HttpClient } from \"effect/unstable/http\";\nimport { fumadb } from \"@executor-js/fumadb\";\nimport { memoryAdapter } from \"@executor-js/fumadb/adapters/memory\";\nimport { withQueryContext, type Condition, type ConditionBuilder } from \"@executor-js/fumadb/query\";\nimport { schema as fumaSchema, type RelationsMap } from \"@executor-js/fumadb/schema\";\nimport type { AnyColumn } from \"@executor-js/fumadb/schema\";\nimport { generateKeyBetween } from \"fractional-indexing\";\n\nimport {\n StorageError,\n isStorageFailure,\n makeFumaClient,\n type FumaDb,\n type FumaRow,\n type FumaTables,\n type StorageFailure,\n} from \"./fuma-runtime\";\nimport { makeFumaBlobStore, pluginBlobStore, type BlobStore, type OwnerPartitions } from \"./blob\";\nimport { coreToolsPlugin } from \"./core-tools\";\nimport type {\n Connection,\n ConnectionInputOrigin,\n ConnectionRef,\n CreateConnectionInput,\n ConnectionValueInput,\n UpdateConnectionInput,\n} from \"./connection\";\nimport {\n coreSchema,\n isToolPolicyAction,\n TOOL_INVOCATION_COLUMNS,\n type ConnectionRow,\n type CoreSchema,\n type IntegrationRow,\n type OAuthClientRow,\n type ToolInvocationRow,\n type ToolRow,\n type ToolPolicyRow,\n} from \"./core-schema\";\nimport {\n ElicitationDeclinedError,\n ElicitationResponse,\n FormElicitation,\n type ElicitationHandler,\n type ElicitationRequest,\n type OnElicitation,\n type InvokeOptions,\n} from \"./elicitation\";\n\nexport type { OnElicitation, InvokeOptions } from \"./elicitation\";\nimport {\n ConnectionNotFoundError,\n CredentialProviderNotRegisteredError,\n CredentialResolutionError,\n IntegrationNotFoundError,\n InvalidConnectionInputError,\n IntegrationRemovalNotAllowedError,\n NoHandlerError,\n PluginNotLoadedError,\n ToolBlockedError,\n ToolInvocationError,\n ToolNotFoundError,\n type ExecuteError,\n} from \"./errors\";\nimport {\n AuthTemplateSlug,\n ConnectionAddress,\n ConnectionName,\n IntegrationSlug,\n NO_AUTH_TEMPLATE,\n OAuthClientSlug,\n Owner,\n PolicyId,\n ProviderItemId,\n ProviderKey,\n Subject,\n Tenant,\n ToolAddress,\n ToolName,\n} from \"./ids\";\nimport type {\n AuthMethodDescriptor,\n Integration,\n IntegrationConfig,\n RegisterIntegrationInput,\n} from \"./integration\";\nimport {\n makeOAuthService,\n type MintOAuthConnectionInput,\n type OAuthScopePolicy,\n} from \"./oauth-service\";\nimport type { OAuthService } from \"./oauth-client\";\nimport {\n comparePolicyRow,\n isValidPattern,\n matchPattern,\n resolveEffectivePolicy,\n rowToToolPolicy,\n type CreateToolPolicyInput,\n type EffectivePolicy,\n type RemoveToolPolicyInput,\n type ToolPolicy,\n type UpdateToolPolicyInput,\n} from \"./policies\";\nimport type { CredentialProvider, ProviderEntry } from \"./provider\";\nimport type {\n AnyPlugin,\n Elicit,\n IntegrationConfigureSchema,\n IntegrationPresetCatalogEntry,\n IntegrationRecord,\n OwnerBinding,\n PluginCtx,\n PluginExtensions,\n ResolveToolsResult,\n StaticSourceDecl,\n StaticToolDecl,\n StorageDeps,\n ToolPolicyProvider,\n ToolPolicyProviderRule,\n ToolInvocationCredential,\n} from \"./plugin\";\nimport {\n pluginStorageId,\n type PluginStorageCollectionData,\n type PluginStorageCollectionDefinition,\n type PluginStorageCollectionQueryInput,\n type PluginStorageEntry,\n type PluginStorageFacade,\n type PluginStorageRuntimeCollectionDefinition,\n type PluginStorageRuntimeIndexSpec,\n} from \"./plugin-storage\";\nimport {\n assertExecutorOwnerPolicyTable,\n ORG_SUBJECT,\n type ExecutorOwnerPolicyContext,\n} from \"./owner-policy\";\nimport { ToolSchemaView, type IntegrationDetectionResult } from \"./types\";\nimport { type Tool, type ToolAnnotations, type ToolDef, type ToolListFilter } from \"./tool\";\nimport { buildToolTypeScriptPreview } from \"./schema-types\";\nimport { collectReferencedDefinitions } from \"./schema-refs\";\nimport {\n refreshAccessToken,\n exchangeClientCredentials,\n shouldRefreshToken,\n type OAuthEndpointUrlPolicy,\n} from \"./oauth-helpers\";\nimport { connectionIdentifier } from \"./connection-name-identifier\";\nimport { annotateToolResultOutcome } from \"./tool-result\";\n\nconst PLUGIN_STORAGE_DELETE_KEY_BATCH_SIZE = 90;\nconst PLUGIN_STORAGE_CREATE_ROW_BATCH_SIZE = 90;\nconst MAX_APPROVAL_ARGUMENT_PREVIEW_CHARS = 4_000;\n\n// ---------------------------------------------------------------------------\n// Elicitation handler — resolved once at `createExecutor({ onElicitation })`\n// and overridable per `execute`. A tool that requests user input mid-execution\n// suspends the fiber and the handler decides how to respond. The \"accept-all\"\n// sentinel auto-accepts (tests / non-interactive hosts).\n// ---------------------------------------------------------------------------\n\nconst acceptAllHandler: ElicitationHandler = () =>\n Effect.succeed(ElicitationResponse.make({ action: \"accept\" }));\n\nconst resolveElicitationHandler = (onElicitation: OnElicitation): ElicitationHandler =>\n onElicitation === \"accept-all\" ? acceptAllHandler : onElicitation;\n\n// ---------------------------------------------------------------------------\n// Address scheme — `tools.<integration>.<owner>.<connection>.<tool>`.\n// ---------------------------------------------------------------------------\n\nconst ADDRESS_PREFIX = \"tools\";\n\nexport interface ParsedToolAddress {\n readonly integration: IntegrationSlug;\n readonly owner: Owner;\n readonly connection: ConnectionName;\n readonly tool: ToolName;\n}\n\nconst isOwner = (value: string): value is Owner => value === \"org\" || value === \"user\";\n\n/** Parse a callable address; null when it's not a well-formed\n * `tools.<integration>.<owner>.<connection>.<tool>`.\n *\n * The four leading segments (prefix, integration, owner, connection) are\n * slug-like and never contain a `.`; the `<tool>` segment is the *entire*\n * remainder after the 4th dot, so it may itself contain dots. That lets a tool\n * whose name is a structured `group.leaf` path (e.g. an OpenAPI\n * `aliases.deleteAlias`) address naturally as\n * `tools.<integration>.<owner>.<connection>.aliases.deleteAlias` — the same\n * dotted nesting the sandbox `tools` proxy produces from property access. */\nexport const parseToolAddress = (address: string): ParsedToolAddress | null => {\n // Walk to the 4th dot; everything past it is the tool (dots and all).\n let cut = -1;\n for (let i = 0; i < 4; i++) {\n cut = address.indexOf(\".\", cut + 1);\n if (cut === -1) return null;\n }\n const [prefix, integration, owner, connection] = address.slice(0, cut).split(\".\") as [\n string,\n string,\n string,\n string,\n ];\n const tool = address.slice(cut + 1);\n if (prefix !== ADDRESS_PREFIX) return null;\n if (!isOwner(owner)) return null;\n if (integration.length === 0 || connection.length === 0 || tool.length === 0) {\n return null;\n }\n return {\n integration: IntegrationSlug.make(integration),\n owner,\n connection: ConnectionName.make(connection),\n tool: ToolName.make(tool),\n };\n};\n\nexport const connectionAddress = (\n owner: Owner,\n integration: IntegrationSlug,\n connection: ConnectionName,\n): ConnectionAddress =>\n ConnectionAddress.make(`${ADDRESS_PREFIX}.${integration}.${owner}.${connection}`);\n\nexport const toolAddress = (\n owner: Owner,\n integration: IntegrationSlug,\n connection: ConnectionName,\n tool: ToolName,\n): ToolAddress =>\n ToolAddress.make(`${ADDRESS_PREFIX}.${integration}.${owner}.${connection}.${tool}`);\n\n// ---------------------------------------------------------------------------\n// Owner key helpers — every owned-row write stamps `tenant`, `owner`,\n// `subject` (org → subject=\"\").\n// ---------------------------------------------------------------------------\n\ninterface OwnedKeys {\n readonly tenant: string;\n readonly owner: Owner;\n readonly subject: string;\n}\n\n// ---------------------------------------------------------------------------\n// Executor — public surface. Every list/execute/schema call is a direct\n// core-table query unioned with the in-memory static pool.\n// ---------------------------------------------------------------------------\n\nexport type Executor<TPlugins extends readonly AnyPlugin[] = readonly []> = {\n readonly integrations: {\n readonly list: () => Effect.Effect<readonly Integration[], StorageFailure>;\n readonly get: (slug: IntegrationSlug) => Effect.Effect<Integration | null, StorageFailure>;\n readonly update: (\n slug: IntegrationSlug,\n patch: { readonly name?: string; readonly description?: string },\n ) => Effect.Effect<void, IntegrationNotFoundError | StorageFailure>;\n readonly remove: (\n slug: IntegrationSlug,\n ) => Effect.Effect<void, IntegrationRemovalNotAllowedError | StorageFailure>;\n readonly detect: (\n url: string,\n ) => Effect.Effect<readonly IntegrationDetectionResult[], StorageFailure>;\n };\n\n readonly connections: {\n readonly create: (\n input: CreateConnectionInput,\n ) => Effect.Effect<\n Connection,\n | IntegrationNotFoundError\n | CredentialProviderNotRegisteredError\n | InvalidConnectionInputError\n | StorageFailure\n >;\n readonly list: (filter?: {\n readonly integration?: IntegrationSlug;\n readonly owner?: Owner;\n }) => Effect.Effect<readonly Connection[], StorageFailure>;\n readonly get: (ref: ConnectionRef) => Effect.Effect<Connection | null, StorageFailure>;\n /** Edit user-curated metadata (description, identityLabel). Credentials and\n * OAuth lifecycle fields are not editable here. */\n readonly update: (\n ref: ConnectionRef,\n input: UpdateConnectionInput,\n ) => Effect.Effect<Connection, ConnectionNotFoundError | StorageFailure>;\n readonly remove: (\n ref: ConnectionRef,\n ) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>;\n readonly refresh: (\n ref: ConnectionRef,\n ) => Effect.Effect<\n readonly Tool[],\n ConnectionNotFoundError | IntegrationNotFoundError | StorageFailure\n >;\n };\n\n /** Shared OAuth service. Hosts use this through the core HTTP OAuth group;\n * plugins see the same service as `ctx.oauth`. */\n readonly oauth: OAuthService;\n\n readonly tools: {\n readonly list: (filter?: ToolListFilter) => Effect.Effect<readonly Tool[], StorageFailure>;\n readonly schema: (address: ToolAddress) => Effect.Effect<ToolSchemaView | null, StorageFailure>;\n };\n\n readonly providers: {\n readonly list: () => Effect.Effect<readonly ProviderKey[]>;\n readonly items: (key: ProviderKey) => Effect.Effect<readonly ProviderEntry[], StorageFailure>;\n };\n\n readonly policies: {\n readonly list: () => Effect.Effect<readonly ToolPolicy[], StorageFailure>;\n readonly create: (input: CreateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;\n readonly update: (input: UpdateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;\n readonly remove: (input: RemoveToolPolicyInput) => Effect.Effect<void, StorageFailure>;\n readonly resolve: (address: ToolAddress) => Effect.Effect<EffectivePolicy, StorageFailure>;\n };\n\n readonly execute: (\n address: ToolAddress,\n args: unknown,\n options?: InvokeOptions,\n ) => Effect.Effect<unknown, ExecuteError>;\n\n readonly close: () => Effect.Effect<void, StorageFailure>;\n} & PluginExtensions<TPlugins>;\n\nexport interface ExecutorDb {\n readonly db: FumaDb<any>;\n readonly close?: () => Effect.Effect<void, StorageFailure> | Promise<void> | void;\n}\n\nexport type ExecutorDbInput = FumaDb<any> | ExecutorDb;\n\nexport type ExecutorDbFactory = (config: {\n readonly tables: FumaTables;\n}) => ExecutorDbInput | Effect.Effect<ExecutorDbInput, StorageFailure>;\n\nexport interface ExecutorConfig<TPlugins extends readonly AnyPlugin[] = readonly []> {\n /** The org / workspace this executor is bound to. `owner: \"org\"` rows file\n * here. */\n readonly tenant: Tenant;\n /** The acting member, or omit for a pure-org executor (no `owner:\"user\"`). */\n readonly subject?: Subject;\n readonly db?: ExecutorDbInput | ExecutorDbFactory;\n /**\n * Backend for the plugin blob seam (`StorageDeps.blobs`). Defaults to the\n * FumaDB `blob` table over `db`. Hosts with an object store hand one in\n * (e.g. the R2 store in `@executor-js/cloudflare/blob-store`) so multi-MB\n * values stay out of the relational tier.\n */\n readonly blobs?: BlobStore;\n readonly plugins?: TPlugins;\n /** Config-level credential providers, merged with every\n * `plugin.credentialProviders`. Config providers register first, so the\n * default (first writable) store is selected from them when present. */\n readonly providers?: readonly CredentialProvider[];\n /**\n * How to respond when a tool requests user input mid-invocation. Pass\n * `\"accept-all\"` for tests / non-interactive hosts, or a handler.\n */\n readonly onElicitation: OnElicitation;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n /**\n * Fetch API implementation for dependencies that cannot consume `httpClientLayer`.\n * Prefer `httpClientLayer` for normal SDK and plugin HTTP.\n */\n readonly fetch?: typeof globalThis.fetch;\n /**\n * The OAuth callback URL (`${webBaseUrl}/oauth/callback`) the host serves and\n * sends to providers. There is NO localhost default: omit it (or pass\n * undefined) only for executors that never run interactive OAuth — the\n * redirect-requiring flows then fail loudly instead of guessing a callback.\n * Hosts serving OAuth derive this from the request origin / web base URL.\n */\n readonly redirectUri?: string;\n /** Optional URL selected organization slug to carry inside OAuth `state`. */\n readonly oauthCallbackStateOrgSlug?: string;\n readonly oauthEndpointUrlPolicy?: OAuthEndpointUrlPolicy;\n /**\n * Enable the built-in `core-tools` plugin which contributes agent-facing\n * static tools over the v2 surface (integrations / connections / policies).\n */\n readonly coreTools?: {\n readonly webBaseUrl?: string;\n readonly orgSlug?: string;\n readonly includeProviders?: boolean;\n };\n}\n\n// ---------------------------------------------------------------------------\n// collectTables — return the executor-owned Fuma table set. Plugins persist\n// through host-owned facades (`pluginStorage`, `blobs`) instead of contributing\n// table definitions, so the schema is fixed and plugin-independent.\n// ---------------------------------------------------------------------------\n\nexport const collectTables = (): FumaTables => {\n validateExecutorOwnerPolicyTables(coreSchema);\n return { ...coreSchema };\n};\n\nconst validateExecutorOwnerPolicyTables = (tables: FumaTables): void => {\n for (const [tableKey, tableDef] of Object.entries(tables)) {\n assertExecutorOwnerPolicyTable(tableDef, tableKey);\n }\n};\n\nconst validateExecutorDbTables = (required: FumaTables, actual: FumaTables): void => {\n const missing = Object.keys(required)\n .filter((tableName) => !actual[tableName])\n .sort();\n if (missing.length === 0) return;\n\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: synchronous startup validation before Executor services are built\n throw new StorageError({\n message: `Executor database is missing required table definitions: ${missing.join(\", \")}`,\n cause: {\n missing,\n available: Object.keys(actual).sort(),\n },\n });\n};\n\nconst storageFailureFromUnknown = (message: string, cause: unknown): StorageFailure =>\n isStorageFailure(cause) ? cause : new StorageError({ message, cause });\n\nconst pluginStorageFailure = (pluginId: string, hook: string, cause: unknown): StorageFailure =>\n storageFailureFromUnknown(`${hook} failed for plugin ${pluginId}`, cause);\n\nconst createDefaultMemoryDb = (tables: FumaTables): ExecutorDb => {\n const version = \"1.0.0\";\n const latestSchema = fumaSchema<string, FumaTables, RelationsMap<FumaTables>>({\n version,\n tables,\n });\n const factory = fumadb({\n namespace: \"executor_memory\",\n schemas: [latestSchema],\n });\n\n // oxlint-disable-next-line executor/no-double-cast -- boundary: fumadb's generic ORM client type doesn't structurally match the FumaDb facade\n const db = factory.client(memoryAdapter()).orm(version) as unknown as FumaDb;\n return { db };\n};\n\n// ---------------------------------------------------------------------------\n// JSON helpers + row → public projection conversions\n// ---------------------------------------------------------------------------\n\nconst decodeJsonFromString = Schema.decodeUnknownOption(Schema.UnknownFromJsonString);\n\nconst decodeJsonColumn = (value: unknown): unknown => {\n if (value === null || value === undefined) return undefined;\n if (typeof value !== \"string\") return value;\n return decodeJsonFromString(value).pipe(Option.getOrElse(() => value));\n};\n\nconst rowToIntegration = (\n row: IntegrationRow,\n authMethods: readonly AuthMethodDescriptor[] = [],\n displayUrl?: string,\n): Integration => ({\n slug: IntegrationSlug.make(row.slug),\n // Pre-split rows have no `name`; their description WAS the display name.\n name: row.name ?? row.description ?? row.slug,\n // `description` is now nullable (cleared where it only held a duplicated\n // title); present it as \"\" so the public Integration type stays a string.\n description: row.description ?? \"\",\n kind: row.plugin_id,\n canRemove: Boolean(row.can_remove),\n canRefresh: Boolean(row.can_refresh),\n authMethods,\n ...(displayUrl ? { displayUrl } : {}),\n});\n\nconst rowToIntegrationRecord = (\n row: IntegrationRow,\n authMethods: readonly AuthMethodDescriptor[] = [],\n): IntegrationRecord => ({\n ...rowToIntegration(row, authMethods),\n config: decodeJsonColumn(row.config),\n});\n\nconst rowToConnection = (row: ConnectionRow): Connection => {\n const owner = row.owner as Owner;\n const integration = IntegrationSlug.make(row.integration);\n const name = ConnectionName.make(row.name);\n return {\n owner,\n name,\n integration,\n template: AuthTemplateSlug.make(row.template),\n provider: ProviderKey.make(row.provider),\n address: connectionAddress(owner, integration, name),\n identityLabel: row.identity_label ?? null,\n description: row.description ?? null,\n expiresAt: row.expires_at == null ? null : Number(row.expires_at),\n oauthClient: row.oauth_client == null ? null : OAuthClientSlug.make(String(row.oauth_client)),\n oauthClientOwner:\n row.oauth_client_owner == null ? null : (String(row.oauth_client_owner) as Owner),\n oauthScope: row.oauth_scope == null ? null : String(row.oauth_scope),\n };\n};\n\n/** The canonical credential variable for a single-secret connection. OAuth tokens\n * and the primary apiKey value resolve through it. */\nconst PRIMARY_INPUT_VARIABLE = \"token\";\n\ninterface NormalizedConnectionInput {\n readonly variable: string;\n readonly origin: ConnectionInputOrigin;\n}\n\n/** Flatten any `ConnectionValueInput` form (single `value`/`from` sugar, pasted\n * `values` map, or the canonical per-variable `inputs` map) into a uniform list\n * of named origins. */\nconst normalizeConnectionInputs = (\n input: ConnectionValueInput,\n): readonly NormalizedConnectionInput[] => {\n if (\"inputs\" in input) {\n return Object.entries(input.inputs).map(([variable, origin]) => ({ variable, origin }));\n }\n if (\"values\" in input) {\n return Object.entries(input.values).map(([variable, value]) => ({\n variable,\n origin: { value },\n }));\n }\n if (\"from\" in input) {\n return [{ variable: PRIMARY_INPUT_VARIABLE, origin: { from: input.from } }];\n }\n return [{ variable: PRIMARY_INPUT_VARIABLE, origin: { value: input.value } }];\n};\n\n/** Decode a connection row's `item_ids` JSON map (`variable → provider item id`).\n * Tolerates the historically-single shape by returning `{}` for anything that\n * isn't an object. */\nconst connectionItemIds = (row: ConnectionRow): Record<string, string> => {\n const decoded = decodeJsonColumn(row.item_ids);\n if (decoded == null || typeof decoded !== \"object\") return {};\n return decoded as Record<string, string>;\n};\n\n// Accepts a projected row (the invoke/list paths select away the heavy\n// schema columns); `Tool.inputSchema`/`outputSchema` are optional and stay\n// absent for those callers — `tools.schema` is the schema-bearing surface.\nconst rowToTool = (\n row: ToolInvocationRow & Partial<Pick<ToolRow, \"input_schema\" | \"output_schema\">>,\n annotations?: ToolAnnotations,\n): Tool => {\n const owner = row.owner as Owner;\n const integration = IntegrationSlug.make(row.integration);\n const connection = ConnectionName.make(row.connection);\n const name = ToolName.make(row.name);\n return {\n address: toolAddress(owner, integration, connection, name),\n owner,\n integration,\n connection,\n name,\n pluginId: row.plugin_id,\n description: row.description,\n inputSchema: decodeJsonColumn(row.input_schema),\n outputSchema: decodeJsonColumn(row.output_schema),\n annotations: annotations ?? (decodeJsonColumn(row.annotations) as ToolAnnotations | undefined),\n };\n};\n\n// ---------------------------------------------------------------------------\n// Condition builders\n// ---------------------------------------------------------------------------\n\ntype AnyCb = ConditionBuilder<Record<string, AnyColumn>>;\ntype CoreTableName = keyof CoreSchema & string;\ntype CoreRow<TName extends CoreTableName> = FumaRow<CoreSchema[TName]>;\ntype CoreColumn<TName extends CoreTableName> = keyof CoreRow<TName> & string;\ntype CoreWhere = (b: AnyCb) => Condition | boolean;\ntype CoreFindManyOptions<TName extends CoreTableName = CoreTableName> = {\n readonly where?: CoreWhere;\n readonly limit?: number;\n readonly offset?: number;\n readonly orderBy?:\n | readonly [string, \"asc\" | \"desc\"]\n | readonly (readonly [string, \"asc\" | \"desc\"])[];\n /** Column projection (fumadb `select`). Omit for all columns. Use on hot\n * paths whose rows carry heavy JSON columns the caller discards — e.g. a\n * tool row is ~KBs of schemas but invoke routing needs only the names. */\n readonly select?: readonly CoreColumn<TName>[];\n};\ntype CoreFindFirstOptions<TName extends CoreTableName = CoreTableName> = Omit<\n CoreFindManyOptions<TName>,\n \"limit\" | \"offset\"\n>;\n/** The narrowed row a projected query returns: the selected columns keep\n * their types, everything else is absent. */\ntype CoreProjectedRow<TName extends CoreTableName, TSelect> = TSelect extends readonly (infer K)[]\n ? Pick<CoreRow<TName>, Extract<K, keyof CoreRow<TName>>>\n : CoreRow<TName>;\n\ntype LooseStorageDb = {\n readonly count: (tableName: string, options?: unknown) => Promise<number>;\n readonly create: (\n tableName: string,\n row: Record<string, unknown>,\n ) => Promise<Record<string, unknown>>;\n readonly createMany: (\n tableName: string,\n rows: readonly Record<string, unknown>[],\n ) => Promise<readonly unknown[]>;\n readonly deleteMany: (tableName: string, options?: unknown) => Promise<void>;\n readonly findFirst: (\n tableName: string,\n options?: unknown,\n ) => Promise<Record<string, unknown> | null>;\n readonly findMany: (\n tableName: string,\n options?: unknown,\n ) => Promise<readonly Record<string, unknown>[]>;\n readonly updateMany: (tableName: string, options: unknown) => Promise<void>;\n};\n\nconst asLooseStorageDb = (db: unknown): LooseStorageDb => db as LooseStorageDb;\n\nconst makeCoreDb = (fuma: ReturnType<typeof makeFumaClient>) => ({\n count: <TName extends CoreTableName>(\n tableName: TName,\n options?: { readonly where?: CoreWhere },\n ): Effect.Effect<number, StorageFailure> =>\n fuma.use(`${tableName}.count`, (db) => asLooseStorageDb(db).count(tableName, options)),\n create: <TName extends CoreTableName>(\n tableName: TName,\n row: Record<string, unknown>,\n ): Effect.Effect<CoreRow<TName>, StorageFailure> =>\n fuma.use(`${tableName}.create`, (db) =>\n asLooseStorageDb(db).create(tableName, row),\n ) as Effect.Effect<CoreRow<TName>, StorageFailure>,\n createMany: <TName extends CoreTableName>(\n tableName: TName,\n rows: readonly Record<string, unknown>[],\n ): Effect.Effect<void, StorageFailure> =>\n rows.length === 0\n ? Effect.void\n : fuma\n .use(`${tableName}.createMany`, (db) => asLooseStorageDb(db).createMany(tableName, rows))\n .pipe(Effect.asVoid),\n deleteMany: <TName extends CoreTableName>(\n tableName: TName,\n options: { readonly where?: CoreWhere } = {},\n ): Effect.Effect<void, StorageFailure> =>\n fuma.use(`${tableName}.deleteMany`, (db) =>\n asLooseStorageDb(db).deleteMany(tableName, options),\n ),\n findFirst: <TName extends CoreTableName, const TOptions extends CoreFindFirstOptions<TName>>(\n tableName: TName,\n options: TOptions,\n ): Effect.Effect<CoreProjectedRow<TName, TOptions[\"select\"]> | null, StorageFailure> =>\n fuma.use(`${tableName}.findFirst`, (db) =>\n asLooseStorageDb(db).findFirst(tableName, options),\n ) as Effect.Effect<CoreProjectedRow<TName, TOptions[\"select\"]> | null, StorageFailure>,\n findMany: <TName extends CoreTableName, const TOptions extends CoreFindManyOptions<TName>>(\n tableName: TName,\n options: TOptions = {} as TOptions,\n ): Effect.Effect<readonly CoreProjectedRow<TName, TOptions[\"select\"]>[], StorageFailure> =>\n fuma.use(`${tableName}.findMany`, (db) =>\n asLooseStorageDb(db).findMany(tableName, options),\n ) as Effect.Effect<readonly CoreProjectedRow<TName, TOptions[\"select\"]>[], StorageFailure>,\n updateMany: <TName extends CoreTableName>(\n tableName: TName,\n options: {\n readonly where?: CoreWhere;\n readonly set: Record<string, unknown>;\n },\n ): Effect.Effect<void, StorageFailure> =>\n fuma.use(`${tableName}.updateMany`, (db) =>\n asLooseStorageDb(db).updateMany(tableName, options),\n ),\n});\n\ntype CoreDb = ReturnType<typeof makeCoreDb>;\n\n// ---------------------------------------------------------------------------\n// Plugin storage facade — owner-scoped (was scope-keyed). Reads fall through\n// [user, org]; writes/deletes name an explicit owner.\n// ---------------------------------------------------------------------------\n\nconst pluginStorageEntryFromRow = <T>(row: CoreRow<\"plugin_storage\">): PluginStorageEntry<T> => ({\n id: pluginStorageId({\n pluginId: row.plugin_id,\n collection: row.collection,\n key: row.key,\n }),\n owner: row.owner as Owner,\n pluginId: row.plugin_id,\n collection: row.collection,\n key: row.key,\n data: row.data as T,\n createdAt: row.created_at instanceof Date ? row.created_at : new Date(row.created_at),\n updatedAt: row.updated_at instanceof Date ? row.updated_at : new Date(row.updated_at),\n});\n\nconst pluginStorageIndexSpecFields = (spec: PluginStorageRuntimeIndexSpec): readonly string[] =>\n typeof spec === \"string\" ? [spec] : spec;\n\nconst pluginStorageCollectionIndexedFields = (\n definition: PluginStorageRuntimeCollectionDefinition,\n): ReadonlySet<string> =>\n new Set(definition.indexes.flatMap((spec) => pluginStorageIndexSpecFields(spec)));\n\nconst pluginStorageQueryValidationError = (\n definition: PluginStorageRuntimeCollectionDefinition,\n query: PluginStorageCollectionQueryInput<PluginStorageCollectionDefinition> | undefined,\n): StorageError | null => {\n if (!query) return null;\n const indexedFields = pluginStorageCollectionIndexedFields(definition);\n const fields = new Set<string>([\n ...Object.keys(query.where ?? {}),\n ...(query.orderBy ?? []).map((order) => order.field),\n ]);\n for (const field of fields) {\n if (!indexedFields.has(field)) {\n return new StorageError({\n message: `Plugin storage collection \"${definition.name}\" cannot query field \"${field}\" because it is not declared as an index`,\n cause: undefined,\n });\n }\n }\n if (query.limit !== undefined && (!Number.isInteger(query.limit) || query.limit < 0)) {\n return new StorageError({\n message: `Plugin storage collection \"${definition.name}\" received an invalid query limit`,\n cause: undefined,\n });\n }\n if (query.offset !== undefined && (!Number.isInteger(query.offset) || query.offset < 0)) {\n return new StorageError({\n message: `Plugin storage collection \"${definition.name}\" received an invalid query offset`,\n cause: undefined,\n });\n }\n return null;\n};\n\nconst isPluginStorageRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst pluginStorageWhereOperators = [\"eq\", \"in\", \"gt\", \"gte\", \"lt\", \"lte\"] as const;\n\nconst isPluginStorageWhereFilter = (value: unknown): value is Readonly<Record<string, unknown>> =>\n isPluginStorageRecord(value) && pluginStorageWhereOperators.some((operator) => operator in value);\n\nconst pluginStorageComparableValue = (value: unknown): string | number | boolean | null => {\n if (value instanceof Date) return value.getTime();\n if (typeof value === \"number\" || typeof value === \"string\" || typeof value === \"boolean\") {\n return value;\n }\n if (value == null) return null;\n return JSON.stringify(value);\n};\n\nconst comparePluginStorageValues = (left: unknown, right: unknown): number => {\n const leftValue = pluginStorageComparableValue(left);\n const rightValue = pluginStorageComparableValue(right);\n if (leftValue === rightValue) return 0;\n if (leftValue === null) return -1;\n if (rightValue === null) return 1;\n return leftValue < rightValue ? -1 : 1;\n};\n\nconst pluginStorageDataField = (data: unknown, field: string): unknown =>\n isPluginStorageRecord(data) ? data[field] : undefined;\n\nconst matchesWhereOperator = (operator: string, value: unknown, operand: unknown): boolean => {\n if (operator === \"eq\") return comparePluginStorageValues(value, operand) === 0;\n if (operator === \"in\") {\n return (\n Array.isArray(operand) &&\n operand.some((item) => comparePluginStorageValues(value, item) === 0)\n );\n }\n if (operator === \"gt\") return comparePluginStorageValues(value, operand) > 0;\n if (operator === \"gte\") return comparePluginStorageValues(value, operand) >= 0;\n if (operator === \"lt\") return comparePluginStorageValues(value, operand) < 0;\n if (operator === \"lte\") return comparePluginStorageValues(value, operand) <= 0;\n return false;\n};\n\nconst matchesWhereOperators = (\n value: unknown,\n filter: Readonly<Record<string, unknown>>,\n): boolean => {\n for (const [operator, operand] of Object.entries(filter)) {\n if (!matchesWhereOperator(operator, value, operand)) return false;\n }\n return true;\n};\n\nconst rowMatchesPluginStorageWhere = (\n row: CoreRow<\"plugin_storage\">,\n where: Readonly<Record<string, unknown>> | undefined,\n): boolean => {\n if (!where) return true;\n for (const [field, condition] of Object.entries(where)) {\n const value = pluginStorageDataField(row.data, field);\n if (isPluginStorageWhereFilter(condition)) {\n if (!matchesWhereOperators(value, condition)) return false;\n } else if (comparePluginStorageValues(value, condition) !== 0) {\n return false;\n }\n }\n return true;\n};\n\nconst makePluginStorageFacade = (input: {\n readonly core: CoreDb;\n readonly pluginId: string;\n readonly owner: OwnerBinding;\n}): PluginStorageFacade => {\n // Owner partitions: org always, plus this subject's user partition.\n const readOwners: readonly Owner[] = input.owner.subject == null ? [\"org\"] : [\"user\", \"org\"];\n\n const ownerSubject = (owner: Owner): { owner: Owner; subject: string } | null => {\n if (owner === \"org\") return { owner: \"org\", subject: ORG_SUBJECT };\n if (input.owner.subject == null) return null;\n return { owner: \"user\", subject: String(input.owner.subject) };\n };\n\n const tenant = String(input.owner.tenant);\n\n const whereFor =\n (collection: string, key?: string): CoreWhere =>\n (b: AnyCb) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"collection\", \"=\", collection),\n key === undefined ? true : b(\"key\", \"=\", key),\n );\n\n const whereOwner = (owner: Owner, collection: string, key: string): CoreWhere => {\n const os = ownerSubject(owner);\n return (b: AnyCb) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"collection\", \"=\", collection),\n b(\"key\", \"=\", key),\n b(\"owner\", \"=\", owner),\n b(\"subject\", \"=\", os ? os.subject : ORG_SUBJECT),\n );\n };\n\n const ownerRank = (owner: Owner): number => readOwners.indexOf(owner);\n\n const sortByOwnerPrecedence = (rows: readonly CoreRow<\"plugin_storage\">[]) =>\n [...rows].sort((left, right) => {\n const l = ownerRank(left.owner as Owner);\n const r = ownerRank(right.owner as Owner);\n return l - r || left.key.localeCompare(right.key);\n });\n\n const getVisible = <T>(collection: string, key: string) =>\n input.core.findMany(\"plugin_storage\", { where: whereFor(collection, key) }).pipe(\n Effect.map((rows) => sortByOwnerPrecedence(rows)[0] ?? null),\n Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null)),\n );\n\n const getForOwnerImpl = <T>(owner: Owner, collection: string, key: string) =>\n input.core\n .findFirst(\"plugin_storage\", {\n where: whereOwner(owner, collection, key),\n })\n .pipe(Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null)));\n\n const putImpl = <T>(owner: Owner, collection: string, key: string, data: unknown) =>\n Effect.gen(function* () {\n const os = ownerSubject(owner);\n if (!os) {\n return yield* new StorageError({\n message: `Cannot write plugin storage for owner \"user\": executor has no subject.`,\n cause: undefined,\n });\n }\n const existing = yield* input.core.findFirst(\"plugin_storage\", {\n where: whereOwner(owner, collection, key),\n });\n const now = new Date();\n if (existing) {\n yield* input.core.updateMany(\"plugin_storage\", {\n where: whereOwner(owner, collection, key),\n set: { data, updated_at: now },\n });\n return pluginStorageEntryFromRow<T>({\n ...existing,\n data,\n updated_at: now,\n });\n }\n const created = yield* input.core.create(\"plugin_storage\", {\n tenant,\n owner: os.owner,\n subject: os.subject,\n plugin_id: input.pluginId,\n collection,\n key,\n data,\n created_at: now,\n updated_at: now,\n });\n return pluginStorageEntryFromRow<T>(created);\n });\n\n const removeImpl = (owner: Owner, collection: string, key: string) =>\n Effect.gen(function* () {\n const os = ownerSubject(owner);\n if (!os) {\n return yield* new StorageError({\n message: `Cannot delete plugin storage for owner \"user\": executor has no subject.`,\n cause: undefined,\n });\n }\n yield* input.core.deleteMany(\"plugin_storage\", {\n where: whereOwner(owner, collection, key),\n });\n });\n\n const keysByCollection = (\n entries: readonly { readonly collection: string; readonly key: string }[],\n ) => {\n const grouped = new Map<string, Set<string>>();\n for (const entry of entries) {\n const keys = grouped.get(entry.collection);\n if (keys) {\n keys.add(entry.key);\n } else {\n grouped.set(entry.collection, new Set([entry.key]));\n }\n }\n return grouped;\n };\n\n const deleteManyImpl = (\n owner: Owner,\n subject: string,\n entries: readonly { readonly collection: string; readonly key: string }[],\n ) =>\n Effect.gen(function* () {\n for (const [collection, keys] of keysByCollection(entries)) {\n const uniqueKeys = [...keys];\n for (\n let offset = 0;\n offset < uniqueKeys.length;\n offset += PLUGIN_STORAGE_DELETE_KEY_BATCH_SIZE\n ) {\n const batchKeys = uniqueKeys.slice(offset, offset + PLUGIN_STORAGE_DELETE_KEY_BATCH_SIZE);\n yield* input.core.deleteMany(\"plugin_storage\", {\n where: (b) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"collection\", \"=\", collection),\n b(\"key\", \"in\", batchKeys),\n b(\"owner\", \"=\", owner),\n b(\"subject\", \"=\", subject),\n ),\n });\n }\n }\n });\n\n const putManyImpl = (\n owner: Owner,\n entries: readonly {\n readonly collection: string;\n readonly key: string;\n readonly data: unknown;\n }[],\n ) =>\n Effect.gen(function* () {\n const os = ownerSubject(owner);\n if (!os) {\n return yield* new StorageError({\n message: `Cannot write plugin storage for owner \"user\": executor has no subject.`,\n cause: undefined,\n });\n }\n const entriesById = new Map(\n entries.map((entry) => [\n pluginStorageId({\n pluginId: input.pluginId,\n collection: entry.collection,\n key: entry.key,\n }),\n entry,\n ]),\n );\n const uniqueEntries = [...entriesById.values()];\n if (uniqueEntries.length === 0) return;\n\n yield* deleteManyImpl(owner, os.subject, uniqueEntries);\n\n const now = new Date();\n for (\n let offset = 0;\n offset < uniqueEntries.length;\n offset += PLUGIN_STORAGE_CREATE_ROW_BATCH_SIZE\n ) {\n const batchEntries = uniqueEntries.slice(\n offset,\n offset + PLUGIN_STORAGE_CREATE_ROW_BATCH_SIZE,\n );\n yield* input.core.createMany(\n \"plugin_storage\",\n batchEntries.map((entry) => ({\n tenant,\n owner: os.owner,\n subject: os.subject,\n plugin_id: input.pluginId,\n collection: entry.collection,\n key: entry.key,\n data: entry.data,\n created_at: now,\n updated_at: now,\n })),\n );\n }\n });\n\n const removeManyImpl = (\n owner: Owner,\n entries: readonly { readonly collection: string; readonly key: string }[],\n ) =>\n Effect.gen(function* () {\n const os = ownerSubject(owner);\n if (!os) {\n return yield* new StorageError({\n message: `Cannot delete plugin storage for owner \"user\": executor has no subject.`,\n cause: undefined,\n });\n }\n yield* deleteManyImpl(owner, os.subject, entries);\n });\n\n const queryCollection = <TDefinition extends PluginStorageCollectionDefinition>(\n definition: TDefinition,\n queryInput?: PluginStorageCollectionQueryInput<TDefinition>,\n ) =>\n Effect.gen(function* () {\n const validationError = pluginStorageQueryValidationError(\n definition,\n queryInput as\n | PluginStorageCollectionQueryInput<PluginStorageCollectionDefinition>\n | undefined,\n );\n if (validationError) return yield* validationError;\n\n const rows = yield* input.core.findMany(\"plugin_storage\", {\n where: whereFor(definition.name),\n });\n const filtered = sortByOwnerPrecedence(rows)\n .filter((row) =>\n queryInput?.keyPrefix === undefined ? true : row.key.startsWith(queryInput.keyPrefix),\n )\n .filter((row) =>\n rowMatchesPluginStorageWhere(\n row,\n queryInput?.where as Readonly<Record<string, unknown>> | undefined,\n ),\n );\n\n const sorted =\n queryInput?.orderBy && queryInput.orderBy.length > 0\n ? [...filtered].sort((left, right) => {\n for (const order of queryInput.orderBy ?? []) {\n const direction = order.direction === \"desc\" ? -1 : 1;\n const compared =\n comparePluginStorageValues(\n pluginStorageDataField(left.data, order.field),\n pluginStorageDataField(right.data, order.field),\n ) * direction;\n if (compared !== 0) return compared;\n }\n return (\n ownerRank(left.owner as Owner) - ownerRank(right.owner as Owner) ||\n left.key.localeCompare(right.key)\n );\n })\n : filtered;\n\n const offset = queryInput?.offset ?? 0;\n const limited =\n queryInput?.limit === undefined\n ? sorted.slice(offset)\n : sorted.slice(offset, offset + queryInput.limit);\n return limited.map((row) =>\n pluginStorageEntryFromRow<PluginStorageCollectionData<TDefinition>>(row),\n );\n });\n\n return {\n collection: (definition) => ({\n get: (storageInput) =>\n getVisible(definition.name, storageInput.key) as Effect.Effect<\n PluginStorageEntry<PluginStorageCollectionData<typeof definition>> | null,\n StorageFailure\n >,\n getForOwner: (storageInput) =>\n getForOwnerImpl(storageInput.owner, definition.name, storageInput.key) as Effect.Effect<\n PluginStorageEntry<PluginStorageCollectionData<typeof definition>> | null,\n StorageFailure\n >,\n list: (storageInput) => queryCollection(definition, { keyPrefix: storageInput?.keyPrefix }),\n put: (storageInput) =>\n putImpl(\n storageInput.owner,\n definition.name,\n storageInput.key,\n storageInput.data,\n ) as Effect.Effect<\n PluginStorageEntry<PluginStorageCollectionData<typeof definition>>,\n StorageFailure\n >,\n query: (storageInput) => queryCollection(definition, storageInput),\n count: (storageInput) =>\n queryCollection(definition, storageInput).pipe(Effect.map((rows) => rows.length)),\n remove: (storageInput) => removeImpl(storageInput.owner, definition.name, storageInput.key),\n }),\n get: (storageInput) => getVisible(storageInput.collection, storageInput.key),\n getForOwner: (storageInput) =>\n getForOwnerImpl(storageInput.owner, storageInput.collection, storageInput.key),\n list: (storageInput) =>\n Effect.gen(function* () {\n const rows = yield* input.core.findMany(\"plugin_storage\", {\n where: whereFor(storageInput.collection),\n });\n return sortByOwnerPrecedence(rows)\n .filter((row) =>\n storageInput.keyPrefix === undefined\n ? true\n : row.key.startsWith(storageInput.keyPrefix),\n )\n .map((row) => pluginStorageEntryFromRow(row));\n }),\n put: (storageInput) =>\n putImpl(storageInput.owner, storageInput.collection, storageInput.key, storageInput.data),\n putMany: (storageInput) => putManyImpl(storageInput.owner, storageInput.entries),\n remove: (storageInput) =>\n removeImpl(storageInput.owner, storageInput.collection, storageInput.key),\n removeMany: (storageInput) => removeManyImpl(storageInput.owner, storageInput.entries),\n };\n};\n\n// ---------------------------------------------------------------------------\n// Approval argument preview\n// ---------------------------------------------------------------------------\n\nconst approvalArgumentPreview = (args: unknown): string => {\n const text = JSON.stringify(args ?? {}, null, 2) ?? \"null\";\n return text.length > MAX_APPROVAL_ARGUMENT_PREVIEW_CHARS\n ? `${text.slice(0, MAX_APPROVAL_ARGUMENT_PREVIEW_CHARS)}...`\n : text;\n};\n\n// ---------------------------------------------------------------------------\n// createExecutor\n// ---------------------------------------------------------------------------\n\ninterface StaticTools {\n readonly source: StaticSourceDecl;\n readonly tool: StaticToolDecl;\n readonly pluginId: string;\n readonly ctx: PluginCtx<unknown>;\n}\n\ninterface PluginRuntime {\n readonly plugin: AnyPlugin;\n readonly storage: unknown;\n readonly ctx: PluginCtx<unknown>;\n}\n\nconst EXECUTOR_SOURCE_ID = \"executor\";\nconst EXECUTOR_SOURCE: StaticSourceDecl = {\n id: EXECUTOR_SOURCE_ID,\n kind: \"built-in\",\n name: \"Executor\",\n canRemove: false,\n canRefresh: false,\n canEdit: false,\n tools: [],\n};\n\nconst isReadonlyRecord = (value: unknown): value is Readonly<Record<PropertyKey, unknown>> =>\n typeof value === \"object\" && value !== null;\n\ntype StandardJsonSchemaSide = \"input\" | \"output\";\ntype StandardJsonSchemaFns = {\n readonly input?: (options: { readonly target: \"draft-07\" }) => unknown;\n readonly output?: (options: { readonly target: \"draft-07\" }) => unknown;\n};\n\nconst staticToolSchemaRoot = (\n schema: StaticToolDecl[\"inputSchema\"] | StaticToolDecl[\"outputSchema\"],\n side: StandardJsonSchemaSide,\n): unknown | undefined => {\n if (!schema) return undefined;\n const standard = isReadonlyRecord(schema) ? schema[\"~standard\"] : undefined;\n if (!isReadonlyRecord(standard)) return schema;\n const jsonSchema = standard[\"jsonSchema\"];\n if (!isReadonlyRecord(jsonSchema)) return schema;\n const materialize = (jsonSchema as StandardJsonSchemaFns)[side];\n return typeof materialize === \"function\" ? materialize({ target: \"draft-07\" }) : jsonSchema;\n};\n\nexport const createExecutor = <const TPlugins extends readonly AnyPlugin[] = readonly []>(\n config: ExecutorConfig<TPlugins>,\n): Effect.Effect<Executor<TPlugins>, StorageFailure> =>\n Effect.gen(function* () {\n const defaultPlugins = (): TPlugins => {\n const empty: readonly AnyPlugin[] = [];\n return empty as TPlugins;\n };\n const { plugins: userPlugins = defaultPlugins() } = config;\n\n const tenant = String(config.tenant);\n const subject = config.subject != null ? String(config.subject) : null;\n\n const ownerBinding: OwnerBinding = {\n tenant: config.tenant,\n subject: config.subject ?? null,\n };\n\n const ownedKeys = (owner: Owner): OwnedKeys => {\n if (owner === \"org\") return { tenant, owner, subject: ORG_SUBJECT };\n if (subject == null) {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: programmer error caught and surfaced as StorageError below by callers\n throw new StorageError({\n message: `Cannot target owner \"user\": executor has no subject.`,\n cause: undefined,\n });\n }\n return { tenant, owner, subject };\n };\n\n const requireUserSubject = (owner: Owner): Effect.Effect<void, StorageFailure> =>\n owner === \"user\" && subject == null\n ? Effect.fail(\n new StorageError({\n message: `Cannot target owner \"user\": executor has no subject.`,\n cause: undefined,\n }),\n )\n : Effect.void;\n\n // Built-in core-tools plugin: agent-facing static tools over the v2 surface.\n const plugins: readonly AnyPlugin[] = config.coreTools\n ? ([\n coreToolsPlugin({\n webBaseUrl: config.coreTools.webBaseUrl,\n orgSlug: config.coreTools.orgSlug,\n includeProviders: config.coreTools.includeProviders,\n }),\n ...userPlugins,\n ] as readonly AnyPlugin[])\n : (userPlugins as readonly AnyPlugin[]);\n\n const tables = yield* Effect.try({\n try: () => collectTables(),\n catch: (cause) => storageFailureFromUnknown(\"Failed to collect executor tables\", cause),\n });\n const dbInput = yield* Effect.suspend(() => {\n if (!config.db) return Effect.succeed(createDefaultMemoryDb(tables));\n if (typeof config.db !== \"function\") return Effect.succeed(config.db);\n const out = config.db({ tables });\n return Effect.isEffect(out) ? out : Effect.succeed(out);\n });\n const rootDbUntyped = \"db\" in dbInput ? dbInput.db : dbInput;\n const closeDb = \"db\" in dbInput ? dbInput.close : undefined;\n yield* Effect.try({\n try: () => {\n validateExecutorDbTables(tables, rootDbUntyped.internal.tables);\n validateExecutorOwnerPolicyTables(rootDbUntyped.internal.tables);\n },\n catch: (cause) => storageFailureFromUnknown(\"Failed to validate executor tables\", cause),\n });\n\n const ownerContext: ExecutorOwnerPolicyContext = { tenant, subject };\n const rootDb = withQueryContext(rootDbUntyped, ownerContext);\n const fuma = makeFumaClient(rootDb);\n const core = makeCoreDb(fuma);\n const blobs = config.blobs ?? makeFumaBlobStore(fuma);\n const transaction = <A, E>(effect: Effect.Effect<A, E>) => fuma.transaction(effect);\n\n // Populated once, never mutated after startup.\n const staticTools = new Map<string, StaticTools>();\n const runtimes = new Map<string, PluginRuntime>();\n let activeToolPolicyProvider: ToolPolicyProvider | null = null;\n // Credential providers keyed by `provider.key`, in registration order.\n const credentialProviders = new Map<string, CredentialProvider>();\n const credentialProviderOrder: string[] = [];\n\n const staticToolOwner = (): Owner => (subject == null ? \"org\" : \"user\");\n const staticToolConnection = (source: StaticSourceDecl): ConnectionName =>\n ConnectionName.make(source.id === EXECUTOR_SOURCE_ID ? \"coreTools\" : \"static\");\n\n const staticSources = (): readonly StaticSourceDecl[] => {\n const byId = new Map<string, StaticSourceDecl>();\n for (const entry of staticTools.values()) {\n if (!byId.has(entry.source.id)) byId.set(entry.source.id, entry.source);\n }\n return [...byId.values()];\n };\n\n const staticSourceToIntegration = (source: StaticSourceDecl): Integration => ({\n slug: IntegrationSlug.make(source.id),\n name: source.name,\n description: source.name,\n kind: source.kind,\n canRemove: source.canRemove ?? false,\n canRefresh: source.canRefresh ?? false,\n authMethods: [],\n });\n\n const staticToolToTool = (entry: StaticTools): Tool => ({\n address: ToolAddress.make(`${entry.source.id}.${entry.tool.name}`),\n owner: staticToolOwner(),\n integration: IntegrationSlug.make(entry.source.id),\n connection: staticToolConnection(entry.source),\n name: ToolName.make(entry.tool.name),\n pluginId: entry.pluginId,\n description: entry.tool.description,\n inputSchema: staticToolSchemaRoot(entry.tool.inputSchema, \"input\"),\n outputSchema: staticToolSchemaRoot(entry.tool.outputSchema, \"output\"),\n annotations: entry.tool.annotations,\n static: true,\n });\n\n const registerCredentialProvider = (\n provider: CredentialProvider,\n sourceLabel: string,\n ): Effect.Effect<void, StorageFailure> => {\n const key = String(provider.key);\n if (credentialProviders.has(key)) {\n return Effect.fail(\n new StorageError({\n message: `Duplicate credential provider key: ${key} (from ${sourceLabel})`,\n cause: undefined,\n }),\n );\n }\n credentialProviders.set(key, provider);\n credentialProviderOrder.push(key);\n return Effect.void;\n };\n\n // Config-level providers register first so the default store prefers them.\n for (const provider of config.providers ?? []) {\n yield* registerCredentialProvider(provider, \"config\");\n }\n\n const defaultWritableProvider = (): CredentialProvider | null => {\n for (const key of credentialProviderOrder) {\n const provider = credentialProviders.get(key);\n if (provider?.writable) return provider;\n }\n return null;\n };\n\n const extensions: Record<string, object> = {};\n\n // ------------------------------------------------------------------\n // Owner condition builders. The owner policy already restricts reads to\n // (tenant, org|this-subject); `byOwner` narrows to one explicit owner.\n // ------------------------------------------------------------------\n\n const byOwner =\n (owner: Owner): CoreWhere =>\n (b: AnyCb) => {\n const keys = owner === \"org\" ? ORG_SUBJECT : (subject ?? \"__none__\");\n return b.and(b(\"owner\", \"=\", owner), b(\"subject\", \"=\", keys));\n };\n\n // ------------------------------------------------------------------\n // Credential resolution\n // ------------------------------------------------------------------\n\n const findConnectionRow = (\n ref: ConnectionRef,\n ): Effect.Effect<ConnectionRow | null, StorageFailure> =>\n core.findFirst(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(ref.owner)(b),\n b(\"integration\", \"=\", String(ref.integration)),\n b(\"name\", \"=\", String(ref.name)),\n ),\n });\n\n // In-flight refresh gate — concurrent resolves of the same connection share\n // one refresh (mirrors v1's refresh deferred-map) so we never fire two\n // refresh-token grants for the same connection in parallel (the AS rotates\n // the refresh token; the second request would race on a consumed token).\n const refreshInFlight = new Map<\n string,\n Effect.Effect<string | null, StorageFailure | CredentialResolutionError>\n >();\n\n const connectionKey = (row: ConnectionRow): string =>\n `${row.owner}:${row.subject}:${row.integration}:${row.name}`;\n\n const loadOAuthClientRow = (\n owner: Owner,\n slug: string,\n ): Effect.Effect<OAuthClientRow | null, StorageFailure> =>\n core.findFirst(\"oauth_client\", {\n where: (b: AnyCb) => b.and(byOwner(owner)(b), b(\"slug\", \"=\", slug)),\n });\n\n // Perform the actual refresh-token grant and persist the rotated material.\n const performTokenRefresh = (\n row: ConnectionRow,\n provider: CredentialProvider,\n ): Effect.Effect<string | null, StorageFailure | CredentialResolutionError> =>\n Effect.gen(function* () {\n const owner = row.owner as Owner;\n const reauth = (message: string): CredentialResolutionError =>\n new CredentialResolutionError({\n owner,\n integration: IntegrationSlug.make(row.integration),\n name: ConnectionName.make(row.name),\n message,\n reauthRequired: true,\n });\n\n // Load the backing app by the owner STORED on the connection (a Personal\n // connection may be backed by a shared Workspace app) — no derivation.\n const clientOwner = (row.oauth_client_owner ?? row.owner) as Owner;\n const clientRow = yield* loadOAuthClientRow(clientOwner, String(row.oauth_client));\n if (!clientRow) {\n return yield* reauth(`OAuth client \"${row.oauth_client}\" is no longer registered.`);\n }\n\n // The secret is stored in the provider (a vault item id), not inline.\n const clientSecret = clientRow.client_secret_item_id\n ? ((yield* provider.get(ProviderItemId.make(String(clientRow.client_secret_item_id)))) ??\n \"\")\n : \"\";\n // Re-request the scopes this connection was GRANTED (RFC 6749 §6: a\n // refresh must not exceed the originally-granted scope). Empty → omit\n // the param, which the AS treats as \"same scopes as granted\".\n const grantedScopes = row.oauth_scope\n ? String(row.oauth_scope).split(/\\s+/).filter(Boolean)\n : [];\n\n // Refresh against the region the code was redeemed at when one was\n // recorded at connect time (multi-site providers like Datadog), else\n // the oauth_client's configured token endpoint.\n const tokenUrl = row.oauth_token_url\n ? String(row.oauth_token_url)\n : String(clientRow.token_url);\n\n // client_credentials (machine-to-machine) has NO refresh token — the\n // token is RE-MINTED from the client id/secret. The authorization_code\n // path below needs a stored refresh token. Branching on grant here is\n // what keeps a client_credentials connection (e.g. DealCloud) from\n // demanding a re-auth on a credential that has no human to re-auth.\n const token =\n String(clientRow.grant) === \"client_credentials\"\n ? yield* exchangeClientCredentials({\n tokenUrl,\n clientId: String(clientRow.client_id),\n clientSecret,\n scopes: grantedScopes,\n resource: clientRow.resource ? String(clientRow.resource) : undefined,\n endpointUrlPolicy: config.oauthEndpointUrlPolicy,\n fetch: config.fetch,\n }).pipe(\n // A client_credentials failure is never a rotated-refresh-token\n // problem, so do NOT map invalid_grant → reauth. Surface as a\n // StorageError; the in-flight gate clears on settle, so the next\n // invoke retries (handles transient AS/network blips).\n Effect.mapError(\n (cause) =>\n new StorageError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuth2Error carries a typed `message`\n message: `Client-credentials token request failed: ${cause.message}`,\n cause,\n }),\n ),\n )\n : yield* Effect.gen(function* () {\n if (!row.refresh_item_id) {\n return yield* reauth(\"No refresh token is stored for this connection.\");\n }\n const refreshToken = yield* provider.get(ProviderItemId.make(row.refresh_item_id));\n if (!refreshToken) {\n return yield* reauth(\"Stored refresh token could not be resolved.\");\n }\n return yield* refreshAccessToken({\n tokenUrl,\n clientId: String(clientRow.client_id),\n clientSecret,\n refreshToken,\n scopes: grantedScopes,\n // RFC 8707: keep the re-minted token bound to the same resource\n // (MCP servers require this on refresh).\n resource: clientRow.resource ? String(clientRow.resource) : undefined,\n endpointUrlPolicy: config.oauthEndpointUrlPolicy,\n fetch: config.fetch,\n }).pipe(\n Effect.mapError((cause) =>\n cause.error === \"invalid_grant\"\n ? reauth(\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuth2Error carries a typed `message`\n `OAuth token refresh was rejected (invalid_grant): ${cause.message}`,\n )\n : new StorageError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuth2Error carries a typed `message`\n message: `OAuth token refresh failed: ${cause.message}`,\n cause,\n }),\n ),\n );\n });\n\n if (provider.set) {\n // OAuth is always single-input: the access token lives in the `token`\n // item. Fall back to a deterministic id if the map is somehow empty.\n const tokenItemId =\n connectionItemIds(row)[PRIMARY_INPUT_VARIABLE] ??\n `connection:${row.owner}:${row.integration}:${row.name}:${PRIMARY_INPUT_VARIABLE}`;\n yield* provider.set(ProviderItemId.make(tokenItemId), token.access_token);\n if (token.refresh_token && row.refresh_item_id) {\n yield* provider.set(ProviderItemId.make(row.refresh_item_id), token.refresh_token);\n }\n }\n\n const nextExpiresAt =\n typeof token.expires_in === \"number\" ? Date.now() + token.expires_in * 1000 : null;\n const set: Record<string, unknown> = {\n expires_at: nextExpiresAt,\n updated_at: new Date(),\n };\n if (token.scope !== undefined) set.oauth_scope = token.scope;\n yield* core.updateMany(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(owner)(b),\n b(\"integration\", \"=\", String(row.integration)),\n b(\"name\", \"=\", String(row.name)),\n ),\n set,\n });\n\n return token.access_token;\n });\n\n const refreshConnectionToken = (\n row: ConnectionRow,\n provider: CredentialProvider,\n ): Effect.Effect<string | null, StorageFailure | CredentialResolutionError> =>\n // Share a single refresh per connection so concurrent resolves of the same\n // connection all await one refresh-token grant (the AS rotates the refresh\n // token; parallel grants would race on a consumed token — v1's refresh\n // deferred-map). The gate is cleared once the refresh settles so a later\n // expiry can refresh again.\n Effect.gen(function* () {\n const key = connectionKey(row);\n const existing = refreshInFlight.get(key);\n if (existing) return yield* existing;\n // `Effect.cached` memoizes the grant onto a deferred: it runs once and\n // replays to every awaiter sharing this entry.\n const memoized = yield* Effect.cached(performTokenRefresh(row, provider));\n const gated = memoized.pipe(\n Effect.ensuring(Effect.sync(() => refreshInFlight.delete(key))),\n );\n // Re-check after building (a peer fiber may have registered first while\n // we built ours) so everyone converges on the same shared grant.\n const winner = refreshInFlight.get(key) ?? gated;\n if (winner === gated) refreshInFlight.set(key, gated);\n return yield* winner;\n });\n\n // Resolve every named input of a connection (`variable → value`). A\n // single-secret connection yields `{ token: <value> }`; an apiKey method with\n // two distinct inputs yields one entry per variable. OAuth connections refresh\n // first (always single-input → `{ token: <access> }`).\n const resolveConnectionValues = (\n row: ConnectionRow,\n ): Effect.Effect<Record<string, string | null>, StorageFailure | CredentialResolutionError> =>\n Effect.gen(function* () {\n const provider = credentialProviders.get(row.provider);\n if (!provider) {\n return yield* new CredentialProviderNotRegisteredError({\n provider: ProviderKey.make(row.provider),\n });\n }\n // OAuth connections refresh their access token before resolving when\n // it has expired (or is within the skew window).\n const expiresAt = row.expires_at == null ? null : Number(row.expires_at);\n if (row.oauth_client != null && shouldRefreshToken({ expiresAt })) {\n const access = yield* refreshConnectionToken(row, provider);\n return { [PRIMARY_INPUT_VARIABLE]: access };\n }\n const out: Record<string, string | null> = {};\n for (const [variable, itemId] of Object.entries(connectionItemIds(row))) {\n out[variable] = yield* provider.get(ProviderItemId.make(itemId));\n }\n return out;\n }).pipe(\n // CredentialProviderNotRegisteredError is part of CredentialResolution\n // for ctx.connections.resolveValue's StorageFailure channel — fold it.\n Effect.catchTag(\"CredentialProviderNotRegisteredError\", (err) =>\n Effect.fail(\n new StorageError({\n message: `Credential provider \"${err.provider}\" is not registered.`,\n cause: err,\n }),\n ),\n ),\n );\n\n /** The primary (`token`) value — the public seam for OAuth + single-input\n * callers that only ever need one value. */\n const resolveConnectionValue = (\n row: ConnectionRow,\n ): Effect.Effect<string | null, StorageFailure | CredentialResolutionError> =>\n resolveConnectionValues(row).pipe(\n Effect.map((values) => values[PRIMARY_INPUT_VARIABLE] ?? null),\n );\n\n // The plugin-facing contract (`ctx.connections.resolveValue`, `getValue`,\n // `getValues`) is `StorageFailure`-typed; fold a reauth-required resolution\n // failure into a StorageError so the public surface stays stable.\n const foldResolutionFailure = <A>(\n effect: Effect.Effect<A, StorageFailure | CredentialResolutionError>,\n ): Effect.Effect<A, StorageFailure> =>\n effect.pipe(\n Effect.catchTag(\"CredentialResolutionError\", (err) =>\n Effect.fail(\n new StorageError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: CredentialResolutionError carries a typed `message` field\n message: err.message,\n cause: err,\n }),\n ),\n ),\n );\n\n const resolveConnectionValueByRef = (\n ref: ConnectionRef,\n ): Effect.Effect<string | null, StorageFailure> =>\n foldResolutionFailure(\n Effect.gen(function* () {\n const row = yield* findConnectionRow(ref);\n if (!row) return null;\n return yield* resolveConnectionValue(row);\n }),\n );\n\n const resolveConnectionValuesByRef = (\n ref: ConnectionRef,\n ): Effect.Effect<Record<string, string | null>, StorageFailure> =>\n foldResolutionFailure(\n Effect.gen(function* () {\n const row = yield* findConnectionRow(ref);\n if (!row) return {};\n return yield* resolveConnectionValues(row);\n }),\n );\n\n // ------------------------------------------------------------------\n // Integrations\n // ------------------------------------------------------------------\n\n const findIntegrationRow = (\n slug: IntegrationSlug,\n ): Effect.Effect<IntegrationRow | null, StorageFailure> =>\n core.findFirst(\"integration\", {\n where: (b: AnyCb) => b(\"slug\", \"=\", String(slug)),\n });\n\n // Project a row's stored config into declared auth methods via the owning\n // plugin's `describeAuthMethods` hook. The hook is plugin-authored, so a\n // throw (malformed config it didn't guard) degrades to `[]` rather than\n // failing the catalog read.\n const describeAuthMethodsForRow = (row: IntegrationRow): readonly AuthMethodDescriptor[] => {\n const runtime = runtimes.get(row.plugin_id);\n const describe = runtime?.plugin.describeAuthMethods;\n if (!describe) return [];\n const record = rowToIntegrationRecord(row);\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: plugin-authored projector must never fail the catalog read\n try {\n return describe(record);\n } catch {\n return [];\n }\n };\n\n const describeDisplayUrlForRow = (row: IntegrationRow): string | undefined => {\n const runtime = runtimes.get(row.plugin_id);\n const describe = runtime?.plugin.describeIntegrationDisplay;\n if (!describe) return undefined;\n const record = rowToIntegrationRecord(row);\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: plugin-authored projector must never fail the catalog read\n try {\n const display = describe(record);\n return display.url && display.url.length > 0 ? display.url : undefined;\n } catch {\n return undefined;\n }\n };\n\n const integrationsList = (): Effect.Effect<readonly Integration[], StorageFailure> =>\n core\n .findMany(\"integration\", {})\n .pipe(\n Effect.map((rows) => [\n ...staticSources().map(staticSourceToIntegration),\n ...rows.map((row) =>\n rowToIntegration(row, describeAuthMethodsForRow(row), describeDisplayUrlForRow(row)),\n ),\n ]),\n );\n\n const integrationsGet = (\n slug: IntegrationSlug,\n ): Effect.Effect<Integration | null, StorageFailure> =>\n Effect.gen(function* () {\n const staticSource = staticSources().find((source) => source.id === String(slug));\n if (staticSource) return staticSourceToIntegration(staticSource);\n const row = yield* findIntegrationRow(slug);\n return row\n ? rowToIntegration(row, describeAuthMethodsForRow(row), describeDisplayUrlForRow(row))\n : null;\n });\n\n const integrationsGetRecord = (\n slug: IntegrationSlug,\n ): Effect.Effect<IntegrationRecord | null, StorageFailure> =>\n findIntegrationRow(slug).pipe(\n Effect.map((row) =>\n row ? rowToIntegrationRecord(row, describeAuthMethodsForRow(row)) : null,\n ),\n );\n\n const integrationsRegister = (\n pluginId: string,\n input: RegisterIntegrationInput,\n ): Effect.Effect<void, StorageFailure> =>\n transaction(\n Effect.gen(function* () {\n const now = new Date();\n const existing = yield* findIntegrationRow(input.slug);\n const config = input.config === undefined ? null : input.config;\n if (existing) {\n yield* core.updateMany(\"integration\", {\n where: (b: AnyCb) => b(\"slug\", \"=\", String(input.slug)),\n set: {\n plugin_id: pluginId,\n name: input.name ?? existing.name ?? null,\n description: input.description,\n config,\n can_remove: input.canRemove ?? Boolean(existing.can_remove),\n can_refresh: input.canRefresh ?? Boolean(existing.can_refresh),\n updated_at: now,\n },\n });\n return;\n }\n yield* core.create(\"integration\", {\n tenant,\n slug: String(input.slug),\n plugin_id: pluginId,\n name: input.name ?? null,\n description: input.description,\n config,\n can_remove: input.canRemove ?? true,\n can_refresh: input.canRefresh ?? false,\n created_at: now,\n updated_at: now,\n });\n }),\n );\n\n const integrationsUpdate = (\n slug: IntegrationSlug,\n patch: {\n readonly name?: string;\n readonly description?: string;\n readonly config?: IntegrationConfig;\n },\n ): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n const now = new Date();\n const set: Record<string, unknown> = { updated_at: now };\n if (patch.name !== undefined) set.name = patch.name;\n if (patch.description !== undefined) set.description = patch.description;\n if (patch.config !== undefined) {\n set.config = patch.config;\n // A config change can change the derived tools. The writer can only\n // rebuild catalogs in its own partition (owner policy), so revise\n // the integration: other subjects' connections compare this stamp\n // against their `tools_synced_at` and lazily rebuild on next read.\n set.config_revised_at = now.getTime();\n }\n yield* core.updateMany(\"integration\", {\n where: (b: AnyCb) => b(\"slug\", \"=\", String(slug)),\n set,\n });\n });\n\n const integrationsUpdatePublic = (\n slug: IntegrationSlug,\n patch: { readonly name?: string; readonly description?: string },\n ): Effect.Effect<void, IntegrationNotFoundError | StorageFailure> =>\n Effect.gen(function* () {\n const existing = yield* findIntegrationRow(slug);\n if (!existing) return yield* new IntegrationNotFoundError({ slug });\n yield* integrationsUpdate(slug, patch);\n });\n\n const integrationsRemove = (\n slug: IntegrationSlug,\n ): Effect.Effect<void, IntegrationRemovalNotAllowedError | StorageFailure> =>\n transaction(\n Effect.gen(function* () {\n const existing = yield* findIntegrationRow(slug);\n if (!existing) return;\n if (!existing.can_remove) {\n return yield* new IntegrationRemovalNotAllowedError({ slug });\n }\n // Drop owned connections / tools / definitions for this integration.\n const where = (b: AnyCb) => b(\"integration\", \"=\", String(slug));\n yield* core.deleteMany(\"tool\", { where });\n yield* core.deleteMany(\"definition\", { where });\n yield* core.deleteMany(\"connection\", { where });\n yield* core.deleteMany(\"integration\", {\n where: (b: AnyCb) => b(\"slug\", \"=\", String(slug)),\n });\n }),\n );\n\n const integrationsDetect = (\n url: string,\n ): Effect.Effect<readonly IntegrationDetectionResult[], StorageFailure> =>\n Effect.gen(function* () {\n const results: IntegrationDetectionResult[] = [];\n for (const runtime of runtimes.values()) {\n if (!runtime.plugin.detect) continue;\n const result = yield* runtime.plugin\n .detect({ ctx: runtime.ctx, url })\n .pipe(\n Effect.mapError((cause) => pluginStorageFailure(runtime.plugin.id, \"detect\", cause)),\n );\n if (result) results.push(result);\n }\n return results;\n });\n\n // ------------------------------------------------------------------\n // Per-connection tool production\n // ------------------------------------------------------------------\n\n const produceConnectionTools = (\n integrationRow: IntegrationRow,\n ref: ConnectionRef,\n ): Effect.Effect<readonly Tool[], IntegrationNotFoundError | StorageFailure> =>\n Effect.gen(function* () {\n const runtime = runtimes.get(integrationRow.plugin_id);\n const keys = yield* Effect.try({\n try: () => ownedKeys(ref.owner),\n catch: (cause) => storageFailureFromUnknown(\"invalid owner\", cause),\n });\n const owner = ref.owner;\n const where = (b: AnyCb) =>\n b.and(\n byOwner(owner)(b),\n b(\"integration\", \"=\", String(ref.integration)),\n b(\"connection\", \"=\", String(ref.name)),\n );\n // Every exit stamps the sync time — including the cleanup paths that\n // produce zero tools — so the stale-catalog check (`config_revised_at`\n // vs `tools_synced_at`) doesn't re-attempt this connection per read.\n const stampSynced = core.updateMany(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(owner)(b),\n b(\"integration\", \"=\", String(ref.integration)),\n b(\"name\", \"=\", String(ref.name)),\n ),\n set: { tools_synced_at: Date.now() },\n });\n\n // Defense in depth (and cleanup for rows created before the create-time\n // guard, or emptied by an external edit): a credentialed non-OAuth\n // connection with no bound credential inputs can never resolve a value,\n // so never advertise tools for it — every call would fail with\n // `connection_value_missing`. OAuth connections resolve via refresh and\n // carry their token outside `item_ids`; no-auth (`\"none\"` template)\n // connections legitimately bind nothing (an empty `item_ids` is their\n // canonical shape) — both are exempt.\n const existingRow = yield* findConnectionRow(ref);\n if (\n existingRow &&\n existingRow.oauth_client == null &&\n existingRow.template !== String(NO_AUTH_TEMPLATE) &&\n Object.keys(connectionItemIds(existingRow)).length === 0\n ) {\n yield* transaction(\n Effect.gen(function* () {\n yield* core.deleteMany(\"tool\", { where });\n yield* core.deleteMany(\"definition\", { where });\n yield* stampSynced;\n }),\n );\n return [];\n }\n\n if (!runtime?.plugin.resolveTools) {\n // No dynamic tools — clear any existing rows and return empty.\n yield* transaction(\n Effect.gen(function* () {\n yield* core.deleteMany(\"tool\", { where });\n yield* core.deleteMany(\"definition\", { where });\n yield* stampSynced;\n }),\n );\n return [];\n }\n\n const result: ResolveToolsResult = yield* runtime.plugin\n .resolveTools({\n integration: rowToIntegration(integrationRow),\n config: decodeJsonColumn(integrationRow.config),\n httpClientLayer: runtime.ctx.httpClientLayer,\n connection: ref,\n template: existingRow ? AuthTemplateSlug.make(existingRow.template) : null,\n storage: runtime.storage,\n getValue: () => resolveConnectionValueByRef(ref),\n getValues: () => resolveConnectionValuesByRef(ref),\n })\n .pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(integrationRow.plugin_id, \"resolveTools\", cause),\n ),\n );\n\n const now = new Date();\n const toolRows = result.tools.map((tool: ToolDef) => ({\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n integration: String(ref.integration),\n connection: String(ref.name),\n plugin_id: integrationRow.plugin_id,\n name: String(tool.name),\n description: tool.description ?? \"\",\n input_schema: tool.inputSchema ?? null,\n output_schema: tool.outputSchema ?? null,\n annotations: tool.annotations ?? null,\n created_at: now,\n updated_at: now,\n }));\n\n const definitionRows = Object.entries(result.definitions ?? {}).map(([name, schema]) => ({\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n integration: String(ref.integration),\n connection: String(ref.name),\n plugin_id: integrationRow.plugin_id,\n name,\n schema,\n created_at: now,\n }));\n\n yield* transaction(\n Effect.gen(function* () {\n yield* core.deleteMany(\"tool\", { where });\n yield* core.deleteMany(\"definition\", { where });\n yield* core.createMany(\"tool\", toolRows);\n yield* core.createMany(\"definition\", definitionRows);\n yield* stampSynced;\n }),\n );\n\n return result.tools.map((tool: ToolDef) =>\n rowToTool(\n {\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n integration: String(ref.integration),\n connection: String(ref.name),\n plugin_id: integrationRow.plugin_id,\n name: String(tool.name),\n description: tool.description ?? \"\",\n input_schema: tool.inputSchema ?? null,\n output_schema: tool.outputSchema ?? null,\n annotations: tool.annotations ?? null,\n created_at: now,\n updated_at: now,\n } as ConnectionToolRow,\n tool.annotations,\n ),\n );\n });\n\n // ------------------------------------------------------------------\n // Connections\n // ------------------------------------------------------------------\n\n const connectionsCreate = (\n input: CreateConnectionInput,\n ): Effect.Effect<\n Connection,\n | IntegrationNotFoundError\n | CredentialProviderNotRegisteredError\n | InvalidConnectionInputError\n | StorageFailure\n > =>\n Effect.gen(function* () {\n const name = connectionIdentifier(String(input.name));\n // Typed (not StorageError) so the HTTP edge can answer 400 with the\n // reason instead of an opaque 500 — callers can act on it.\n if (input.owner === \"user\" && subject == null) {\n return yield* new InvalidConnectionInputError({\n message:\n 'Cannot create a personal connection: this context has no user subject. Create it with owner \"org\", or connect as a signed-in user.',\n });\n }\n const integrationRow = yield* findIntegrationRow(input.integration);\n if (!integrationRow) {\n return yield* new IntegrationNotFoundError({\n slug: input.integration,\n });\n }\n\n // Resolve the value origin(s) → one provider + an item_ids map (one entry\n // per named input). All of a connection's inputs share a single provider:\n // pasted inputs go to the default writable store, external `from` inputs to\n // their provider. Mixing pasted + external, or two external providers, is\n // rejected (the connection row carries one `provider`).\n const inputs = normalizeConnectionInputs(input);\n const pasted = inputs.filter((i) => \"value\" in i.origin);\n const external = inputs.filter((i) => \"from\" in i.origin);\n // A credentialed connection is born wired: it must reference at least\n // one credential input. An empty binding (no inputs at all — e.g. an\n // empty `values`/`inputs` map) is a credential with no credential: it\n // would persist, produce a full tool catalog, and then fail every\n // invocation with `connection_value_missing`. Reject it here — EXCEPT\n // for the no-auth template (\"none\"), where zero inputs and an empty\n // `item_ids` map are the canonical shape (public MCP servers; the UI\n // submits `values: {}` for them). OAuth connections are minted via\n // `mintOAuthConnection`, not this path; an external `from` reference\n // may resolve to null and is surfaced at invoke time, not here.\n const isNoAuth = String(input.template) === String(NO_AUTH_TEMPLATE);\n if (inputs.length === 0 && !isNoAuth) {\n return yield* new InvalidConnectionInputError({\n message: \"A connection must supply at least one credential input.\",\n });\n }\n let providerKey: string;\n const itemIds: Record<string, string> = {};\n if (external.length > 0 && pasted.length > 0) {\n return yield* new InvalidConnectionInputError({\n message: \"A connection cannot mix pasted and external-provider inputs.\",\n });\n }\n if (external.length > 0) {\n const providers = new Set(\n external.map((i) => (\"from\" in i.origin ? String(i.origin.from.provider) : \"\")),\n );\n if (providers.size > 1) {\n return yield* new InvalidConnectionInputError({\n message: \"A connection's inputs must all use the same external provider.\",\n });\n }\n const [only] = [...providers];\n const provider = credentialProviders.get(only ?? \"\");\n if (!provider) {\n return yield* new CredentialProviderNotRegisteredError({\n provider: ProviderKey.make(only ?? \"\"),\n });\n }\n providerKey = only ?? \"\";\n for (const i of external) {\n if (\"from\" in i.origin) itemIds[i.variable] = String(i.origin.from.id);\n }\n } else {\n const provider = defaultWritableProvider();\n if (!provider) {\n return yield* new CredentialProviderNotRegisteredError({\n provider: ProviderKey.make(\"default\"),\n });\n }\n providerKey = String(provider.key);\n for (const i of pasted) {\n const itemId = `connection:${input.owner}:${input.integration}:${name}:${i.variable}`;\n if (\"value\" in i.origin && provider.set) {\n yield* provider.set(ProviderItemId.make(itemId), i.origin.value);\n }\n itemIds[i.variable] = itemId;\n }\n }\n\n const keys = yield* Effect.try({\n try: () => ownedKeys(input.owner),\n catch: (cause) => storageFailureFromUnknown(\"invalid owner\", cause),\n });\n const now = new Date();\n yield* transaction(\n Effect.gen(function* () {\n const existing = yield* findConnectionRow({\n owner: input.owner,\n integration: input.integration,\n name,\n });\n const set: Record<string, unknown> = {\n template: String(input.template),\n provider: providerKey,\n item_ids: itemIds,\n identity_label: input.identityLabel ?? null,\n // Re-saving a credential keeps an existing curated description\n // unless the caller explicitly provides one.\n ...(input.description !== undefined ? { description: input.description } : {}),\n updated_at: now,\n };\n if (existing) {\n yield* core.updateMany(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(input.owner)(b),\n b(\"integration\", \"=\", String(input.integration)),\n b(\"name\", \"=\", String(name)),\n ),\n set,\n });\n } else {\n yield* core.create(\"connection\", {\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n integration: String(input.integration),\n name: String(name),\n template: String(input.template),\n provider: providerKey,\n item_ids: itemIds,\n identity_label: input.identityLabel ?? null,\n description: input.description ?? null,\n oauth_client: null,\n refresh_item_id: null,\n expires_at: null,\n oauth_scope: null,\n provider_state: null,\n created_at: now,\n updated_at: now,\n });\n }\n }),\n );\n\n const ref: ConnectionRef = {\n owner: input.owner,\n integration: input.integration,\n name,\n };\n // Produce + persist tools for the new connection.\n yield* produceConnectionTools(integrationRow, ref).pipe(\n Effect.catchTag(\"IntegrationNotFoundError\", () => Effect.succeed([] as readonly Tool[])),\n );\n\n const row = yield* findConnectionRow(ref);\n return row\n ? rowToConnection(row)\n : rowToConnection({\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n integration: String(input.integration),\n name: String(name),\n template: String(input.template),\n provider: providerKey,\n item_ids: itemIds,\n identity_label: input.identityLabel ?? null,\n description: input.description ?? null,\n oauth_client: null,\n refresh_item_id: null,\n expires_at: null,\n oauth_scope: null,\n provider_state: null,\n created_at: now,\n updated_at: now,\n } as ConnectionRow);\n });\n\n // Mint (or re-mint) an OAuth connection: write the connection row with its\n // OAuth lifecycle fields (the access token is already stored in the provider\n // by the OAuth service) + produce the connection's tools. Mirrors\n // `connectionsCreate`'s upsert + tool-production, stamping the OAuth columns.\n const mintOAuthConnection = (\n input: MintOAuthConnectionInput,\n ): Effect.Effect<Connection, StorageFailure> =>\n Effect.gen(function* () {\n const name = connectionIdentifier(String(input.name));\n yield* requireUserSubject(input.owner);\n const integrationRow = yield* findIntegrationRow(input.integration);\n if (!integrationRow) {\n return yield* new StorageError({\n message: `Integration not found: ${input.integration}`,\n cause: undefined,\n });\n }\n const keys = yield* Effect.try({\n try: () => ownedKeys(input.owner),\n catch: (cause) => storageFailureFromUnknown(\"invalid owner\", cause),\n });\n const now = new Date();\n const ref: ConnectionRef = {\n owner: input.owner,\n integration: input.integration,\n name,\n };\n yield* transaction(\n Effect.gen(function* () {\n const existing = yield* findConnectionRow(ref);\n const set: Record<string, unknown> = {\n template: String(input.template),\n provider: input.provider,\n item_ids: { [PRIMARY_INPUT_VARIABLE]: input.itemId },\n identity_label: input.identityLabel ?? null,\n oauth_client: String(input.oauthClient),\n oauth_client_owner: input.oauthClientOwner,\n refresh_item_id: input.refreshItemId,\n expires_at: input.expiresAt,\n oauth_scope: input.oauthScope,\n oauth_token_url: input.oauthTokenUrl ?? null,\n updated_at: now,\n };\n if (existing) {\n yield* core.updateMany(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(input.owner)(b),\n b(\"integration\", \"=\", String(input.integration)),\n b(\"name\", \"=\", String(name)),\n ),\n set,\n });\n } else {\n yield* core.create(\"connection\", {\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n integration: String(input.integration),\n name: String(name),\n template: String(input.template),\n provider: input.provider,\n item_ids: { [PRIMARY_INPUT_VARIABLE]: input.itemId },\n identity_label: input.identityLabel ?? null,\n // Curated description: never stamped by a mint — a reconnect\n // or token refresh must not erase what the user wrote.\n description: null,\n oauth_client: String(input.oauthClient),\n oauth_client_owner: input.oauthClientOwner,\n refresh_item_id: input.refreshItemId,\n expires_at: input.expiresAt,\n oauth_scope: input.oauthScope,\n oauth_token_url: input.oauthTokenUrl ?? null,\n provider_state: null,\n created_at: now,\n updated_at: now,\n });\n }\n }),\n );\n\n // Produce + persist tools for the minted connection (same path\n // connections.create uses).\n yield* produceConnectionTools(integrationRow, ref).pipe(\n Effect.catchTag(\"IntegrationNotFoundError\", () => Effect.succeed([] as readonly Tool[])),\n );\n\n const row = yield* findConnectionRow(ref);\n return row\n ? rowToConnection(row)\n : rowToConnection({\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n integration: String(input.integration),\n name: String(name),\n template: String(input.template),\n provider: input.provider,\n item_ids: { [PRIMARY_INPUT_VARIABLE]: input.itemId },\n identity_label: input.identityLabel ?? null,\n description: null,\n oauth_client: String(input.oauthClient),\n oauth_client_owner: input.oauthClientOwner,\n refresh_item_id: input.refreshItemId,\n expires_at: input.expiresAt,\n oauth_scope: input.oauthScope,\n oauth_token_url: input.oauthTokenUrl ?? null,\n provider_state: null,\n created_at: now,\n updated_at: now,\n } as ConnectionRow);\n });\n\n const connectionsList = (filter?: {\n readonly integration?: IntegrationSlug;\n readonly owner?: Owner;\n }): Effect.Effect<readonly Connection[], StorageFailure> =>\n Effect.gen(function* () {\n const rows = yield* core.findMany(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n filter?.integration === undefined\n ? true\n : b(\"integration\", \"=\", String(filter.integration)),\n filter?.owner === undefined ? true : b(\"owner\", \"=\", filter.owner),\n ),\n });\n const connections = rows.map(rowToConnection);\n if (!activeToolPolicyProvider) return connections;\n\n const visibleTools = yield* toolsList({ includeAnnotations: false });\n const visibleConnectionKeys = new Set(\n visibleTools\n .filter((tool) => !tool.static)\n .map((tool) => `${tool.owner}:${tool.integration}:${tool.connection}`),\n );\n return connections.filter((connection) =>\n visibleConnectionKeys.has(\n `${connection.owner}:${connection.integration}:${connection.name}`,\n ),\n );\n });\n\n const connectionsGet = (ref: ConnectionRef): Effect.Effect<Connection | null, StorageFailure> =>\n findConnectionRow(ref).pipe(Effect.map((row) => (row ? rowToConnection(row) : null)));\n\n const connectionsUpdate = (\n ref: ConnectionRef,\n input: UpdateConnectionInput,\n ): Effect.Effect<Connection, ConnectionNotFoundError | StorageFailure> =>\n Effect.gen(function* () {\n const row = yield* findConnectionRow(ref);\n if (!row) {\n return yield* new ConnectionNotFoundError({\n owner: ref.owner,\n integration: ref.integration,\n name: ref.name,\n });\n }\n const set: Record<string, unknown> = { updated_at: new Date() };\n if (input.description !== undefined) set.description = input.description;\n if (input.identityLabel !== undefined) set.identity_label = input.identityLabel;\n yield* core.updateMany(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(ref.owner)(b),\n b(\"integration\", \"=\", String(ref.integration)),\n b(\"name\", \"=\", String(ref.name)),\n ),\n set,\n });\n const updated = yield* findConnectionRow(ref);\n return rowToConnection(updated ?? row);\n });\n\n const connectionsRemove = (\n ref: ConnectionRef,\n ): Effect.Effect<void, ConnectionNotFoundError | StorageFailure> =>\n transaction(\n Effect.gen(function* () {\n const row = yield* findConnectionRow(ref);\n if (!row) {\n return yield* new ConnectionNotFoundError({\n owner: ref.owner,\n integration: ref.integration,\n name: ref.name,\n });\n }\n const integrationRow = yield* findIntegrationRow(ref.integration);\n const runtime = integrationRow ? runtimes.get(integrationRow.plugin_id) : undefined;\n if (integrationRow && runtime?.plugin.removeConnection) {\n yield* runtime.plugin\n .removeConnection({\n ctx: runtime.ctx,\n integration: ref.integration,\n connection: ref,\n })\n .pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(integrationRow.plugin_id, \"removeConnection\", cause),\n ),\n );\n }\n const where = (b: AnyCb) =>\n b.and(\n byOwner(ref.owner)(b),\n b(\"integration\", \"=\", String(ref.integration)),\n b(\"connection\", \"=\", String(ref.name)),\n );\n yield* core.deleteMany(\"tool\", { where });\n yield* core.deleteMany(\"definition\", { where });\n yield* core.deleteMany(\"connection\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(ref.owner)(b),\n b(\"integration\", \"=\", String(ref.integration)),\n b(\"name\", \"=\", String(ref.name)),\n ),\n });\n }),\n );\n\n const connectionsRefresh = (\n ref: ConnectionRef,\n ): Effect.Effect<\n readonly Tool[],\n ConnectionNotFoundError | IntegrationNotFoundError | StorageFailure\n > =>\n Effect.gen(function* () {\n const row = yield* findConnectionRow(ref);\n if (!row) {\n return yield* new ConnectionNotFoundError({\n owner: ref.owner,\n integration: ref.integration,\n name: ref.name,\n });\n }\n const integrationRow = yield* findIntegrationRow(ref.integration);\n if (!integrationRow) {\n return yield* new IntegrationNotFoundError({ slug: ref.integration });\n }\n return yield* produceConnectionTools(integrationRow, ref);\n });\n\n // ------------------------------------------------------------------\n // Active policy source.\n // ------------------------------------------------------------------\n\n type ActivePolicyRuleSet =\n | { readonly kind: \"global\"; readonly rows: readonly ToolPolicyRow[] }\n | {\n readonly kind: \"provider\";\n readonly provider: ToolPolicyProvider;\n readonly rules: readonly ToolPolicyProviderRule[] | null;\n }\n | {\n readonly kind: \"prepared\";\n readonly resolve: (input: {\n readonly toolId: string;\n readonly defaultRequiresApproval?: boolean;\n }) => EffectivePolicy;\n };\n\n const compareProviderPolicyRule = (\n a: ToolPolicyProviderRule,\n b: ToolPolicyProviderRule,\n ): number => {\n if (a.position < b.position) return -1;\n if (a.position > b.position) return 1;\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n };\n\n const resolveProviderPolicyFromRules = (\n toolId: string,\n rules: readonly ToolPolicyProviderRule[],\n ): EffectivePolicy => {\n for (const rule of [...rules].sort(compareProviderPolicyRule)) {\n if (!matchPattern(rule.pattern, toolId)) continue;\n return {\n action: rule.action,\n source: \"user\",\n pattern: rule.pattern,\n policyId: rule.id,\n };\n }\n // Toolkit-style providers are capability allowlists. No matching rule\n // means the tool is outside the capability boundary.\n return {\n action: \"block\",\n source: \"user\",\n pattern: \"*\",\n };\n };\n\n const listActivePolicyRuleSet = (): Effect.Effect<ActivePolicyRuleSet, StorageFailure> =>\n activeToolPolicyProvider\n ? // Batched per-operation resolver: fetch all policy + connection state\n // once, then resolve every tool in this operation against that\n // snapshot. Avoids the per-tool resolve N+1 on the list surface.\n activeToolPolicyProvider.prepare\n ? activeToolPolicyProvider\n .prepare()\n .pipe(Effect.map((resolve) => ({ kind: \"prepared\" as const, resolve })))\n : activeToolPolicyProvider.resolve\n ? Effect.succeed({\n kind: \"provider\" as const,\n provider: activeToolPolicyProvider,\n rules: null,\n })\n : activeToolPolicyProvider.list().pipe(\n Effect.map((rules) => ({\n kind: \"provider\" as const,\n provider: activeToolPolicyProvider!,\n rules,\n })),\n )\n : core\n .findMany(\"tool_policy\", {})\n .pipe(Effect.map((rows) => ({ kind: \"global\" as const, rows })));\n\n const resolvePolicyFromRuleSet = (\n toolId: string,\n ruleSet: ActivePolicyRuleSet,\n defaultRequiresApproval?: boolean,\n ): Effect.Effect<EffectivePolicy, StorageFailure> =>\n ruleSet.kind === \"prepared\"\n ? Effect.succeed(ruleSet.resolve({ toolId, defaultRequiresApproval }))\n : ruleSet.kind === \"provider\"\n ? ruleSet.provider.resolve\n ? ruleSet.provider.resolve({ toolId, defaultRequiresApproval })\n : Effect.succeed(resolveProviderPolicyFromRules(toolId, ruleSet.rules ?? []))\n : Effect.succeed(\n resolveEffectivePolicy(\n toolId,\n ruleSet.rows,\n ownerRankForRow,\n defaultRequiresApproval,\n ),\n );\n\n // ------------------------------------------------------------------\n // Tools (read surface)\n // ------------------------------------------------------------------\n\n const matchesToolFilter = (tool: Tool, filter: ToolListFilter | undefined): boolean => {\n if (!filter) return true;\n if (filter.integration !== undefined && tool.integration !== filter.integration) return false;\n if (filter.owner !== undefined && tool.owner !== filter.owner) return false;\n if (filter.connection !== undefined && tool.connection !== filter.connection) return false;\n if (filter.query !== undefined) {\n const q = filter.query.toLowerCase();\n const hay = `${tool.name} ${tool.description}`.toLowerCase();\n if (!hay.includes(q)) return false;\n }\n return true;\n };\n\n // Rebuild any visible connection whose tool catalog predates its\n // integration's last tool-affecting config change. The change's author\n // could only rewrite catalogs in their own partition (owner policy);\n // every other subject converges here, on their own read, under their own\n // binding. Best-effort: a failed rebuild leaves the stale-but-working\n // catalog in place and retries on the next read.\n const syncStaleConnectionTools = Effect.gen(function* () {\n const revised = yield* core.findMany(\"integration\", {\n where: (b: AnyCb) => b.isNotNull(\"config_revised_at\"),\n });\n if (revised.length === 0) return;\n const revisedAt = new Map(\n revised.map((row) => [row.slug, Number(row.config_revised_at)] as const),\n );\n const connections = yield* core.findMany(\"connection\", {\n where: (b: AnyCb) => b.or(...revised.map((row) => b(\"integration\", \"=\", row.slug))),\n });\n for (const connection of connections) {\n const revisedTime = revisedAt.get(connection.integration);\n if (revisedTime === undefined) continue;\n const syncedAt =\n connection.tools_synced_at == null ? 0 : Number(connection.tools_synced_at);\n if (syncedAt >= revisedTime) continue;\n const integrationRow = revised.find((row) => row.slug === connection.integration);\n if (!integrationRow) continue;\n yield* produceConnectionTools(integrationRow, {\n owner: connection.owner as Owner,\n integration: IntegrationSlug.make(connection.integration),\n name: ConnectionName.make(connection.name),\n }).pipe(\n Effect.catch(() => Effect.succeed([] as readonly Tool[])),\n Effect.withSpan(\"executor.tools.sync_stale\", {\n attributes: {\n \"executor.integration\": connection.integration,\n \"executor.connection\": connection.name,\n },\n }),\n );\n }\n });\n\n const toolsList = (filter?: ToolListFilter): Effect.Effect<readonly Tool[], StorageFailure> =>\n Effect.gen(function* () {\n yield* syncStaleConnectionTools;\n // Projected: the list surface is metadata (address, description,\n // annotations) — loading every tool's input/output schema JSON made\n // an unbounded list scale with schema bytes, not tool count.\n const rows = yield* core.findMany(\"tool\", {\n where: (b: AnyCb) =>\n b.and(\n filter?.integration === undefined\n ? true\n : b(\"integration\", \"=\", String(filter.integration)),\n filter?.owner === undefined ? true : b(\"owner\", \"=\", filter.owner),\n filter?.connection === undefined\n ? true\n : b(\"connection\", \"=\", String(filter.connection)),\n ),\n select: TOOL_INVOCATION_COLUMNS,\n });\n const includeBlocked = filter?.includeBlocked ?? false;\n const policyRules = yield* listActivePolicyRuleSet();\n const tools: Tool[] = [];\n for (const row of rows) {\n const tool = rowToTool(row);\n if (!matchesToolFilter(tool, filter)) continue;\n if (!includeBlocked) {\n const effective = yield* resolvePolicyFromRuleSet(\n normalizedPolicyId(tool),\n policyRules,\n tool.annotations?.requiresApproval,\n );\n if (effective.action === \"block\") continue;\n }\n tools.push(tool);\n }\n for (const entry of staticTools.values()) {\n const tool = staticToolToTool(entry);\n if (!matchesToolFilter(tool, filter)) continue;\n if (!includeBlocked) {\n const effective = yield* resolvePolicyFromRuleSet(\n normalizedPolicyId(tool),\n policyRules,\n tool.annotations?.requiresApproval,\n );\n if (effective.action === \"block\") continue;\n }\n tools.push(tool);\n }\n return tools;\n });\n\n const toolSchema = (\n address: ToolAddress,\n ): Effect.Effect<ToolSchemaView | null, StorageFailure> =>\n Effect.gen(function* () {\n const policyRules = yield* listActivePolicyRuleSet();\n const staticEntry = staticTools.get(String(address));\n if (staticEntry) {\n const tool = staticToolToTool(staticEntry);\n const effective = yield* resolvePolicyFromRuleSet(\n normalizedPolicyId(tool),\n policyRules,\n tool.annotations?.requiresApproval,\n );\n if (effective.action === \"block\") return null;\n const preview = yield* Effect.tryPromise({\n try: () =>\n buildToolTypeScriptPreview({\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n defs: new Map(),\n }),\n catch: (cause) =>\n storageFailureFromUnknown(\"Failed to build static tool TypeScript preview\", cause),\n }).pipe(Effect.option);\n return ToolSchemaView.make({\n address,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n inputTypeScript: Option.getOrUndefined(preview)?.inputTypeScript,\n outputTypeScript: Option.getOrUndefined(preview)?.outputTypeScript,\n typeScriptDefinitions: Option.getOrUndefined(preview)?.typeScriptDefinitions,\n });\n }\n\n const parsed = parseToolAddress(String(address));\n if (!parsed) return null;\n const row = yield* core.findFirst(\"tool\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(parsed.owner)(b),\n b(\"integration\", \"=\", String(parsed.integration)),\n b(\"connection\", \"=\", String(parsed.connection)),\n b(\"name\", \"=\", String(parsed.tool)),\n ),\n });\n if (!row) return null;\n const tool = rowToTool(row);\n const effective = yield* resolvePolicyFromRuleSet(\n normalizedPolicyId(tool),\n policyRules,\n tool.annotations?.requiresApproval,\n );\n if (effective.action === \"block\") return null;\n\n const definitionRows = yield* core.findMany(\"definition\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(parsed.owner)(b),\n b(\"integration\", \"=\", String(parsed.integration)),\n b(\"connection\", \"=\", String(parsed.connection)),\n ),\n });\n const defs = new Map<string, unknown>();\n for (const def of definitionRows) defs.set(def.name, decodeJsonColumn(def.schema));\n\n const referenced = collectReferencedDefinitions(\n [tool.inputSchema, tool.outputSchema],\n defs,\n );\n const preview = yield* Effect.tryPromise({\n try: () =>\n buildToolTypeScriptPreview({\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n defs,\n }),\n catch: (cause) =>\n storageFailureFromUnknown(\"Failed to build tool TypeScript preview\", cause),\n }).pipe(Effect.option);\n\n const view = preview;\n return ToolSchemaView.make({\n address,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n schemaDefinitions:\n Object.keys(referenced).length > 0\n ? (referenced as Record<string, unknown>)\n : undefined,\n inputTypeScript: Option.getOrUndefined(view)?.inputTypeScript,\n outputTypeScript: Option.getOrUndefined(view)?.outputTypeScript,\n typeScriptDefinitions: Option.getOrUndefined(view)?.typeScriptDefinitions,\n });\n });\n\n // ------------------------------------------------------------------\n // Providers\n // ------------------------------------------------------------------\n\n const providersList = (): Effect.Effect<readonly ProviderKey[]> =>\n Effect.sync(() => credentialProviderOrder.map((key) => ProviderKey.make(key)));\n\n const providersItems = (\n key: ProviderKey,\n ): Effect.Effect<readonly ProviderEntry[], StorageFailure> =>\n Effect.gen(function* () {\n const provider = credentialProviders.get(String(key));\n if (!provider || !provider.list) return [];\n return yield* provider.list();\n });\n\n // ------------------------------------------------------------------\n // Policies — owner-ranked (user=0 inner, org=1 outer).\n // ------------------------------------------------------------------\n\n const ownerRankForRow = (row: { readonly owner: string }): number =>\n row.owner === \"user\" ? 0 : 1;\n\n // Tool policies gate by tool identity (`<integration>.<tool>`), independent of\n // which connection serves it; the org/user split is handled by owner-scoped\n // policy rows + ownerRank, not the match pattern.\n const normalizedPolicyId = (tool: Tool): string =>\n tool.static\n ? String(tool.address)\n : `${tool.integration}.${tool.owner}.${tool.connection}.${tool.name}`;\n\n const policiesList = (): Effect.Effect<readonly ToolPolicy[], StorageFailure> =>\n core\n .findMany(\"tool_policy\", {})\n .pipe(\n Effect.map((rows) =>\n [...rows]\n .sort((a, b) => ownerRankForRow(a) - ownerRankForRow(b) || comparePolicyRow(a, b))\n .map(rowToToolPolicy),\n ),\n );\n\n const policiesCreate = (\n input: CreateToolPolicyInput,\n ): Effect.Effect<ToolPolicy, StorageFailure> =>\n Effect.gen(function* () {\n if (!isValidPattern(input.pattern)) {\n return yield* new StorageError({\n message: `Invalid tool policy pattern: ${input.pattern}`,\n cause: undefined,\n });\n }\n if (!isToolPolicyAction(input.action)) {\n return yield* new StorageError({\n message: `Invalid tool policy action: ${String(input.action)}`,\n cause: undefined,\n });\n }\n yield* requireUserSubject(input.owner);\n const keys = yield* Effect.try({\n try: () => ownedKeys(input.owner),\n catch: (cause) => storageFailureFromUnknown(\"invalid owner\", cause),\n });\n const existing = yield* core.findMany(\"tool_policy\", {\n where: byOwner(input.owner),\n });\n const minPosition = existing\n .map((row) => row.position)\n .sort()\n .at(0);\n const position = input.position ?? generateKeyBetween(null, minPosition ?? null);\n const id = PolicyId.make(\n `pol_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,\n );\n const now = new Date();\n const created = yield* core.create(\"tool_policy\", {\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n id: String(id),\n pattern: input.pattern,\n action: input.action,\n position,\n created_at: now,\n updated_at: now,\n });\n return rowToToolPolicy(created);\n });\n\n const policiesUpdate = (\n input: UpdateToolPolicyInput,\n ): Effect.Effect<ToolPolicy, StorageFailure> =>\n Effect.gen(function* () {\n if (input.pattern !== undefined && !isValidPattern(input.pattern)) {\n return yield* new StorageError({\n message: `Invalid tool policy pattern: ${input.pattern}`,\n cause: undefined,\n });\n }\n const where = (b: AnyCb) => b.and(byOwner(input.owner)(b), b(\"id\", \"=\", input.id));\n const existing = yield* core.findFirst(\"tool_policy\", { where });\n if (!existing) {\n return yield* new StorageError({\n message: `Tool policy not found: ${input.id}`,\n cause: undefined,\n });\n }\n const set: Record<string, unknown> = { updated_at: new Date() };\n if (input.pattern !== undefined) set.pattern = input.pattern;\n if (input.action !== undefined) set.action = input.action;\n if (input.position !== undefined) set.position = input.position;\n yield* core.updateMany(\"tool_policy\", { where, set });\n const updated = yield* core.findFirst(\"tool_policy\", { where });\n return rowToToolPolicy(updated ?? ({ ...existing, ...set } as ToolPolicyRow));\n });\n\n const policiesRemove = (input: RemoveToolPolicyInput): Effect.Effect<void, StorageFailure> =>\n core.deleteMany(\"tool_policy\", {\n where: (b: AnyCb) => b.and(byOwner(input.owner)(b), b(\"id\", \"=\", input.id)),\n });\n\n const policiesResolve = (\n address: ToolAddress,\n ): Effect.Effect<EffectivePolicy, StorageFailure> =>\n Effect.gen(function* () {\n const parsed = parseToolAddress(String(address));\n const policyRows = yield* core.findMany(\"tool_policy\", {});\n const toolId = parsed\n ? `${parsed.integration}.${parsed.owner}.${parsed.connection}.${parsed.tool}`\n : String(address);\n // Find the tool to read its default approval annotation.\n let requiresApproval: boolean | undefined;\n if (parsed) {\n const row = yield* core.findFirst(\"tool\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(parsed.owner)(b),\n b(\"integration\", \"=\", String(parsed.integration)),\n b(\"connection\", \"=\", String(parsed.connection)),\n b(\"name\", \"=\", String(parsed.tool)),\n ),\n });\n if (row) {\n const annotations = decodeJsonColumn(row.annotations) as ToolAnnotations | undefined;\n requiresApproval = annotations?.requiresApproval;\n }\n }\n return resolveEffectivePolicy(toolId, policyRows, ownerRankForRow, requiresApproval);\n });\n\n // ------------------------------------------------------------------\n // Elicitation\n // ------------------------------------------------------------------\n\n const defaultElicitationHandler = resolveElicitationHandler(config.onElicitation);\n\n const pickHandler = (options: InvokeOptions | undefined): ElicitationHandler =>\n options?.onElicitation\n ? resolveElicitationHandler(options.onElicitation)\n : defaultElicitationHandler;\n\n const buildElicit = (\n address: ToolAddress,\n args: unknown,\n handler: ElicitationHandler,\n ): Elicit => {\n return (request: ElicitationRequest) =>\n Effect.gen(function* () {\n const response: ElicitationResponse = yield* handler({\n address,\n args,\n request,\n });\n if (response.action !== \"accept\") {\n return yield* new ElicitationDeclinedError({\n address,\n action: response.action,\n });\n }\n return response;\n });\n };\n\n const enforceApproval = (\n annotations: ToolAnnotations | undefined,\n address: ToolAddress,\n args: unknown,\n policy: EffectivePolicy,\n handler: ElicitationHandler,\n ) =>\n Effect.gen(function* () {\n if (policy.action === \"approve\") return;\n const policyForcesApproval = policy.action === \"require_approval\";\n if (!policyForcesApproval && !annotations?.requiresApproval) return;\n const message = annotations?.approvalDescription\n ? annotations.approvalDescription\n : policyForcesApproval && policy.pattern\n ? `Approve ${address}? (matched policy: ${policy.pattern})`\n : `Approve ${address}?`;\n const request = FormElicitation.make({\n message: `${message}\\n\\nArguments:\\n${approvalArgumentPreview(args)}`,\n requestedSchema: { type: \"object\", properties: {} },\n });\n const response = yield* handler({ address, args, request });\n if (response.action !== \"accept\") {\n return yield* new ElicitationDeclinedError({\n address,\n action: response.action,\n });\n }\n });\n\n // ------------------------------------------------------------------\n // execute — the invoke path.\n // ------------------------------------------------------------------\n\n const TOOL_SUGGESTION_LIMIT = 5;\n\n const toolSuggestions = (rows: readonly ToolInvocationRow[]): readonly ToolAddress[] =>\n rows.map((row) => rowToTool(row).address);\n\n const toolRowsForConnectionWhere = (parsed: ParsedToolAddress) => (b: AnyCb) =>\n b.and(\n byOwner(parsed.owner)(b),\n b(\"integration\", \"=\", String(parsed.integration)),\n b(\"connection\", \"=\", String(parsed.connection)),\n );\n\n const searchToolRowsForConnection = (\n parsed: ParsedToolAddress,\n ): Effect.Effect<readonly ToolInvocationRow[], StorageFailure> =>\n core.findMany(\"tool\", {\n where: (b: AnyCb) =>\n b.and(\n toolRowsForConnectionWhere(parsed)(b),\n b.or(\n b(\"name\", \"contains\", String(parsed.tool)),\n b(\"description\", \"contains\", String(parsed.tool)),\n ),\n ),\n orderBy: [\"name\", \"asc\"],\n limit: TOOL_SUGGESTION_LIMIT,\n select: TOOL_INVOCATION_COLUMNS,\n });\n\n const findToolRowsForConnection = (\n parsed: ParsedToolAddress,\n ): Effect.Effect<readonly ToolInvocationRow[], StorageFailure> =>\n core.findMany(\"tool\", {\n where: toolRowsForConnectionWhere(parsed),\n orderBy: [\"name\", \"asc\"],\n limit: TOOL_SUGGESTION_LIMIT,\n select: TOOL_INVOCATION_COLUMNS,\n });\n\n const execute = (\n address: ToolAddress,\n args: unknown,\n options?: InvokeOptions,\n ): Effect.Effect<unknown, ExecuteError> => {\n const handler = pickHandler(options);\n return Effect.gen(function* () {\n // oxlint-disable executor/no-instanceof-error, executor/no-unknown-error-message, executor/no-manual-tag-check -- boundary: normalize arbitrary unknown plugin failures into a human-readable message for ToolInvocationError/telemetry\n const formatInvocationCauseMessage = (cause: unknown): string => {\n if (cause instanceof Error && cause.message.length > 0) return cause.message;\n // Non-Error / empty-message causes: `String(plainObject)` renders\n // \"[object Object]\", which is what telemetry then shows as the only\n // label for the failure. Prefer the tag, else stringify structurally.\n if (typeof cause === \"object\" && cause !== null) {\n const tag = (cause as { readonly _tag?: unknown })._tag;\n if (typeof tag === \"string\") return tag;\n return Inspectable.toStringUnknown(cause, 0);\n }\n return String(cause);\n };\n // oxlint-enable executor/no-instanceof-error, executor/no-unknown-error-message, executor/no-manual-tag-check\n const wrapInvocationError = <A, E>(\n effect: Effect.Effect<A, E>,\n ): Effect.Effect<A, ToolInvocationError> =>\n effect.pipe(\n Effect.mapError(\n (cause) =>\n new ToolInvocationError({\n address,\n message: formatInvocationCauseMessage(cause),\n cause,\n }),\n ),\n );\n\n // Static path — O(1) map lookup for plugin-contributed static tools\n // (core-tools, plugin executor namespaces). Addressed by their fqid,\n // not the 5-segment dynamic form.\n const staticEntry = staticTools.get(String(address));\n if (staticEntry) {\n const policyRules = yield* listActivePolicyRuleSet();\n const policy = yield* resolvePolicyFromRuleSet(\n String(address),\n policyRules,\n staticEntry.tool.annotations?.requiresApproval,\n );\n if (policy.action === \"block\") {\n return yield* new ToolBlockedError({\n address,\n pattern: policy.pattern ?? \"*\",\n });\n }\n yield* enforceApproval(staticEntry.tool.annotations, address, args, policy, handler);\n return yield* wrapInvocationError(\n staticEntry.tool.handler({\n ctx: staticEntry.ctx,\n args,\n elicit: buildElicit(address, args, handler),\n }),\n );\n }\n\n const parsed = parseToolAddress(String(address));\n if (!parsed) {\n return yield* new ToolNotFoundError({ address });\n }\n\n // Find the tool row — projected: invoke needs routing/policy fields\n // only, never the multi-KB input/output schema JSON (`tools.schema`\n // is the schema-bearing surface).\n const row = yield* core.findFirst(\"tool\", {\n where: (b: AnyCb) =>\n b.and(\n byOwner(parsed.owner)(b),\n b(\"integration\", \"=\", String(parsed.integration)),\n b(\"connection\", \"=\", String(parsed.connection)),\n b(\"name\", \"=\", String(parsed.tool)),\n ),\n select: TOOL_INVOCATION_COLUMNS,\n });\n if (!row) {\n const searchMatches = yield* searchToolRowsForConnection(parsed);\n const connectionTools =\n searchMatches.length > 0 ? searchMatches : yield* findToolRowsForConnection(parsed);\n return yield* new ToolNotFoundError({\n address,\n suggestions: toolSuggestions(connectionTools),\n });\n }\n\n // Resolve policy (owner-ranked).\n const toolForPolicy = rowToTool(row);\n const policyRules = yield* listActivePolicyRuleSet();\n const annotations = decodeJsonColumn(row.annotations) as ToolAnnotations | undefined;\n const policy = yield* resolvePolicyFromRuleSet(\n normalizedPolicyId(toolForPolicy),\n policyRules,\n annotations?.requiresApproval,\n );\n if (policy.action === \"block\") {\n return yield* new ToolBlockedError({\n address,\n pattern: policy.pattern ?? \"*\",\n });\n }\n\n const runtime = runtimes.get(row.plugin_id);\n if (!runtime) {\n return yield* new PluginNotLoadedError({\n address,\n pluginId: row.plugin_id,\n });\n }\n if (!runtime.plugin.invokeTool) {\n return yield* new NoHandlerError({\n address,\n pluginId: row.plugin_id,\n });\n }\n\n // Find the connection row.\n const connectionRow = yield* findConnectionRow({\n owner: parsed.owner,\n integration: parsed.integration,\n name: parsed.connection,\n });\n if (!connectionRow) {\n return yield* new ConnectionNotFoundError({\n owner: parsed.owner,\n integration: parsed.integration,\n name: parsed.connection,\n });\n }\n\n // Resolve annotations + enforce approval.\n let resolvedAnnotations = annotations;\n if (policy.action !== \"approve\" && runtime.plugin.resolveAnnotations) {\n const map = yield* runtime.plugin\n .resolveAnnotations({\n ctx: runtime.ctx,\n integration: parsed.integration,\n connection: parsed.connection,\n toolRows: [row],\n })\n .pipe(wrapInvocationError);\n resolvedAnnotations = map[String(parsed.tool)] ?? annotations;\n }\n yield* enforceApproval(resolvedAnnotations, address, args, policy, handler);\n\n // Resolve every named credential input (`variable → value`); `value` is\n // the primary `token` for single-input + OAuth callers.\n const values = yield* resolveConnectionValues(connectionRow);\n const integrationRow = yield* findIntegrationRow(parsed.integration);\n const credential: ToolInvocationCredential = {\n owner: parsed.owner,\n integration: parsed.integration,\n connection: parsed.connection,\n template: AuthTemplateSlug.make(connectionRow.template),\n value: values[PRIMARY_INPUT_VARIABLE] ?? null,\n values,\n config: integrationRow ? decodeJsonColumn(integrationRow.config) : undefined,\n };\n\n return yield* wrapInvocationError(\n runtime.plugin.invokeTool({\n ctx: runtime.ctx,\n toolRow: row,\n credential,\n args,\n elicit: buildElicit(address, args, handler),\n }),\n );\n }).pipe(\n // Expected tool failures (`ToolResult.fail`) resolve through the\n // success channel, so the tracer alone would record them as healthy\n // spans. Stamp the outcome + error code so telemetry can distinguish\n // \"tool ran fine\" from \"user hit an upstream error / auth wall\"\n // without parsing response bodies.\n Effect.tap(annotateToolResultOutcome),\n Effect.withSpan(\"executor.tool.execute\", {\n attributes: {\n \"mcp.tool.name\": String(address),\n \"executor.tenant\": tenant,\n ...(subject != null ? { \"executor.subject\": subject } : {}),\n },\n }),\n );\n };\n\n // ------------------------------------------------------------------\n // OAuth service seam.\n // ------------------------------------------------------------------\n\n const oauth = makeOAuthService({\n fuma,\n owner: ownerBinding,\n tenant,\n subject,\n ownedKeys: (owner: Owner) => ownedKeys(owner),\n defaultWritableProvider,\n mintOAuthConnection: (input: MintOAuthConnectionInput) => mintOAuthConnection(input),\n // One integration-row read + one projector run. Resolve the method this\n // template selects exactly as the runtime's `selectAuthMethod` does —\n // exact slug match, else the sole declared method (single-method\n // integrations accept any slug); an ambiguous miss selects nothing rather\n // than guessing across methods. The discover-vs-scopes choice then reads\n // off that method (MCP exposes `discoveryUrl`), so core needs no plugin-id\n // knowledge.\n resolveOAuthScopePolicy: (integration: IntegrationSlug, template: AuthTemplateSlug) =>\n findIntegrationRow(integration).pipe(\n Effect.map((row): OAuthScopePolicy => {\n const methods = row ? describeAuthMethodsForRow(row) : [];\n const selected =\n methods.find((m: AuthMethodDescriptor) => m.template === String(template)) ??\n (methods.length === 1 ? methods[0] : undefined);\n const oauth = selected?.kind === \"oauth\" ? selected.oauth : undefined;\n // Declared scopes win. Discover only when the selected method\n // declares none but names a source to discover them from (MCP).\n if (oauth?.scopes === undefined && oauth?.discoveryUrl !== undefined) {\n return { kind: \"discover\" };\n }\n return { kind: \"scopes\", scopes: oauth?.scopes ?? [] };\n }),\n ),\n httpClientLayer: config.httpClientLayer,\n fetch: config.fetch,\n endpointUrlPolicy: config.oauthEndpointUrlPolicy,\n // EXPLICIT — no localhost default. When a caller omits `redirectUri` the\n // OAuth service receives `null` and redirect-requiring flows fail loudly\n // instead of silently using `http://127.0.0.1/callback`. Hosts that serve\n // OAuth (cloud, self-host) derive a real `${webBaseUrl}/oauth/callback`.\n redirectUri: config.redirectUri ?? null,\n callbackStateOrgSlug: config.oauthCallbackStateOrgSlug ?? null,\n });\n\n // ------------------------------------------------------------------\n // Plugin wiring — build ctx, run extension, populate static pools,\n // register credential providers.\n // ------------------------------------------------------------------\n\n const blobPartitions: OwnerPartitions = {\n org: `o:${tenant}`,\n user: subject != null ? `u:${tenant}:${subject}` : null,\n };\n\n for (const plugin of plugins) {\n if (runtimes.has(plugin.id)) {\n return yield* new StorageError({\n message: `Duplicate plugin id: ${plugin.id}`,\n cause: undefined,\n });\n }\n\n const pluginStorage = makePluginStorageFacade({\n core,\n pluginId: plugin.id,\n owner: ownerBinding,\n });\n const storageDeps: StorageDeps = {\n owner: ownerBinding,\n blobs: pluginBlobStore(blobs, blobPartitions, plugin.id),\n pluginStorage,\n };\n const storage = plugin.storage(storageDeps);\n\n const ctx: PluginCtx<unknown> = {\n owner: ownerBinding,\n storage,\n pluginStorage,\n httpClientLayer: config.httpClientLayer ?? FetchHttpClient.layer,\n core: {\n integrations: {\n register: (input: RegisterIntegrationInput) => integrationsRegister(plugin.id, input),\n update: (slug, patch) => integrationsUpdate(slug, patch),\n list: () => integrationsList(),\n get: (slug) => integrationsGetRecord(slug),\n remove: (slug) => integrationsRemove(slug),\n detect: (url) => integrationsDetect(url),\n configureSchemas: (): readonly IntegrationConfigureSchema[] =>\n Array.from(runtimes.values())\n .map(({ plugin }) =>\n plugin.integrationConfigure\n ? {\n pluginId: plugin.id,\n type: plugin.integrationConfigure.type,\n schema: undefined,\n }\n : undefined,\n )\n .filter(Predicate.isNotUndefined),\n presets: (): readonly IntegrationPresetCatalogEntry[] =>\n Array.from(runtimes.values()).flatMap(({ plugin }) =>\n (plugin.integrationPresets ?? []).map((preset) => ({\n ...preset,\n pluginId: plugin.id,\n })),\n ),\n },\n policies: {\n list: () => policiesList(),\n create: (input) => policiesCreate(input),\n update: (input) => policiesUpdate(input),\n remove: (input) => policiesRemove(input),\n },\n },\n connections: {\n create: (input) => connectionsCreate(input),\n list: (filter) => connectionsList(filter),\n get: (ref) => connectionsGet(ref),\n update: (ref, input) => connectionsUpdate(ref, input),\n remove: (ref) => connectionsRemove(ref),\n refresh: (ref) => connectionsRefresh(ref),\n resolveValue: (ref) => resolveConnectionValueByRef(ref),\n },\n providers: {\n list: () => providersList(),\n items: (key) => providersItems(key),\n },\n oauth,\n transaction: <A, E>(effect: Effect.Effect<A, E>) => transaction(effect),\n };\n\n if (plugin.toolPolicyProvider) {\n const rawProvider = plugin.toolPolicyProvider(ctx);\n const provider = Effect.isEffect(rawProvider) ? yield* rawProvider : rawProvider;\n if (provider) {\n if (activeToolPolicyProvider) {\n return yield* new StorageError({\n message: \"Only one plugin can provide the active tool policy source.\",\n cause: undefined,\n });\n }\n activeToolPolicyProvider = provider;\n }\n }\n\n // Build extension FIRST so it's available as `self` for staticSources.\n const extension: object = plugin.extension ? plugin.extension(ctx) : {};\n if (plugin.extension) {\n extensions[plugin.id] = extension;\n }\n\n const decls = plugin.staticSources ? plugin.staticSources(extension) : [];\n for (const source of decls) {\n const mountUnderExecutor = source.kind === \"executor\";\n const mountedSource = mountUnderExecutor ? EXECUTOR_SOURCE : source;\n for (const tool of source.tools) {\n const mountedTool = mountUnderExecutor\n ? { ...tool, name: `${source.id}.${tool.name}` }\n : tool;\n const fqid = `${mountedSource.id}.${mountedTool.name}`;\n if (staticTools.has(fqid)) {\n return yield* new StorageError({\n message: `Duplicate static tool id: ${fqid} (plugin ${plugin.id})`,\n cause: undefined,\n });\n }\n staticTools.set(fqid, {\n source: mountedSource,\n tool: mountedTool,\n pluginId: plugin.id,\n ctx,\n });\n }\n }\n\n runtimes.set(plugin.id, { plugin, storage, ctx });\n\n if (plugin.credentialProviders) {\n const raw =\n typeof plugin.credentialProviders === \"function\"\n ? plugin.credentialProviders(ctx)\n : plugin.credentialProviders;\n const providers = Effect.isEffect(raw)\n ? yield* raw.pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(plugin.id, \"credentialProviders\", cause),\n ),\n )\n : raw;\n for (const provider of providers) {\n yield* registerCredentialProvider(provider, `plugin ${plugin.id}`);\n }\n }\n }\n\n // ------------------------------------------------------------------\n // close\n // ------------------------------------------------------------------\n\n const close = () =>\n Effect.gen(function* () {\n for (const runtime of runtimes.values()) {\n if (runtime.plugin.close) {\n yield* runtime.plugin\n .close()\n .pipe(\n Effect.mapError((cause) => pluginStorageFailure(runtime.plugin.id, \"close\", cause)),\n );\n }\n }\n if (closeDb) {\n const out = closeDb();\n if (Effect.isEffect(out)) {\n yield* out;\n } else if (out instanceof Promise) {\n yield* Effect.tryPromise({\n try: () => out,\n catch: (cause) =>\n new StorageError({\n message: \"Executor database close failed\",\n cause,\n }),\n });\n }\n }\n });\n\n const base = {\n integrations: {\n list: integrationsList,\n get: integrationsGet,\n update: integrationsUpdatePublic,\n remove: integrationsRemove,\n detect: integrationsDetect,\n },\n connections: {\n create: connectionsCreate,\n list: connectionsList,\n get: connectionsGet,\n update: connectionsUpdate,\n remove: connectionsRemove,\n refresh: connectionsRefresh,\n },\n oauth,\n tools: {\n list: toolsList,\n schema: toolSchema,\n },\n providers: {\n list: providersList,\n items: providersItems,\n },\n policies: {\n list: policiesList,\n create: policiesCreate,\n update: policiesUpdate,\n remove: policiesRemove,\n resolve: policiesResolve,\n },\n execute,\n close,\n };\n\n const toExecutor = (value: unknown): Executor<TPlugins> => value as Executor<TPlugins>;\n return toExecutor(Object.assign(base, extensions));\n });\n\n// Helper alias so the inline literal used for the optimistic projection in\n// `produceConnectionTools` satisfies the ToolRow shape.\ntype ConnectionToolRow = ToolRow;\n","// ---------------------------------------------------------------------------\n// core-tools plugin\n//\n// Built-in plugin that contributes agent-facing static tools for configuring\n// executor-level primitives over the v2 surface. Agent-facing connection setup\n// should hand users to the web UI for pasted credentials; low-level creation\n// through this plugin only accepts provider refs.\n// ---------------------------------------------------------------------------\n\nimport { Effect, Schema } from \"effect\";\n\nimport type { Connection, ConnectionInputOrigin, CreateConnectionInput } from \"./connection\";\nimport {\n AuthTemplateSlug,\n ConnectionName,\n IntegrationSlug,\n NO_AUTH_TEMPLATE,\n OAuthClientSlug,\n OAuthState,\n ProviderItemId,\n ProviderKey,\n type Owner,\n} from \"./ids\";\nimport { definePlugin, tool, type StaticToolSchema } from \"./plugin\";\nimport { ToolPolicyActionSchema } from \"./policies\";\nimport type { Tool } from \"./tool\";\n\nconst schemaToStandard = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>\n Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<\n A,\n I\n >;\n\nconst OwnerSchema = Schema.Literals([\"org\", \"user\"]);\nconst OAuthGrantSchema = Schema.Literals([\"authorization_code\", \"client_credentials\"]);\n\n// ---------------------------------------------------------------------------\n// Schemas\n// ---------------------------------------------------------------------------\n\nconst IntegrationOutput = Schema.Struct({\n slug: Schema.String,\n description: Schema.String,\n kind: Schema.String,\n canRemove: Schema.Boolean,\n canRefresh: Schema.Boolean,\n});\n\nconst IntegrationsListOutput = Schema.Struct({\n integrations: Schema.Array(IntegrationOutput),\n});\n\nconst DetectInput = Schema.Struct({ url: Schema.String });\nconst DetectOutput = Schema.Struct({\n results: Schema.Array(\n Schema.Struct({\n kind: Schema.String,\n confidence: Schema.Literals([\"high\", \"medium\", \"low\"]),\n endpoint: Schema.String,\n name: Schema.String,\n slug: Schema.String,\n }),\n ),\n});\n\nconst ConnectionOutput = Schema.Struct({\n owner: OwnerSchema,\n name: Schema.String,\n integration: Schema.String,\n template: Schema.String,\n provider: Schema.String,\n address: Schema.String,\n identityLabel: Schema.optional(Schema.NullOr(Schema.String)),\n description: Schema.optional(Schema.NullOr(Schema.String)),\n expiresAt: Schema.NullOr(Schema.Number),\n oauthClient: Schema.NullOr(Schema.String),\n oauthClientOwner: Schema.NullOr(OwnerSchema),\n oauthScope: Schema.NullOr(Schema.String),\n});\n\nconst ConnectionsListInput = Schema.Struct({\n integration: Schema.optional(Schema.String),\n owner: Schema.optional(OwnerSchema),\n verbose: Schema.optional(Schema.Boolean),\n});\n\n/** Lean per-connection shape for list scans. Omits the full `oauthScope`\n * grant string (a single connection's scope list can run to thousands of\n * characters and dominates the payload) in favor of `oauthScopeCount`. The\n * full scope is included only when the caller passes `verbose: true`. */\nconst ConnectionListItem = Schema.Struct({\n owner: OwnerSchema,\n name: Schema.String,\n integration: Schema.String,\n template: Schema.String,\n provider: Schema.String,\n address: Schema.String,\n identityLabel: Schema.optional(Schema.NullOr(Schema.String)),\n description: Schema.optional(Schema.NullOr(Schema.String)),\n expiresAt: Schema.NullOr(Schema.Number),\n oauthClient: Schema.NullOr(Schema.String),\n oauthClientOwner: Schema.NullOr(OwnerSchema),\n oauthScopeCount: Schema.NullOr(Schema.Number),\n oauthScope: Schema.optional(Schema.NullOr(Schema.String)),\n});\nconst ConnectionsListOutput = Schema.Struct({\n connections: Schema.Array(ConnectionListItem),\n});\n\nconst ConnectionCreateHandoffInput = Schema.Struct({\n integration: Schema.String,\n owner: Schema.optional(OwnerSchema),\n template: Schema.optional(Schema.String),\n label: Schema.optional(Schema.String),\n});\nconst ConnectionCreateHandoffOutput = Schema.Struct({\n url: Schema.String,\n instructions: Schema.String,\n});\n\nconst ConnectionFromInput = Schema.Struct({\n provider: Schema.String,\n id: Schema.String,\n});\nconst ConnectionInputOriginInput = Schema.Struct({ from: ConnectionFromInput });\nconst ConnectionCreateInput = Schema.Struct({\n owner: OwnerSchema,\n name: Schema.String,\n integration: Schema.String,\n template: Schema.String,\n identityLabel: Schema.optional(Schema.NullOr(Schema.String)),\n from: Schema.optional(ConnectionFromInput),\n inputs: Schema.optional(Schema.Record(Schema.String, ConnectionInputOriginInput)),\n}).check(\n Schema.makeFilter((payload) => {\n const originCount =\n (payload.from === undefined ? 0 : 1) + (payload.inputs === undefined ? 0 : 1);\n // The no-auth template (\"none\") binds zero credentials — both `from` and\n // `inputs` are legitimately absent (public MCP servers, public REST APIs).\n // Mirror the engine, which accepts an empty input set only for this\n // template; a stray origin would wire a credential the connection can't\n // hold, so reject any. Every other template needs exactly one origin.\n const isNoAuth = String(payload.template) === String(NO_AUTH_TEMPLATE);\n if (isNoAuth) {\n if (originCount > 0) {\n return 'A no-auth connection (template \"none\") takes no provider credential origin';\n }\n } else if (originCount !== 1) {\n return \"Expected exactly one provider credential origin\";\n }\n if (payload.inputs !== undefined && Object.keys(payload.inputs).length === 0) {\n return \"Expected at least one provider credential input\";\n }\n return undefined;\n }),\n);\nconst ConnectionRefInput = Schema.Struct({\n owner: OwnerSchema,\n name: Schema.String,\n integration: Schema.String,\n});\n\nconst ToolOutput = Schema.Struct({\n address: Schema.String,\n owner: OwnerSchema,\n integration: Schema.String,\n connection: Schema.String,\n name: Schema.String,\n pluginId: Schema.String,\n description: Schema.String,\n});\nconst ConnectionsRefreshOutput = Schema.Struct({\n tools: Schema.Array(ToolOutput),\n});\n\nconst RemovedOutput = Schema.Struct({ removed: Schema.Boolean });\nconst CancelledOutput = Schema.Struct({ cancelled: Schema.Boolean });\n\nconst ProvidersOutput = Schema.Struct({\n providers: Schema.Array(Schema.String),\n});\n\nconst ProviderItemsInput = Schema.Struct({ provider: Schema.String });\nconst ProviderItemsOutput = Schema.Struct({\n items: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.String })),\n});\n\nconst PolicyOutput = Schema.Struct({\n id: Schema.String,\n owner: OwnerSchema,\n pattern: Schema.String,\n action: Schema.String,\n position: Schema.String,\n});\nconst PoliciesListOutput = Schema.Struct({\n policies: Schema.Array(PolicyOutput),\n});\n\nconst PolicyCreateInput = Schema.Struct({\n owner: OwnerSchema,\n pattern: Schema.String,\n action: ToolPolicyActionSchema,\n});\nconst PolicyUpdateInput = Schema.Struct({\n id: Schema.String,\n owner: OwnerSchema,\n pattern: Schema.optional(Schema.String),\n action: Schema.optional(ToolPolicyActionSchema),\n});\nconst PolicyRemoveInput = Schema.Struct({\n id: Schema.String,\n owner: OwnerSchema,\n});\n\nconst OAuthClientOutput = Schema.Struct({\n owner: OwnerSchema,\n slug: Schema.String,\n grant: OAuthGrantSchema,\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n resource: Schema.optional(Schema.NullOr(Schema.String)),\n clientId: Schema.String,\n origin: Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"manual\") }),\n Schema.Struct({\n kind: Schema.Literal(\"dynamic_client_registration\"),\n integration: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n ]),\n});\nconst OAuthClientsListOutput = Schema.Struct({\n clients: Schema.Array(OAuthClientOutput),\n});\n// No `clientSecret`: a confidential client's secret must never cross the agent\n// boundary (it would land in the LLM context window). This tool registers a\n// PUBLIC client only; a secret-bearing app is registered by the human through\n// `oauth.clients.createHandoff`, which deep-links them to the web form.\nconst OAuthCreateClientInput = Schema.Struct({\n owner: OwnerSchema,\n slug: Schema.String,\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n grant: OAuthGrantSchema,\n clientId: Schema.String,\n resource: Schema.optional(Schema.NullOr(Schema.String)),\n});\n// Browser-handoff for a CONFIDENTIAL OAuth app: carries only the NON-secret\n// fields the form pre-fills. The client secret is typed by the human in the web\n// UI, exactly like a pasted connection credential, so it never reaches the\n// agent. Mirrors `ConnectionCreateHandoffInput`.\nconst OAuthCreateClientHandoffInput = Schema.Struct({\n integration: Schema.String,\n owner: Schema.optional(OwnerSchema),\n slug: Schema.optional(Schema.String),\n grant: Schema.optional(OAuthGrantSchema),\n clientId: Schema.optional(Schema.String),\n authorizationUrl: Schema.optional(Schema.String),\n tokenUrl: Schema.optional(Schema.String),\n resource: Schema.optional(Schema.NullOr(Schema.String)),\n label: Schema.optional(Schema.String),\n});\nconst OAuthCreateClientHandoffOutput = Schema.Struct({\n url: Schema.String,\n instructions: Schema.String,\n});\nconst OAuthClientOutputRef = Schema.Struct({\n client: Schema.String,\n});\nconst OAuthRegisterDynamicInput = Schema.Struct({\n owner: OwnerSchema,\n slug: Schema.String,\n registrationEndpoint: Schema.String,\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n resource: Schema.optional(Schema.NullOr(Schema.String)),\n scopes: Schema.Array(Schema.String),\n tokenEndpointAuthMethodsSupported: Schema.optional(Schema.Array(Schema.String)),\n clientName: Schema.optional(Schema.String),\n redirectUri: Schema.optional(Schema.NullOr(Schema.String)),\n originIntegration: Schema.optional(Schema.NullOr(Schema.String)),\n});\nconst OAuthRemoveClientInput = Schema.Struct({\n owner: OwnerSchema,\n slug: Schema.String,\n});\nconst OAuthProbeInput = Schema.Struct({\n url: Schema.String,\n});\nconst OAuthProbeOutput = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n resource: Schema.optional(Schema.NullOr(Schema.String)),\n scopesSupported: Schema.optional(Schema.Array(Schema.String)),\n registrationEndpoint: Schema.optional(Schema.NullOr(Schema.String)),\n tokenEndpointAuthMethodsSupported: Schema.optional(Schema.Array(Schema.String)),\n});\nconst OAuthStartInput = Schema.Struct({\n client: Schema.String,\n clientOwner: OwnerSchema,\n owner: OwnerSchema,\n name: Schema.String,\n integration: Schema.String,\n template: Schema.String,\n identityLabel: Schema.optional(Schema.NullOr(Schema.String)),\n redirectUri: Schema.optional(Schema.NullOr(Schema.String)),\n});\nconst OAuthStartOutput = Schema.Union([\n Schema.Struct({\n status: Schema.Literal(\"connected\"),\n connection: ConnectionOutput,\n }),\n Schema.Struct({\n status: Schema.Literal(\"redirect\"),\n authorizationUrl: Schema.String,\n state: Schema.String,\n }),\n]);\nconst OAuthCancelInput = Schema.Struct({\n state: Schema.String,\n});\n\n// Standard-schema versions for the tool() builder.\nconst IntegrationsListOutputStd = schemaToStandard(IntegrationsListOutput);\nconst DetectInputStd = schemaToStandard(DetectInput);\nconst DetectOutputStd = schemaToStandard(DetectOutput);\nconst ConnectionsListInputStd = schemaToStandard(ConnectionsListInput);\nconst ConnectionsListOutputStd = schemaToStandard(ConnectionsListOutput);\nconst ConnectionCreateHandoffInputStd = schemaToStandard(ConnectionCreateHandoffInput);\nconst ConnectionCreateHandoffOutputStd = schemaToStandard(ConnectionCreateHandoffOutput);\nconst ConnectionCreateInputStd = schemaToStandard(ConnectionCreateInput);\nconst ConnectionOutputStd = schemaToStandard(ConnectionOutput);\nconst ConnectionRefInputStd = schemaToStandard(ConnectionRefInput);\nconst ConnectionsRefreshOutputStd = schemaToStandard(ConnectionsRefreshOutput);\nconst RemovedOutputStd = schemaToStandard(RemovedOutput);\nconst CancelledOutputStd = schemaToStandard(CancelledOutput);\nconst ProvidersOutputStd = schemaToStandard(ProvidersOutput);\nconst ProviderItemsInputStd = schemaToStandard(ProviderItemsInput);\nconst ProviderItemsOutputStd = schemaToStandard(ProviderItemsOutput);\nconst PoliciesListOutputStd = schemaToStandard(PoliciesListOutput);\nconst PolicyOutputStd = schemaToStandard(PolicyOutput);\nconst PolicyCreateInputStd = schemaToStandard(PolicyCreateInput);\nconst PolicyUpdateInputStd = schemaToStandard(PolicyUpdateInput);\nconst PolicyRemoveInputStd = schemaToStandard(PolicyRemoveInput);\nconst OAuthClientsListOutputStd = schemaToStandard(OAuthClientsListOutput);\nconst OAuthCreateClientInputStd = schemaToStandard(OAuthCreateClientInput);\nconst OAuthCreateClientHandoffInputStd = schemaToStandard(OAuthCreateClientHandoffInput);\nconst OAuthCreateClientHandoffOutputStd = schemaToStandard(OAuthCreateClientHandoffOutput);\nconst OAuthClientOutputRefStd = schemaToStandard(OAuthClientOutputRef);\nconst OAuthRegisterDynamicInputStd = schemaToStandard(OAuthRegisterDynamicInput);\nconst OAuthRemoveClientInputStd = schemaToStandard(OAuthRemoveClientInput);\nconst OAuthProbeInputStd = schemaToStandard(OAuthProbeInput);\nconst OAuthProbeOutputStd = schemaToStandard(OAuthProbeOutput);\nconst OAuthStartInputStd = schemaToStandard(OAuthStartInput);\nconst OAuthStartOutputStd = schemaToStandard(OAuthStartOutput);\nconst OAuthCancelInputStd = schemaToStandard(OAuthCancelInput);\n\nconst connectionToOutput = (connection: Connection) => ({\n owner: connection.owner,\n name: String(connection.name),\n integration: String(connection.integration),\n template: String(connection.template),\n provider: String(connection.provider),\n address: String(connection.address),\n identityLabel: connection.identityLabel ?? null,\n description: connection.description ?? null,\n expiresAt: connection.expiresAt ?? null,\n oauthClient: connection.oauthClient == null ? null : String(connection.oauthClient),\n oauthClientOwner: connection.oauthClientOwner ?? null,\n oauthScope: connection.oauthScope ?? null,\n});\n\n/** Number of space-separated grants in an `oauthScope` string, or null when\n * the connection carries no scope (static credentials, or an OAuth AS that\n * omitted scope). */\nconst oauthScopeCount = (scope: string | null | undefined): number | null =>\n scope == null ? null : scope.split(/\\s+/).filter(Boolean).length;\n\n/** Lean projection for `connections.list`. Summarizes `oauthScope` to a count\n * unless `verbose`, where the full grant string is included too. */\nconst connectionToListItem = (connection: Connection, verbose: boolean) => ({\n owner: connection.owner,\n name: String(connection.name),\n integration: String(connection.integration),\n template: String(connection.template),\n provider: String(connection.provider),\n address: String(connection.address),\n identityLabel: connection.identityLabel ?? null,\n description: connection.description ?? null,\n expiresAt: connection.expiresAt ?? null,\n oauthClient: connection.oauthClient == null ? null : String(connection.oauthClient),\n oauthClientOwner: connection.oauthClientOwner ?? null,\n oauthScopeCount: oauthScopeCount(connection.oauthScope),\n ...(verbose ? { oauthScope: connection.oauthScope ?? null } : {}),\n});\n\nconst toolToOutput = (toolRow: Tool) => ({\n address: String(toolRow.address),\n owner: toolRow.owner,\n integration: String(toolRow.integration),\n connection: String(toolRow.connection),\n name: String(toolRow.name),\n pluginId: toolRow.pluginId,\n description: toolRow.description,\n});\n\nconst connectionRefFromInput = (input: typeof ConnectionRefInput.Type) => ({\n owner: input.owner as Owner,\n integration: IntegrationSlug.make(input.integration),\n name: ConnectionName.make(input.name),\n});\n\nconst originFromInput = (\n origin: typeof ConnectionInputOriginInput.Type,\n): ConnectionInputOrigin => ({\n from: {\n provider: ProviderKey.make(origin.from.provider),\n id: ProviderItemId.make(origin.from.id),\n },\n});\n\nconst createConnectionInputFromTool = (\n input: typeof ConnectionCreateInput.Type,\n): CreateConnectionInput => {\n const base = {\n owner: input.owner as Owner,\n name: ConnectionName.make(input.name),\n integration: IntegrationSlug.make(input.integration),\n template: AuthTemplateSlug.make(input.template),\n identityLabel: input.identityLabel ?? null,\n };\n\n if (input.from !== undefined) {\n return {\n ...base,\n from: {\n provider: ProviderKey.make(input.from.provider),\n id: ProviderItemId.make(input.from.id),\n },\n };\n }\n return {\n ...base,\n inputs: Object.fromEntries(\n Object.entries(input.inputs ?? {}).map(([variable, origin]) => [\n variable,\n originFromInput(origin),\n ]),\n ),\n };\n};\n\nconst connectionCreateHandoffUrl = (\n webBaseUrl: string | undefined,\n orgSlug: string | undefined,\n input: typeof ConnectionCreateHandoffInput.Type,\n): string => {\n const search = new URLSearchParams({ addAccount: \"1\" });\n if (input.owner !== undefined) search.set(\"owner\", input.owner);\n if (input.template !== undefined) search.set(\"template\", input.template);\n if (input.label !== undefined) search.set(\"label\", input.label);\n // Org-scoped hosts (cloud, self-host, cloudflare) serve the console under an\n // optional `/<org-slug>` segment. Pin the URL to the executor's bound org so\n // it opens that org directly instead of relying on the browser's last-active\n // org (which `OrgSlugGate` would otherwise canonicalize a bare URL to). When\n // no slug is known (CLI, local, non-request callers) we emit the bare path.\n const orgPrefix = orgSlug !== undefined && orgSlug.length > 0 ? `/${orgSlug}` : \"\";\n const path = `${orgPrefix}/integrations/${encodeURIComponent(input.integration)}?${search.toString()}`;\n if (webBaseUrl === undefined || webBaseUrl.length === 0) return path;\n return new URL(path, webBaseUrl.endsWith(\"/\") ? webBaseUrl : `${webBaseUrl}/`).toString();\n};\n\nconst oauthClientCreateHandoffUrl = (\n webBaseUrl: string | undefined,\n orgSlug: string | undefined,\n input: typeof OAuthCreateClientHandoffInput.Type,\n): string => {\n // `oauthClient=1` flips the integration's Add-account flow straight into the\n // Register-OAuth-app form; the rest pre-fill its NON-secret fields. The client\n // secret is deliberately absent: the human types it in the browser, so it is\n // never placed in this URL (nor in the agent's context). Same builder shape as\n // `connectionCreateHandoffUrl`.\n const search = new URLSearchParams({ addAccount: \"1\", oauthClient: \"1\" });\n if (input.owner !== undefined) search.set(\"owner\", input.owner);\n if (input.slug !== undefined) search.set(\"clientSlug\", input.slug);\n if (input.grant !== undefined) search.set(\"grant\", input.grant);\n if (input.clientId !== undefined) search.set(\"clientId\", input.clientId);\n if (input.authorizationUrl !== undefined) search.set(\"authorizationUrl\", input.authorizationUrl);\n if (input.tokenUrl !== undefined) search.set(\"tokenUrl\", input.tokenUrl);\n if (input.resource != null && input.resource.length > 0) search.set(\"resource\", input.resource);\n if (input.label !== undefined) search.set(\"label\", input.label);\n const orgPrefix = orgSlug !== undefined && orgSlug.length > 0 ? `/${orgSlug}` : \"\";\n const path = `${orgPrefix}/integrations/${encodeURIComponent(input.integration)}?${search.toString()}`;\n if (webBaseUrl === undefined || webBaseUrl.length === 0) return path;\n return new URL(path, webBaseUrl.endsWith(\"/\") ? webBaseUrl : `${webBaseUrl}/`).toString();\n};\n\nexport interface CoreToolsPluginOptions {\n readonly webBaseUrl?: string;\n /** The bound org's URL slug, prefixed onto browser-handoff URLs so they open\n * the right org's console (`${webBaseUrl}/<orgSlug>/integrations/...`). */\n readonly orgSlug?: string;\n readonly includeProviders?: boolean;\n}\n\nexport const coreToolsPlugin = definePlugin((options: CoreToolsPluginOptions = {}) => ({\n id: \"core-tools\" as const,\n packageName: \"@executor-js/sdk/core-tools\",\n storage: () => ({}),\n extension: () => ({}),\n\n staticSources: () => [\n {\n id: \"coreTools\",\n kind: \"executor\",\n name: \"Executor\",\n tools: [\n tool({\n name: \"integrations.list\",\n description:\n \"List integrations in the workspace catalog (slug, description, owning plugin kind). Connections authenticate against these.\",\n outputSchema: IntegrationsListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.core.integrations.list(), (integrations) => ({\n integrations: integrations.map((i) => ({\n slug: String(i.slug),\n description: i.description,\n kind: i.kind,\n canRemove: i.canRemove,\n canRefresh: i.canRefresh,\n })),\n })),\n }),\n tool({\n name: \"integrations.detect\",\n description:\n \"Given a URL, ask every plugin whether it recognizes it, returning best-confidence matches so the UI can pre-fill onboarding for the right plugin.\",\n inputSchema: DetectInputStd,\n outputSchema: DetectOutputStd,\n execute: (input: typeof DetectInput.Type, { ctx }) =>\n Effect.map(ctx.core.integrations.detect(input.url), (results) => ({\n results: results.map((r) => ({\n kind: r.kind,\n confidence: r.confidence,\n endpoint: r.endpoint,\n name: r.name,\n slug: r.slug,\n })),\n })),\n }),\n tool({\n name: \"connections.list\",\n description:\n \"List saved connections (the credential for one integration). Never returns the credential value. Optionally filter by integration or owner. OAuth scopes are summarized as `oauthScopeCount` by default; pass `verbose: true` to include the full `oauthScope` grant string per connection.\",\n inputSchema: ConnectionsListInputStd,\n outputSchema: ConnectionsListOutputStd,\n execute: (input: typeof ConnectionsListInput.Type, { ctx }) =>\n Effect.map(\n ctx.connections.list({\n integration:\n input.integration === undefined\n ? undefined\n : IntegrationSlug.make(input.integration),\n owner: input.owner === undefined ? undefined : (input.owner as Owner),\n }),\n (connections) => ({\n connections: connections.map((connection) =>\n connectionToListItem(connection, input.verbose === true),\n ),\n }),\n ),\n }),\n tool({\n name: \"connections.create\",\n description:\n 'Low-level create or replace for a saved connection from provider item references. For a no-auth integration (public MCP server, public REST API), pass `template: \"none\"` with no `from`/`inputs` to wire it up directly. For normal API keys/tokens, use `connections.createHandoff` so the user enters the credential in the web UI. OAuth credentials should use `oauth.start`.',\n inputSchema: ConnectionCreateInputStd,\n outputSchema: ConnectionOutputStd,\n // Creating a connection binds a credential reference and roots a new\n // tool catalog: every tool that connection produces then becomes\n // callable. Even the no-auth (`template: \"none\"`) path pulls tools\n // from an arbitrary endpoint. Prompt-injected code could silently\n // wire an attacker-chosen integration or credential, so this is\n // approval-gated (the v1 `sources.configure` carried the same guard).\n annotations: { requiresApproval: true },\n execute: (input: typeof ConnectionCreateInput.Type, { ctx }) =>\n Effect.map(\n ctx.connections.create(createConnectionInputFromTool(input)),\n connectionToOutput,\n ),\n }),\n tool({\n name: \"connections.createHandoff\",\n description:\n \"Return a browser URL that opens the Add account flow for one integration. Use this for API keys/tokens so the user enters secrets directly in the web UI instead of sending them through the agent. Optionally preselect owner, auth template, and a non-secret label.\",\n inputSchema: ConnectionCreateHandoffInputStd,\n outputSchema: ConnectionCreateHandoffOutputStd,\n execute: (input: typeof ConnectionCreateHandoffInput.Type) => {\n const url = connectionCreateHandoffUrl(options.webBaseUrl, options.orgSlug, input);\n return Effect.succeed({\n url,\n instructions:\n \"Ask the user to open this URL and add the account in the Executor web UI. Do not ask them to paste the credential value into chat. After they finish, call connections.list for the integration to discover the created connection.\",\n });\n },\n }),\n tool({\n name: \"connections.remove\",\n description:\n \"Remove a saved connection and its produced tools by owner, integration, and connection name.\",\n inputSchema: ConnectionRefInputStd,\n outputSchema: RemovedOutputStd,\n // Deleting a connection drops it and every tool it produced, which\n // prompt-injected code could use to disrupt an integration or force a\n // re-add flow. Approval-gated, matching v1 `sources.remove`.\n annotations: { requiresApproval: true },\n execute: (input: typeof ConnectionRefInput.Type, { ctx }) =>\n Effect.map(ctx.connections.remove(connectionRefFromInput(input)), () => ({\n removed: true,\n })),\n }),\n tool({\n name: \"connections.refresh\",\n description:\n \"Re-run an integration's tool production for a saved connection, replacing that connection's persisted tools.\",\n inputSchema: ConnectionRefInputStd,\n outputSchema: ConnectionsRefreshOutputStd,\n // Refresh replaces a connection's persisted tool set; for a mutable\n // upstream (an MCP server whose catalog can change) this can swap in\n // different tools without confirmation. Approval-gated, matching v1\n // `sources.refresh`.\n annotations: { requiresApproval: true },\n execute: (input: typeof ConnectionRefInput.Type, { ctx }) =>\n Effect.map(ctx.connections.refresh(connectionRefFromInput(input)), (tools) => ({\n tools: tools.map(toolToOutput),\n })),\n }),\n // removed: tools.list — the cross-connection tool catalog is an\n // executor-surface read, not exposed on PluginCtx.\n ...(options.includeProviders === false\n ? []\n : [\n tool({\n name: \"providers.list\",\n description:\n \"List registered credential provider keys (the storage backends, not API vendors). Use `providers.items` to browse a backend's entries.\",\n outputSchema: ProvidersOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.providers.list(), (providers) => ({\n providers: providers.map((p) => String(p)),\n })),\n }),\n tool({\n name: \"providers.items\",\n description:\n \"Browse a credential provider's items for discovery (pick a 1Password / keychain entry). Returns opaque ids and labels, never values.\",\n inputSchema: ProviderItemsInputStd,\n outputSchema: ProviderItemsOutputStd,\n execute: (input: typeof ProviderItemsInput.Type, { ctx }) =>\n Effect.map(ctx.providers.items(ProviderKey.make(input.provider)), (items) => ({\n items: items.map((i) => ({ id: String(i.id), name: i.name })),\n })),\n }),\n ]),\n tool({\n name: \"oauth.clients.list\",\n description:\n \"List registered OAuth clients visible to this executor. Returns metadata only; client secrets are never returned.\",\n outputSchema: OAuthClientsListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.oauth.listClients(), (clients) => ({\n clients: clients.map((client) => ({\n owner: client.owner,\n slug: String(client.slug),\n grant: client.grant,\n authorizationUrl: client.authorizationUrl,\n tokenUrl: client.tokenUrl,\n resource: client.resource ?? null,\n clientId: client.clientId,\n })),\n })),\n }),\n tool({\n name: \"oauth.clients.create\",\n description:\n \"Register or replace an owner-scoped OAuth client WITHOUT a client secret: a PUBLIC client (PKCE / authorization_code) or a discovery-prefill placeholder. To register a CONFIDENTIAL client that has a secret, call `oauth.clients.createHandoff` instead so the human enters the secret in the web UI; never pass a client secret through this tool.\",\n inputSchema: OAuthCreateClientInputStd,\n outputSchema: OAuthClientOutputRefStd,\n // This persists an OAuth client and REPLACES on slug collision. It\n // takes NO client secret: a secret would have to travel through the\n // agent's context window, so a confidential app is registered by the\n // human via `oauth.clients.createHandoff`. An empty secret registers a\n // PUBLIC client. The remaining risk is the write itself: prompt-injected\n // code could register a client with an attacker-controlled\n // authorizationUrl/tokenUrl, then drive `oauth.start` to mint a\n // connection and route the user's tokens to the attacker. The\n // highest-value gate here; matches v1 `sources.bindings.set`, which\n // guarded credential writes.\n annotations: { requiresApproval: true },\n execute: (input: typeof OAuthCreateClientInput.Type, { ctx }) =>\n Effect.map(\n ctx.oauth.createClient({\n owner: input.owner as Owner,\n slug: OAuthClientSlug.make(input.slug),\n authorizationUrl: input.authorizationUrl,\n tokenUrl: input.tokenUrl,\n grant: input.grant,\n clientId: input.clientId,\n // No secret crosses the agent boundary; an empty secret registers\n // a public client. Confidential clients go through\n // `oauth.clients.createHandoff`.\n clientSecret: \"\",\n resource: input.resource ?? null,\n }),\n (client) => ({ client: String(client) }),\n ),\n }),\n tool({\n name: \"oauth.clients.createHandoff\",\n description:\n \"Return a browser URL that opens the Register-OAuth-app form for one integration, pre-filled with the non-secret fields (client id, endpoints, grant). Use this for any CONFIDENTIAL OAuth app: the user types the client secret directly in the web UI instead of sending it through the agent. After they register the app, call `oauth.clients.list` to discover its owner and slug, then `oauth.start`.\",\n inputSchema: OAuthCreateClientHandoffInputStd,\n outputSchema: OAuthCreateClientHandoffOutputStd,\n // Pure URL builder: no DB write, no token, no secret. This is the SAFE\n // path (it routes the secret to the human in the browser), so it is\n // deliberately NOT approval-gated, mirroring `connections.createHandoff`.\n execute: (input: typeof OAuthCreateClientHandoffInput.Type) => {\n const url = oauthClientCreateHandoffUrl(options.webBaseUrl, options.orgSlug, input);\n return Effect.succeed({\n url,\n instructions:\n \"Ask the user to open this URL and register the OAuth app in the Executor web UI, entering the client secret there. Do not ask them to paste the client secret into chat. After they finish, call oauth.clients.list to find the registered client (owner + slug), then oauth.start.\",\n });\n },\n }),\n tool({\n name: \"oauth.clients.registerDynamic\",\n description:\n \"Register an OAuth client through RFC 7591 Dynamic Client Registration and save the minted client for later `oauth.start` calls.\",\n inputSchema: OAuthRegisterDynamicInputStd,\n outputSchema: OAuthClientOutputRefStd,\n // Same risk class as `oauth.clients.create`: registers a client at a\n // caller-supplied endpoint and persists the minted credentials for\n // later `oauth.start` abuse. Approval-gated. See `oauth.clients.create`.\n annotations: { requiresApproval: true },\n execute: (input: typeof OAuthRegisterDynamicInput.Type, { ctx }) =>\n Effect.map(\n ctx.oauth.registerDynamicClient({\n owner: input.owner as Owner,\n slug: OAuthClientSlug.make(input.slug),\n registrationEndpoint: input.registrationEndpoint,\n authorizationUrl: input.authorizationUrl,\n tokenUrl: input.tokenUrl,\n resource: input.resource ?? null,\n scopes: input.scopes,\n tokenEndpointAuthMethodsSupported: input.tokenEndpointAuthMethodsSupported,\n clientName: input.clientName,\n redirectUri: input.redirectUri,\n originIntegration:\n input.originIntegration == null\n ? null\n : IntegrationSlug.make(input.originIntegration),\n }),\n (client) => ({ client: String(client) }),\n ),\n }),\n tool({\n name: \"oauth.clients.remove\",\n description:\n \"Remove an owner-scoped OAuth client by owner and slug. Existing connections are not cascaded.\",\n inputSchema: OAuthRemoveClientInputStd,\n outputSchema: RemovedOutputStd,\n // Removing a client breaks token refresh for every connection that\n // depends on it (a silent DoS) and can force re-auth through an\n // attacker-supplied replacement. Approval-gated, matching v1\n // `sources.bindings.remove`.\n annotations: { requiresApproval: true },\n execute: (input: typeof OAuthRemoveClientInput.Type, { ctx }) =>\n Effect.map(\n ctx.oauth.removeClient(input.owner as Owner, OAuthClientSlug.make(input.slug)),\n () => ({ removed: true }),\n ),\n }),\n tool({\n name: \"oauth.probe\",\n description:\n \"Discover OAuth authorization-server metadata from an issuer or protected-resource URL so client registration can be pre-filled.\",\n inputSchema: OAuthProbeInputStd,\n outputSchema: OAuthProbeOutputStd,\n execute: (input: typeof OAuthProbeInput.Type, { ctx }) =>\n Effect.map(ctx.oauth.probe({ url: input.url }), (result) => ({\n authorizationUrl: result.authorizationUrl,\n tokenUrl: result.tokenUrl,\n resource: result.resource ?? null,\n scopesSupported: result.scopesSupported,\n registrationEndpoint: result.registrationEndpoint ?? null,\n tokenEndpointAuthMethodsSupported: result.tokenEndpointAuthMethodsSupported,\n })),\n }),\n tool({\n name: \"oauth.start\",\n description:\n \"Start OAuth through a registered client to mint a connection for an integration. `client_credentials` clients return `connected`; authorization-code clients return an authorization URL and state.\",\n inputSchema: OAuthStartInputStd,\n outputSchema: OAuthStartOutputStd,\n // This is the materialization step that turns a registered client\n // into a live connection. For `client_credentials` it completes\n // synchronously (status `connected`) with no browser step, so a\n // prompt-injected call against an attacker-registered client mints a\n // credentialed connection with no human in the loop. The\n // authorization-code path already returns a URL the user must visit,\n // but one gate on the whole tool covers the silent path cleanly.\n annotations: { requiresApproval: true },\n execute: (input: typeof OAuthStartInput.Type, { ctx }) =>\n Effect.map(\n ctx.oauth.start({\n client: OAuthClientSlug.make(input.client),\n clientOwner: input.clientOwner as Owner,\n owner: input.owner as Owner,\n name: ConnectionName.make(input.name),\n integration: IntegrationSlug.make(input.integration),\n template: AuthTemplateSlug.make(input.template),\n identityLabel: input.identityLabel,\n redirectUri: input.redirectUri,\n }),\n (result) =>\n result.status === \"connected\"\n ? {\n status: \"connected\" as const,\n connection: connectionToOutput(result.connection),\n }\n : {\n status: \"redirect\" as const,\n authorizationUrl: result.authorizationUrl,\n state: String(result.state),\n },\n ),\n }),\n tool({\n name: \"oauth.cancel\",\n description:\n \"Cancel an in-flight OAuth authorization-code session by state after the user abandons the flow.\",\n inputSchema: OAuthCancelInputStd,\n outputSchema: CancelledOutputStd,\n execute: (input: typeof OAuthCancelInput.Type, { ctx }) =>\n Effect.map(ctx.oauth.cancel(OAuthState.make(input.state)), () => ({ cancelled: true })),\n }),\n tool({\n name: \"policies.list\",\n description:\n \"List tool policies (approve / require_approval / block) for org and user owners, in evaluation order.\",\n outputSchema: PoliciesListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.core.policies.list(), (policies) => ({\n policies: policies.map((p) => ({\n id: String(p.id),\n owner: p.owner,\n pattern: p.pattern,\n action: p.action,\n position: p.position,\n })),\n })),\n }),\n tool({\n name: \"policies.create\",\n description:\n \"Create a tool policy. `pattern` matches a tool address tail (`integration.connection.tool`, `integration.*`, `*`); `action` is approve/require_approval/block. `owner` is org (workspace guardrail) or user (personal).\",\n inputSchema: PolicyCreateInputStd,\n outputSchema: PolicyOutputStd,\n // A policy decides which tools run without confirmation, so creating\n // one can silence every other approval gate (e.g. `approve *`). It\n // must itself require approval, otherwise prompt-injected code could\n // disable approvals by writing its own bypass policy.\n annotations: { requiresApproval: true },\n execute: (input: typeof PolicyCreateInput.Type, { ctx }) =>\n Effect.map(\n ctx.core.policies.create({\n owner: input.owner as Owner,\n pattern: input.pattern,\n action: input.action,\n }),\n (p) => ({\n id: String(p.id),\n owner: p.owner,\n pattern: p.pattern,\n action: p.action,\n position: p.position,\n }),\n ),\n }),\n tool({\n name: \"policies.update\",\n description: \"Update a tool policy's pattern and/or action by id + owner.\",\n inputSchema: PolicyUpdateInputStd,\n outputSchema: PolicyOutputStd,\n // Editing a policy can broaden a pattern or flip an action to\n // `approve`, weakening an approval gate just as creation can, so it\n // requires approval too. See `policies.create`.\n annotations: { requiresApproval: true },\n execute: (input: typeof PolicyUpdateInput.Type, { ctx }) =>\n Effect.map(\n ctx.core.policies.update({\n id: input.id,\n owner: input.owner as Owner,\n pattern: input.pattern,\n action: input.action,\n }),\n (p) => ({\n id: String(p.id),\n owner: p.owner,\n pattern: p.pattern,\n action: p.action,\n position: p.position,\n }),\n ),\n }),\n tool({\n name: \"policies.remove\",\n description: \"Remove a tool policy by id + owner.\",\n inputSchema: PolicyRemoveInputStd,\n outputSchema: RemovedOutputStd,\n // Removing a policy can drop a `block` or `require_approval`\n // guardrail, so deletion is also approval-gated. See\n // `policies.create`.\n annotations: { requiresApproval: true },\n execute: (input: typeof PolicyRemoveInput.Type, { ctx }) =>\n Effect.map(\n ctx.core.policies.remove({\n id: input.id,\n owner: input.owner as Owner,\n }),\n () => ({ removed: true }),\n ),\n }),\n ],\n },\n ],\n}));\n","// ---------------------------------------------------------------------------\n// OAuth service implementation — the runtime behind `executor.oauth` and\n// `ctx.oauth`.\n//\n// v2 model: a client is a registered app carrying its own endpoints; running\n// its flow mints a Connection. The client + in-flight session rows are\n// owner-scoped core tables; minted access tokens persist through the default\n// writable credential provider; tools are produced by `mintOAuthConnection`\n// (which the executor wires to the connection-create + tool-production path).\n//\n// Milestone 2: `start` / `complete` are wired. `start` generates PKCE + a\n// branded state, persists an `oauth_session`, and returns the authorize URL\n// (authorization_code) or exchanges client credentials immediately. `complete`\n// redeems the session, exchanges the code, and mints the connection.\n// ---------------------------------------------------------------------------\n\nimport { Duration, Effect, Layer, Option, Schema } from \"effect\";\nimport { FetchHttpClient, type HttpClient } from \"effect/unstable/http\";\n\nimport type { Connection } from \"./connection\";\nimport type { IFumaClient, StorageFailure } from \"./fuma-runtime\";\nimport { StorageError } from \"./fuma-runtime\";\nimport {\n AuthTemplateSlug,\n ConnectionName,\n IntegrationSlug,\n OAuthClientSlug,\n OAuthState,\n Owner,\n ProviderItemId,\n} from \"./ids\";\nimport {\n OAuthCompleteError,\n OAuthProbeError,\n OAuthRegisterDynamicError,\n OAuthSessionNotFoundError,\n OAuthStartError,\n type ConnectResult,\n type CreateOAuthClientInput,\n type OAuthClientOrigin,\n type OAuthClientSummary,\n type OAuthCompleteInput,\n type OAuthGrant,\n type OAuthProbeInput,\n type OAuthProbeResult,\n type OAuthService,\n type OAuthStartInput,\n type RegisterDynamicClientInput,\n} from \"./oauth-client\";\nimport type { OwnerBinding } from \"./plugin\";\nimport type { CredentialProvider } from \"./provider\";\nimport {\n discoverAuthorizationServerMetadata,\n discoverProtectedResourceMetadata,\n OAuthDiscoveryError,\n registerDynamicClient as registerDynamicClientDcr,\n} from \"./oauth-discovery\";\nimport {\n assertSupportedOAuthEndpointUrl,\n buildAuthorizationUrl,\n providerAuthorizeExtras,\n createOAuthState,\n createPkceCodeChallenge,\n createPkceCodeVerifier,\n exchangeAuthorizationCode,\n exchangeClientCredentials,\n rebindTokenEndpointHostToCallbackDomain,\n type OAuth2TokenResponse,\n type OAuthEndpointUrlPolicy,\n} from \"./oauth-helpers\";\nimport { OAUTH2_SESSION_TTL_MS, encodeOAuthCallbackState } from \"./oauth\";\n\n/** Connection-minting input for the OAuth flow — extends a connection create\n * with the OAuth lifecycle fields (client slug, refresh material, expiry,\n * granted scope). The executor's `mintOAuthConnection` writes these onto the\n * `connection` row and produces the connection's tools. */\nexport interface MintOAuthConnectionInput {\n readonly owner: Owner;\n readonly name: ConnectionName;\n readonly integration: IntegrationSlug;\n readonly template: AuthTemplateSlug;\n readonly identityLabel?: string | null;\n /** Credential provider key + item id the access token is stored under. */\n readonly provider: string;\n readonly itemId: string;\n readonly oauthClient: OAuthClientSlug;\n /** The owner of `oauthClient` (persisted so refresh loads it by explicit owner). */\n readonly oauthClientOwner: Owner;\n readonly refreshItemId: string | null;\n readonly expiresAt: number | null;\n readonly oauthScope: string | null;\n /** Per-connection override for the token endpoint, persisted only when the\n * code was redeemed at a region other than the client's configured token\n * host (Datadog multi-site). Null means refresh uses the client's token URL. */\n readonly oauthTokenUrl?: string | null;\n}\n\n/** The OAuth scope policy for a `(integration, template)`. Either the\n * integration declares the scopes to request (`scopes`, possibly empty — an\n * empty set requests no scopes), or it declares none and the request scopes\n * are discovered from the server's metadata at connect (`discover`, used by\n * MCP). The two are mutually exclusive by construction. */\nexport type OAuthScopePolicy =\n | { readonly kind: \"scopes\"; readonly scopes: readonly string[] }\n | { readonly kind: \"discover\" };\n\n/** Everything the OAuth service needs from the executor: fuma access for the\n * owned `oauth_client` / `oauth_session` tables, the default credential\n * provider for minted tokens, a `mintOAuthConnection` callback (writes the\n * connection row + produces tools), the owner binding, and the redirect base. */\nexport interface OAuthServiceDeps {\n readonly fuma: IFumaClient;\n readonly owner: OwnerBinding;\n readonly tenant: string;\n readonly subject: string | null;\n readonly ownedKeys: (owner: Owner) => {\n readonly tenant: string;\n readonly owner: Owner;\n readonly subject: string;\n };\n readonly defaultWritableProvider: () => CredentialProvider | null;\n /** Write the connection row with OAuth lifecycle fields + produce its tools. */\n readonly mintOAuthConnection: (\n input: MintOAuthConnectionInput,\n ) => Effect.Effect<Connection, StorageFailure>;\n /**\n * Resolve the OAuth scope policy for a `(integration, template)`:\n * - `{ kind: \"scopes\", scopes }`: the scopes the integration's auth template\n * DECLARES (e.g. an OpenAPI bundle's authentication-template scope union),\n * NOT the scopes frozen on a specific `oauth_client` row. These are\n * requested verbatim at connect (`start`); an empty set requests none.\n * - `{ kind: \"discover\" }`: the integration declares no scopes, so `start`\n * discovers the request scopes from the server's RFC 9728 / RFC 8414\n * metadata. Used by server-targeting integrations (MCP) whose scopes live\n * on the server rather than in a template.\n */\n readonly resolveOAuthScopePolicy: (\n integration: IntegrationSlug,\n template: AuthTemplateSlug,\n ) => Effect.Effect<OAuthScopePolicy, StorageFailure>;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n readonly fetch?: typeof globalThis.fetch;\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n /**\n * The OAuth callback URL (`${webBaseUrl}${mountPrefix}/oauth/callback`) the host\n * serves and sends to providers on every authorization request + DCR registration.\n * The path carries the host's API mount prefix (cloud: `/api`; root-mounted\n * hosts like local: none), so it matches the route that serves the callback.\n *\n * REQUIRED and EXPLICIT — there is no localhost default. Pass `null` only when\n * the host genuinely has no redirect callback (e.g. a pure client-credentials\n * or non-HTTP context); the redirect-requiring flows (`start` for\n * `authorization_code`, `registerDynamicClient`) then fail loudly instead of\n * silently handing the provider a wrong `http://127.0.0.1/callback`. Hosts\n * that serve OAuth MUST derive this from the request origin / web base URL.\n */\n readonly redirectUri: string | null;\n /** URL selected organization slug to round-trip through OAuth `state`. */\n readonly callbackStateOrgSlug?: string | null;\n}\n\ntype LooseDb = {\n readonly create: (name: string, value: Record<string, unknown>) => Promise<unknown>;\n readonly deleteMany: (name: string, options: unknown) => Promise<void>;\n readonly findFirst: (name: string, options: unknown) => Promise<Record<string, unknown> | null>;\n readonly findMany: (\n name: string,\n options: unknown,\n ) => Promise<readonly Record<string, unknown>[]>;\n};\nconst looseDb = (db: unknown): LooseDb => db as LooseDb;\n\n/** Where an OAuth-minted access token is stored in the default provider. The\n * refresh token lives at the same id with a `:refresh` suffix. */\nconst accessItemId = (owner: Owner, integration: IntegrationSlug, name: ConnectionName): string =>\n `oauth:${owner}:${integration}:${name}`;\nconst refreshItemIdFor = (accessId: string): string => `${accessId}:refresh`;\n\n/** Order-preserving de-duplication of a scope list. */\nconst dedupeScopes = (scopes: readonly string[]): readonly string[] => [...new Set(scopes)];\n\nconst recordedOAuthScope = (\n token: OAuth2TokenResponse,\n requestedScopes: readonly string[],\n): string | null => {\n if (token.scope == null) return requestedScopes.join(\" \") || null;\n\n const granted = token.scope.split(/\\s+/).filter(Boolean);\n const coveredByRefreshToken =\n token.refresh_token && requestedScopes.includes(\"offline_access\") ? [\"offline_access\"] : [];\n const recorded = dedupeScopes([...granted, ...coveredByRefreshToken]);\n return recorded.join(\" \") || null;\n};\n\nconst decodeJsonPayload = Schema.decodeUnknownOption(Schema.UnknownFromJsonString);\n\n/** Extract the persisted `requestedScopes` from an `oauth_session.payload`. The\n * jsonColumn may surface as a parsed object (in-memory backends) or a JSON\n * string (serialized backends); decode strings before reading. Returns `null`\n * for legacy sessions written before `requestedScopes` was persisted, so\n * `complete` can fall back to the client's scopes. */\nconst requestedScopesFromPayload = (payload: unknown): readonly string[] | null => {\n const decoded =\n typeof payload === \"string\"\n ? decodeJsonPayload(payload).pipe(Option.getOrElse(() => payload))\n : payload;\n if (decoded === null || typeof decoded !== \"object\") return null;\n const value = (decoded as Record<string, unknown>).requestedScopes;\n return Array.isArray(value) ? value.filter((s): s is string => typeof s === \"string\") : null;\n};\n\n/** Read the app owner `start` recorded on the session payload. Null when absent\n * (same-owner connects, or sessions written before this field), so `complete`\n * falls back to the session owner. */\nconst clientOwnerFromPayload = (payload: unknown): Owner | null => {\n const decoded =\n typeof payload === \"string\"\n ? decodeJsonPayload(payload).pipe(Option.getOrElse(() => payload))\n : payload;\n if (decoded === null || typeof decoded !== \"object\") return null;\n const value = (decoded as Record<string, unknown>).clientOwner;\n return value === \"user\" || value === \"org\" ? value : null;\n};\n\n/** Narrow a stored `grant` string to the `OAuthGrant` union, or `null` when the\n * value is neither known grant. EXPLICIT — there is no silent fallback to\n * `authorization_code`; an unknown grant means a corrupt row and callers that\n * drive token exchange (`loadClient`) must fail loudly rather than guessing. */\nconst parseGrant = (grant: unknown): OAuthGrant | null =>\n grant === \"client_credentials\" || grant === \"authorization_code\" ? grant : null;\n\nconst parseOAuthClientOrigin = (row: {\n readonly slug?: unknown;\n readonly grant?: unknown;\n readonly resource?: unknown;\n readonly origin_kind?: unknown;\n readonly origin_integration?: unknown;\n}): OAuthClientOrigin => {\n if (row.origin_kind === \"dynamic_client_registration\") {\n return {\n kind: \"dynamic_client_registration\",\n integration:\n row.origin_integration == null\n ? null\n : IntegrationSlug.make(String(row.origin_integration)),\n };\n }\n const slug = row.slug == null ? \"\" : String(row.slug);\n const resource = row.resource == null ? \"\" : String(row.resource);\n if (\n row.origin_kind == null &&\n row.grant === \"authorization_code\" &&\n /(^|[-_])mcp($|[-_])/.test(slug) &&\n /(^|\\/)mcp($|[/?#])/.test(resource)\n ) {\n return { kind: \"dynamic_client_registration\", integration: null };\n }\n return { kind: \"manual\" };\n};\n\ninterface LoadedOAuthClient {\n readonly slug: string;\n readonly authorizationUrl: string;\n readonly tokenUrl: string;\n readonly grant: OAuthGrant;\n readonly clientId: string;\n /** Resolved literal secret (read from the provider via the stored item id). */\n readonly clientSecret: string;\n readonly resource: string | null;\n}\n\n/** Where an OAuth app's client secret is stored in the default writable\n * provider — derived solely from the app's (owner, slug) identity. */\nconst clientSecretItemId = (owner: Owner, slug: OAuthClientSlug): string =>\n `oauth-client:${owner}:${slug}:secret`;\n\nconst expiresAtFrom = (token: OAuth2TokenResponse): number | null =>\n typeof token.expires_in === \"number\" ? Date.now() + token.expires_in * 1000 : null;\n\n/** Error message surfaced when a redirect-requiring OAuth flow runs on an\n * executor that was constructed without a `redirectUri`. Previously this path\n * silently used `http://127.0.0.1/callback`, which providers stored as the\n * client's callback and then rejected (or worse, accepted, handing tokens to\n * localhost). Fail loudly so the misconfiguration is caught at the call site. */\nconst REDIRECT_URI_REQUIRED_MESSAGE =\n \"OAuth redirect flow requires a configured redirectUri, but none was provided \" +\n \"to the executor. Pass `redirectUri` to createExecutor (hosts derive it from \" +\n \"the web base URL / request origin as `${webBaseUrl}${mountPrefix}/oauth/callback`).\";\n\nconst canonicalUrlString = (value: string): string => {\n const url = new URL(value.trim());\n url.hash = \"\";\n return url.toString();\n};\n\nconst isWellKnownOAuthMetadataUrl = (value: string): boolean => {\n const path = new URL(value.trim()).pathname.toLowerCase();\n return (\n path.includes(\"/.well-known/oauth-authorization-server\") ||\n path.includes(\"/.well-known/openid-configuration\") ||\n path.includes(\"/.well-known/oauth-protected-resource\")\n );\n};\n\nconst validateSupportedEndpoint = (\n value: string,\n label: string,\n endpointUrlPolicy: OAuthEndpointUrlPolicy | undefined,\n): Effect.Effect<void, StorageFailure> =>\n Effect.try({\n try: () => assertSupportedOAuthEndpointUrl(value, label, endpointUrlPolicy),\n catch: (cause) =>\n new StorageError({\n message: `Invalid OAuth client endpoint configuration: ${label} must use https: or loopback http:.`,\n cause,\n }),\n }).pipe(Effect.asVoid);\n\nconst validateClientEndpoints = (\n input: CreateOAuthClientInput,\n endpointUrlPolicy: OAuthEndpointUrlPolicy | undefined,\n): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n yield* validateSupportedEndpoint(input.tokenUrl, \"token_url\", endpointUrlPolicy);\n if (input.resource != null && input.resource.trim().length > 0) {\n yield* validateSupportedEndpoint(input.resource, \"resource\", endpointUrlPolicy);\n }\n if (input.grant !== \"authorization_code\") return;\n yield* validateSupportedEndpoint(\n input.authorizationUrl,\n \"authorization_url\",\n endpointUrlPolicy,\n );\n if (isWellKnownOAuthMetadataUrl(input.authorizationUrl)) {\n return yield* new StorageError({\n message:\n \"Invalid OAuth client endpoint configuration: authorization_url must be the OAuth authorization endpoint, not a .well-known metadata URL.\",\n cause: undefined,\n });\n }\n if (canonicalUrlString(input.authorizationUrl) === canonicalUrlString(input.tokenUrl)) {\n return yield* new StorageError({\n message:\n \"Invalid OAuth client endpoint configuration: authorization_url must not equal token_url.\",\n cause: undefined,\n });\n }\n });\n\nexport const makeOAuthService = (deps: OAuthServiceDeps): OAuthService => {\n const httpClientLayer = deps.httpClientLayer ?? FetchHttpClient.layer;\n const fetch = deps.fetch;\n // EXPLICIT — no localhost default. `null` means this executor has no OAuth\n // callback; redirect-requiring flows fail loudly via `requireRedirectUri`.\n const redirectUri = deps.redirectUri;\n\n // Caps on server-controlled discovery input — a hostile or buggy server must\n // not be able to hang `oauth.start` or overflow the authorize URL.\n const MAX_DISCOVERY_AUTH_SERVERS = 3; // AS-failover lists are tiny in practice\n const MAX_DISCOVERED_SCOPES = 100; // far beyond any realistic authorization template\n const capScopes = (scopes: readonly string[]): readonly string[] =>\n dedupeScopes(scopes).slice(0, MAX_DISCOVERED_SCOPES);\n\n // Discover the scopes to request when the integration declares none — only\n // reached for integrations that opt in (MCP-style). The resource's own RFC\n // 9728 `scopes_supported` is authoritative when present, even when empty (§2\n // defines the field; §7.2 cautions against requesting more than it lists).\n // Only when the resource is SILENT do we read the scopes advertised by the\n // authorization servers it NAMES (RFC 8414) — we never probe arbitrary URLs.\n const discoverScopesForResource = (\n resource: string | null,\n ): Effect.Effect<readonly string[], OAuthDiscoveryError> =>\n Effect.gen(function* () {\n if (resource == null) {\n return yield* new OAuthDiscoveryError({\n message: \"Cannot discover OAuth scopes: the client has no resource configured\",\n });\n }\n // `httpClientLayer` flows through `options` so discovery uses the host's\n // configured client (discovery self-provides from `options.httpClientLayer`).\n const discoveryOptions = { endpointUrlPolicy: deps.endpointUrlPolicy, httpClientLayer };\n\n const protectedResource = yield* discoverProtectedResourceMetadata(\n resource,\n discoveryOptions,\n );\n const resourceScopes = protectedResource?.metadata.scopes_supported;\n if (resourceScopes !== undefined) return capScopes(resourceScopes);\n\n // The resource is silent on scopes — read them from the authorization\n // servers it names, in order. An advertised list is authoritative even\n // when empty. Any AS we cannot read clean RFC 8414 metadata from —\n // unreachable, 404, malformed, or issuer-mismatched — contributes nothing\n // and we move on (mirroring the dynamic-registration discovery path); if\n // none advertise scopes we request none and let the AS apply its defaults\n // (RFC 8414 metadata is optional, so its absence is not a failure). The\n // list is server-controlled, so cap how many of its hosts we probe.\n for (const issuer of (protectedResource?.metadata.authorization_servers ?? []).slice(\n 0,\n MAX_DISCOVERY_AUTH_SERVERS,\n )) {\n const authServer = yield* discoverAuthorizationServerMetadata(\n issuer,\n discoveryOptions,\n ).pipe(Effect.catchTag(\"OAuthDiscoveryError\", () => Effect.succeed(null)));\n const scopes = authServer?.metadata.scopes_supported;\n if (scopes !== undefined) return capScopes(scopes);\n }\n\n return [];\n }).pipe(\n // Bound the whole sequence (PRM + up to MAX_DISCOVERY_AUTH_SERVERS AS\n // fetches, each with its own request timeout). 30s is larger than a single\n // request timeout so it bounds the sequence, not a slow-but-valid request.\n Effect.timeoutOrElse({\n duration: Duration.seconds(30),\n orElse: () =>\n Effect.fail(\n new OAuthDiscoveryError({\n message: \"OAuth scope discovery timed out\",\n cause: \"timeout\",\n }),\n ),\n }),\n );\n\n // -----------------------------------------------------------------------\n // createClient — write the oauth_client row.\n // -----------------------------------------------------------------------\n const createClient = (\n input: CreateOAuthClientInput,\n ): Effect.Effect<OAuthClientSlug, StorageFailure> =>\n Effect.gen(function* () {\n yield* validateClientEndpoints(input, deps.endpointUrlPolicy);\n const keys = yield* Effect.try({\n try: () => deps.ownedKeys(input.owner),\n catch: (cause) =>\n new StorageError({\n message: \"Cannot write oauth_client for owner without a subject\",\n cause,\n }),\n });\n const now = new Date();\n\n // Store the secret out-of-band in the default writable provider; the row\n // keeps only its item id. A public/PKCE client (empty secret) stores null\n // — there is no plaintext column to fall back to (the schema dropped it).\n let clientSecretItemIdValue: string | null = null;\n if (input.clientSecret.length > 0) {\n const provider = deps.defaultWritableProvider();\n if (!provider || !provider.set) {\n return yield* new StorageError({\n message:\n \"No default writable credential provider is registered to store the OAuth client secret.\",\n cause: undefined,\n });\n }\n clientSecretItemIdValue = clientSecretItemId(input.owner, input.slug);\n yield* provider.set(ProviderItemId.make(clientSecretItemIdValue), input.clientSecret);\n }\n\n yield* deps.fuma\n .use(\"oauth_client.deleteExisting\", (db) =>\n looseDb(db).deleteMany(\"oauth_client\", {\n where: (b: any) =>\n b.and(b(\"owner\", \"=\", input.owner), b(\"slug\", \"=\", String(input.slug))),\n }),\n )\n .pipe(Effect.catch(() => Effect.void));\n yield* deps.fuma.use(\"oauth_client.create\", (db) =>\n looseDb(db).create(\"oauth_client\", {\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n slug: String(input.slug),\n authorization_url: input.authorizationUrl,\n token_url: input.tokenUrl,\n grant: input.grant,\n client_id: input.clientId,\n client_secret_item_id: clientSecretItemIdValue,\n resource: input.resource ?? null,\n origin_kind: input.origin?.kind ?? \"manual\",\n origin_integration:\n input.origin?.kind === \"dynamic_client_registration\"\n ? input.origin.integration == null\n ? null\n : String(input.origin.integration)\n : null,\n created_at: now,\n }),\n );\n return input.slug;\n });\n\n // -----------------------------------------------------------------------\n // removeClient — permanently delete an owner-scoped oauth_client row.\n //\n // Mirrors createClient's deleteExisting filter (same (owner, slug) key) but\n // does NOT swallow storage errors: createClient pipes `.catch(() =>\n // Effect.void)` because a missing prior row is fine on upsert, whereas a real\n // removal must surface a storage failure loudly. The owner policy on\n // `oauth_client` narrows visibility, so a cross-subject user row cannot be\n // deleted. `deleteMany` is idempotent (no matching row -> no-op), so removing\n // an already-gone client returns success — acceptable for a delete. The\n // connection rows that referenced the slug keep their stored value and fail at\n // the next token refresh, prompting a reconnect (graceful degradation; this\n // op never cascades into connections).\n // -----------------------------------------------------------------------\n const removeClient = (owner: Owner, slug: OAuthClientSlug): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n yield* deps.fuma\n .use(\"oauth_client.delete\", (db) =>\n looseDb(db).deleteMany(\"oauth_client\", {\n where: (b: any) => b.and(b(\"owner\", \"=\", owner), b(\"slug\", \"=\", String(slug))),\n }),\n )\n .pipe(Effect.asVoid);\n // Best-effort: drop the secret from the provider so it isn't orphaned.\n const provider = deps.defaultWritableProvider();\n if (provider?.delete) {\n yield* provider\n .delete(ProviderItemId.make(clientSecretItemId(owner, slug)))\n .pipe(Effect.catch(() => Effect.void));\n }\n });\n\n // -----------------------------------------------------------------------\n // registerDynamicClient — RFC 7591 Dynamic Client Registration.\n //\n // POSTs the server's registration_endpoint to mint a client_id (public,\n // PKCE-only, no secret when the server allows `none`; else\n // `client_secret_post`), then persists it through createClient's path. The\n // user pastes NO client id/secret — that is the point. The minted secret is\n // never returned over the read surface.\n // -----------------------------------------------------------------------\n // DCR auth-method negotiation. This is an EXPLICIT, documented choice (not a\n // silent guess): a Dynamic Client Registration ALWAYS mints a public PKCE\n // client — `none` when the server advertises nothing or lists `none`, and\n // `client_secret_post` only when the server's advertised methods exclude\n // `none` (so a confidential secret is mandatory). Static clients never reach\n // here; they require an explicit grant + secret in `createClient`.\n const pickDcrAuthMethod = (\n advertised: readonly string[] | undefined,\n ): \"none\" | \"client_secret_post\" =>\n !advertised || advertised.length === 0 || advertised.includes(\"none\")\n ? \"none\"\n : \"client_secret_post\";\n\n const registerDynamicClient = (\n input: RegisterDynamicClientInput,\n ): Effect.Effect<OAuthClientSlug, OAuthRegisterDynamicError | StorageFailure> =>\n Effect.gen(function* () {\n const flowRedirectUri = input.redirectUri ?? redirectUri;\n // DCR registers our callback as the client's redirect_uri — fail loudly\n // if the executor has none rather than registering a localhost URL.\n if (flowRedirectUri == null) {\n return yield* new OAuthRegisterDynamicError({\n message: REDIRECT_URI_REQUIRED_MESSAGE,\n });\n }\n const authMethod = pickDcrAuthMethod(input.tokenEndpointAuthMethodsSupported);\n const information = yield* registerDynamicClientDcr(\n {\n registrationEndpoint: input.registrationEndpoint,\n metadata: {\n client_name: input.clientName,\n redirect_uris: [flowRedirectUri],\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: authMethod,\n scope: input.scopes.length > 0 ? input.scopes.join(\" \") : undefined,\n },\n },\n { httpClientLayer, endpointUrlPolicy: deps.endpointUrlPolicy },\n ).pipe(\n Effect.mapError(\n (cause) =>\n new OAuthRegisterDynamicError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuthDiscoveryError carries a typed `message` field\n message: `Dynamic Client Registration failed: ${cause.message}`,\n }),\n ),\n );\n\n // Persist the minted client. DCR-minted public clients have no secret; we\n // store \"\" so the PKCE-only token exchange omits `client_secret`.\n // Confidential DCR clients keep the returned secret in the credential\n // provider. The persisted grant is interactive authorization_code.\n // `input.scopes` was already sent to the AS at registration above; the\n // stored client carries no scope set (the integration drives requests).\n yield* createClient({\n owner: input.owner,\n slug: input.slug,\n authorizationUrl: input.authorizationUrl,\n tokenUrl: input.tokenUrl,\n resource: input.resource ?? null,\n grant: \"authorization_code\",\n clientId: information.client_id,\n clientSecret: information.client_secret ?? \"\",\n origin: {\n kind: \"dynamic_client_registration\",\n integration: input.originIntegration ?? null,\n },\n });\n return input.slug;\n });\n\n // -----------------------------------------------------------------------\n // listClients — metadata-only summaries of every client the caller can see.\n // The owner policy on `oauth_client` already narrows `findMany` to the\n // tenant's org rows + this subject's own user rows, so no explicit filter is\n // needed. The `client_secret` column is deliberately never projected.\n // -----------------------------------------------------------------------\n const listClients = (): Effect.Effect<readonly OAuthClientSummary[], StorageFailure> =>\n deps.fuma\n .use(\"oauth_client.findMany\", (db) => looseDb(db).findMany(\"oauth_client\", {}))\n .pipe(\n Effect.flatMap((rows) =>\n Effect.forEach(rows, (row) => {\n const grant = parseGrant(row.grant);\n // EXPLICIT — a row with an unknown grant is corrupt; surface it\n // loudly rather than silently displaying it as authorization_code.\n if (grant === null) {\n return Effect.fail(\n new StorageError({\n message: `oauth_client ${String(row.slug)} has an unknown grant: ${String(row.grant)}`,\n cause: undefined,\n }),\n );\n }\n return Effect.succeed({\n owner: String(row.owner) as Owner,\n slug: OAuthClientSlug.make(String(row.slug)),\n grant,\n authorizationUrl: String(row.authorization_url),\n tokenUrl: String(row.token_url),\n resource: row.resource == null ? null : String(row.resource),\n clientId: String(row.client_id),\n origin: parseOAuthClientOrigin(row),\n } satisfies OAuthClientSummary);\n }),\n ),\n );\n\n // -----------------------------------------------------------------------\n // Load an oauth_client row by (owner, slug).\n // -----------------------------------------------------------------------\n const loadClient = (\n owner: Owner,\n slug: OAuthClientSlug,\n ): Effect.Effect<LoadedOAuthClient | null, StorageFailure> =>\n deps.fuma\n .use(\"oauth_client.findFirst\", (db) =>\n looseDb(db).findFirst(\"oauth_client\", {\n where: (b: any) => b.and(b(\"owner\", \"=\", owner), b(\"slug\", \"=\", String(slug))),\n }),\n )\n .pipe(\n Effect.flatMap((row) => {\n if (!row) return Effect.succeed(null);\n const grant = parseGrant(row.grant);\n // EXPLICIT — this row drives the token exchange. An unknown grant is a\n // corrupt row; fail loudly rather than guessing authorization_code and\n // running the wrong flow.\n if (grant === null) {\n return Effect.fail(\n new StorageError({\n message: `oauth_client ${String(slug)} has an unknown grant: ${String(row.grant)}`,\n cause: undefined,\n }),\n );\n }\n // `client_secret_item_id` is null for DCR-minted / public PKCE clients;\n // the token exchange treats a missing secret as \"public client, omit\n // client_secret\" (see pickClientAuth). A confidential client persisted\n // its secret to the provider in createClient; resolve it back here.\n return Effect.gen(function* () {\n let clientSecret = \"\";\n if (row.client_secret_item_id != null) {\n const provider = deps.defaultWritableProvider();\n if (provider) {\n clientSecret =\n (yield* provider.get(ProviderItemId.make(String(row.client_secret_item_id)))) ??\n \"\";\n }\n }\n return {\n slug: String(row.slug),\n authorizationUrl: String(row.authorization_url),\n tokenUrl: String(row.token_url),\n grant,\n clientId: String(row.client_id),\n clientSecret,\n resource: row.resource == null ? null : String(row.resource),\n } satisfies LoadedOAuthClient;\n });\n }),\n );\n\n // -----------------------------------------------------------------------\n // start — begin a flow through a client to mint a connection.\n // -----------------------------------------------------------------------\n const start = (\n input: OAuthStartInput,\n ): Effect.Effect<ConnectResult, OAuthStartError | StorageFailure> =>\n Effect.gen(function* () {\n const keys = yield* Effect.try({\n try: () => deps.ownedKeys(input.owner),\n catch: (cause) =>\n new StorageError({\n message: \"Cannot start OAuth flow for owner without a subject\",\n cause,\n }),\n });\n // Sharing is one-directional (org → members): a Workspace (org) connection\n // cannot be backed by a member's private (user) app. The connection owner\n // and the app owner are otherwise independent — a Personal connection\n // through a shared Workspace app is the supported cross-owner case.\n if (input.owner === \"org\" && input.clientOwner === \"user\") {\n return yield* new OAuthStartError({\n message: \"A Workspace connection must use a Workspace app.\",\n });\n }\n // Load the app by its EXPLICIT owner (the caller knows it — no derivation).\n // The connection is still minted under `input.owner`. Storage visibility\n // policy hides apps the actor cannot see, so a wrong owner yields null.\n const client = yield* loadClient(input.clientOwner, input.client);\n if (!client) {\n return yield* new OAuthStartError({\n message: `OAuth client not found: ${input.client}`,\n });\n }\n\n // Declared scopes win (driven by the selected auth template). MCP-style\n // integrations declare none and discover them from the client's protected\n // resource / authorization server metadata at connect.\n const scopePolicy = yield* deps\n .resolveOAuthScopePolicy(input.integration, input.template)\n .pipe(\n Effect.mapError(\n (cause) =>\n new OAuthStartError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: StorageFailure carries a typed `message` field\n message: `Failed to resolve OAuth scope policy: ${cause.message}`,\n }),\n ),\n );\n const requestedScopes =\n scopePolicy.kind === \"discover\"\n ? yield* discoverScopesForResource(client.resource).pipe(\n Effect.mapError(\n (cause) =>\n new OAuthStartError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuthDiscoveryError carries a typed `message` field\n message: `Failed to discover OAuth scopes: ${cause.message}`,\n }),\n ),\n )\n : dedupeScopes(scopePolicy.scopes);\n\n // client_credentials: exchange immediately and mint the connection.\n if (client.grant === \"client_credentials\") {\n const token = yield* exchangeClientCredentials({\n tokenUrl: client.tokenUrl,\n clientId: client.clientId,\n clientSecret: client.clientSecret,\n scopes: requestedScopes,\n resource: client.resource ?? undefined,\n endpointUrlPolicy: deps.endpointUrlPolicy,\n fetch,\n }).pipe(\n Effect.mapError(\n (cause) =>\n new OAuthStartError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuth2Error carries a typed `message` field\n message: `OAuth client-credentials exchange failed: ${cause.message}`,\n }),\n ),\n );\n const connection = yield* mintFromToken(\n input,\n client,\n token,\n requestedScopes,\n input.clientOwner,\n // client_credentials has no callback, so no regional rebind applies.\n null,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new OAuthStartError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: StorageFailure carries a typed `message` field\n message: `Failed to mint OAuth connection: ${cause.message}`,\n }),\n ),\n );\n return { status: \"connected\", connection } as const;\n }\n\n // authorization_code requires our callback to receive the code — fail\n // loudly if the executor was constructed without a redirectUri rather\n // than persisting a session pointed at a wrong localhost callback.\n const flowRedirectUri = input.redirectUri ?? redirectUri;\n if (flowRedirectUri == null) {\n return yield* new OAuthStartError({\n message: REDIRECT_URI_REQUIRED_MESSAGE,\n });\n }\n\n // authorization_code: persist a session + build the authorize URL.\n const verifier = createPkceCodeVerifier();\n const challenge = yield* Effect.promise(() => createPkceCodeChallenge(verifier));\n const state = OAuthState.make(createOAuthState());\n const providerState = encodeOAuthCallbackState({\n state: String(state),\n orgSlug: deps.callbackStateOrgSlug,\n });\n\n const now = new Date();\n const expiresAt = Date.now() + OAUTH2_SESSION_TTL_MS;\n yield* deps.fuma.use(\"oauth_session.create\", (db) =>\n looseDb(db).create(\"oauth_session\", {\n tenant: keys.tenant,\n owner: keys.owner,\n subject: keys.subject,\n state: String(state),\n client_slug: String(input.client),\n integration: String(input.integration),\n name: String(input.name),\n template: String(input.template),\n redirect_url: flowRedirectUri,\n pkce_verifier: verifier,\n identity_label: input.identityLabel ?? null,\n // Persist the requested scope set (the integration's declared or\n // discovered scopes) so `complete`'s recorded-scope fallback reflects\n // exactly what was requested when the AS omits `scope`, without\n // re-resolving it at completion.\n payload: { owner: input.owner, clientOwner: input.clientOwner, requestedScopes },\n expires_at: expiresAt,\n created_at: now,\n }),\n );\n\n const authorizationUrl = yield* Effect.try({\n try: () =>\n buildAuthorizationUrl({\n authorizationUrl: client.authorizationUrl,\n clientId: client.clientId,\n redirectUrl: flowRedirectUri,\n scopes: requestedScopes,\n state: providerState,\n codeChallenge: challenge,\n resource: client.resource ?? undefined,\n // Provider quirks (Google: access_type=offline + prompt=consent) —\n // without these Google returns no refresh token and won't re-consent\n // to widen scopes on reconnect.\n extraParams: providerAuthorizeExtras(client.authorizationUrl),\n endpointUrlPolicy: deps.endpointUrlPolicy,\n }),\n catch: (cause) =>\n new OAuthStartError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: surface the URL-construction failure\n message: `Failed to build authorization URL: ${String(cause)}`,\n }),\n });\n\n return { status: \"redirect\", authorizationUrl, state } as const;\n });\n\n // -----------------------------------------------------------------------\n // complete — redeem the session, exchange the code, mint the connection.\n // -----------------------------------------------------------------------\n const complete = (\n input: OAuthCompleteInput,\n ): Effect.Effect<Connection, OAuthCompleteError | OAuthSessionNotFoundError | StorageFailure> =>\n Effect.gen(function* () {\n const sessionRow = yield* deps.fuma.use(\"oauth_session.findFirst\", (db) =>\n looseDb(db).findFirst(\"oauth_session\", {\n where: (b: any) => b(\"state\", \"=\", String(input.state)),\n }),\n );\n if (!sessionRow) {\n return yield* new OAuthSessionNotFoundError({ state: input.state });\n }\n const session = {\n owner: String(sessionRow.owner) as Owner,\n clientSlug: OAuthClientSlug.make(String(sessionRow.client_slug)),\n integration: IntegrationSlug.make(String(sessionRow.integration)),\n name: ConnectionName.make(String(sessionRow.name)),\n template: AuthTemplateSlug.make(String(sessionRow.template)),\n redirectUrl: String(sessionRow.redirect_url),\n pkceVerifier: sessionRow.pkce_verifier == null ? null : String(sessionRow.pkce_verifier),\n identityLabel: sessionRow.identity_label == null ? null : String(sessionRow.identity_label),\n expiresAt: Number(sessionRow.expires_at),\n // The scope set `start` requested (the integration's declared or\n // discovered scopes), persisted on the session payload. Drives the\n // recorded-scope fallback when the AS omits `scope`. Missing/legacy\n // payloads fall back to the client's scopes below.\n requestedScopes: requestedScopesFromPayload(sessionRow.payload),\n // The app's owner, recorded by `start` — reload the SAME app at\n // completion by explicit owner (no derivation). Defaults to the session\n // owner for same-owner connects.\n clientOwner:\n clientOwnerFromPayload(sessionRow.payload) ?? (String(sessionRow.owner) as Owner),\n };\n\n // Expired sessions are not redeemable — drop + treat as not found.\n if (Number.isFinite(session.expiresAt) && session.expiresAt <= Date.now()) {\n yield* deleteSession(input.state);\n return yield* new OAuthSessionNotFoundError({ state: input.state });\n }\n\n // Reload the SAME app `start` resolved, by its explicit recorded owner.\n const client = yield* loadClient(session.clientOwner, session.clientSlug);\n if (!client) {\n return yield* new OAuthCompleteError({\n message: `OAuth client not found: ${session.clientSlug}`,\n restartRequired: true,\n });\n }\n\n // The PKCE verifier is minted by `start` for every authorization_code\n // session. A null/missing one means a corrupt session row — exchanging\n // with an empty verifier would violate RFC 7636 and the AS would reject\n // it with an opaque error. Fail loudly + require a restart instead.\n if (session.pkceVerifier == null) {\n return yield* new OAuthCompleteError({\n message: `OAuth session ${input.state} is missing its PKCE code verifier; restart the flow.`,\n restartRequired: true,\n });\n }\n\n // Some authorization servers (Datadog) advertise one region's token\n // endpoint in static metadata but issue codes that only redeem at the\n // org's actual region, signalled back on the callback as `domain`/`site`.\n // Rebind the token host to that region when it is a sibling subdomain of\n // the configured host; otherwise this is a no-op.\n const tokenUrl = rebindTokenEndpointHostToCallbackDomain(\n client.tokenUrl,\n input.callbackDomain,\n );\n\n const token = yield* exchangeAuthorizationCode({\n tokenUrl,\n clientId: client.clientId,\n clientSecret: client.clientSecret,\n redirectUrl: session.redirectUrl,\n codeVerifier: session.pkceVerifier,\n code: input.code,\n resource: client.resource ?? undefined,\n endpointUrlPolicy: deps.endpointUrlPolicy,\n fetch,\n }).pipe(\n Effect.mapError(\n (cause) =>\n new OAuthCompleteError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuth2Error carries a typed `message` field\n message: `OAuth code exchange failed: ${cause.message}`,\n restartRequired: cause.error === \"invalid_grant\",\n }),\n ),\n );\n\n const connection = yield* mintFromToken(\n {\n owner: session.owner,\n name: session.name,\n integration: session.integration,\n template: session.template,\n identityLabel: session.identityLabel,\n },\n client,\n token,\n // The scopes `start` requested (the integration's declared set), persisted\n // on the session. Empty only for a corrupt/legacy session with no payload.\n session.requestedScopes ?? [],\n session.clientOwner,\n // Persist the regional token endpoint ONLY when it differs from the\n // client's configured one, so refresh redeems against the same region.\n tokenUrl === client.tokenUrl ? null : tokenUrl,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new OAuthCompleteError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: StorageFailure carries a typed `message` field\n message: `Failed to mint OAuth connection: ${cause.message}`,\n restartRequired: false,\n }),\n ),\n );\n\n yield* deleteSession(input.state);\n return connection;\n });\n\n // -----------------------------------------------------------------------\n // Mint the connection from a freshly exchanged token: store the access\n // value (+ refresh) in the default writable provider, then write the\n // connection row with OAuth lifecycle fields + produce its tools.\n // -----------------------------------------------------------------------\n const mintFromToken = (\n target: {\n readonly owner: Owner;\n readonly name: ConnectionName;\n readonly integration: IntegrationSlug;\n readonly template: AuthTemplateSlug;\n readonly identityLabel?: string | null;\n },\n client: LoadedOAuthClient,\n token: OAuth2TokenResponse,\n /** The scope set requested at /authorize + /token (the integration's\n * declared or discovered scopes) — the recorded-scope fallback when the AS\n * omits `scope`. */\n requestedScopes: readonly string[],\n /** The owner of `client` — persisted so refresh loads it by explicit owner. */\n clientOwner: Owner,\n /** Regional token endpoint override to persist when the code was redeemed\n * off the client's configured host; null to use the client's token URL. */\n oauthTokenUrl: string | null,\n ): Effect.Effect<Connection, StorageFailure> =>\n Effect.gen(function* () {\n const provider = deps.defaultWritableProvider();\n if (!provider || !provider.set) {\n return yield* new StorageError({\n message:\n \"No default writable credential provider is registered to store the OAuth access token.\",\n cause: undefined,\n });\n }\n const itemId = accessItemId(target.owner, target.integration, target.name);\n yield* provider.set(ProviderItemId.make(itemId), token.access_token);\n\n let refreshItemId: string | null = null;\n if (token.refresh_token) {\n refreshItemId = refreshItemIdFor(itemId);\n yield* provider.set(ProviderItemId.make(refreshItemId), token.refresh_token);\n }\n\n return yield* deps.mintOAuthConnection({\n owner: target.owner,\n name: target.name,\n integration: target.integration,\n template: target.template,\n identityLabel: target.identityLabel ?? null,\n provider: String(provider.key),\n itemId,\n oauthClient: OAuthClientSlug.make(client.slug),\n oauthClientOwner: clientOwner,\n refreshItemId,\n expiresAt: expiresAtFrom(token),\n // Record the granted scope the AS echoed back. Some providers, including\n // Microsoft, issue a refresh token for `offline_access` but omit that\n // non-resource scope from the token `scope` string, so preserve it when\n // the refresh token proves it was granted.\n oauthScope: recordedOAuthScope(token, requestedScopes),\n oauthTokenUrl,\n });\n });\n\n const deleteSession = (state: OAuthState): Effect.Effect<void, StorageFailure> =>\n deps.fuma\n .use(\"oauth_session.delete\", (db) =>\n looseDb(db).deleteMany(\"oauth_session\", {\n where: (b: any) => b(\"state\", \"=\", String(state)),\n }),\n )\n .pipe(Effect.asVoid);\n\n // -----------------------------------------------------------------------\n // cancel — drop an in-flight session.\n // -----------------------------------------------------------------------\n const cancel = (state: OAuthState): Effect.Effect<void, StorageFailure> => deleteSession(state);\n\n // -----------------------------------------------------------------------\n // probe — RFC 8414 / OIDC discovery for onboarding pre-fill.\n // -----------------------------------------------------------------------\n const probe = (\n input: OAuthProbeInput,\n ): Effect.Effect<OAuthProbeResult, OAuthProbeError | StorageFailure> =>\n Effect.gen(function* () {\n const options = { endpointUrlPolicy: deps.endpointUrlPolicy };\n // Try protected-resource metadata first (RFC 9728), then the AS issuer.\n const resource = yield* discoverProtectedResourceMetadata(input.url, options).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n // EXPLICIT discovery order: when the protected-resource metadata advertises\n // an authorization server, probe that; otherwise probe the input endpoint\n // itself as a last resort. This is a documented probe order, not a silent\n // guess — a probe that finds no AS metadata fails loudly below.\n const issuerCandidate = resource?.metadata.authorization_servers?.[0] ?? input.url;\n const as = yield* discoverAuthorizationServerMetadata(issuerCandidate, options).pipe(\n Effect.mapError(\n (cause) =>\n new OAuthProbeError({\n // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: OAuthDiscoveryError carries a typed `message` field\n message: `OAuth discovery failed: ${cause.message}`,\n }),\n ),\n );\n if (!as) {\n return yield* new OAuthProbeError({\n message: `No OAuth authorization-server metadata found at ${input.url}`,\n });\n }\n return {\n authorizationUrl: as.metadata.authorization_endpoint,\n tokenUrl: as.metadata.token_endpoint,\n resource: resource?.metadata.resource ?? null,\n // Prefer the resource's own RFC 9728 scopes (authoritative, even when\n // empty); fall back to the authorization server's list only when PRM is\n // silent. For a spec-compliant MCP server (one that publishes PRM) this\n // matches what `oauth.start` discovers. The AS fallback is a best-effort\n // hint for the registration form on servers that omit PRM — where\n // `oauth.start` requests none — so the two can differ for those.\n scopesSupported: resource?.metadata.scopes_supported ?? as.metadata.scopes_supported,\n registrationEndpoint: as.metadata.registration_endpoint ?? null,\n tokenEndpointAuthMethodsSupported: as.metadata.token_endpoint_auth_methods_supported,\n } satisfies OAuthProbeResult;\n }).pipe(Effect.provide(httpClientLayer));\n\n return {\n createClient,\n removeClient,\n registerDynamicClient,\n listClients,\n start,\n complete,\n cancel,\n probe,\n };\n};\n","// ---------------------------------------------------------------------------\n// OAuth 2.0 metadata discovery + DCR.\n//\n// The token-endpoint helpers in `./oauth-helpers.ts` assume the caller\n// already knows the authorization/token URLs and client_id — that's\n// fine for static integrations (Google, a specific OpenAPI server).\n// The zero-config case — user pastes an arbitrary endpoint URL and we\n// figure out its OAuth configuration — needs three more building blocks:\n//\n// - RFC 9728 Protected Resource Metadata (/.well-known/oauth-protected-resource)\n// - RFC 8414 Authorization Server Metadata (/.well-known/oauth-authorization-server,\n// with OIDC /.well-known/openid-configuration as fallback)\n// - RFC 7591 Dynamic Client Registration (POST `registration_endpoint`)\n//\n// The discovery path uses Effect HttpClient throughout so tests can provide\n// realistic local HTTP services without patching `globalThis.fetch`. A\n// convenience `beginDynamicAuthorization` chains all three into the single\n// call callers actually need.\n// ---------------------------------------------------------------------------\n\nimport { Data, Duration, Effect, Layer, Option, Predicate, Result, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nimport {\n OAUTH2_DEFAULT_TIMEOUT_MS,\n assertSupportedOAuthEndpointUrl,\n buildAuthorizationUrl,\n createPkceCodeChallenge,\n createPkceCodeVerifier,\n type OAuthEndpointUrlPolicy,\n} from \"./oauth-helpers\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/** Separate tag from `OAuth2Error` so callers can distinguish discovery\n * / DCR failures (happen once, before any token round-trips) from\n * token-endpoint failures. A plugin's refresh path should never have\n * to inspect error messages to tell \"metadata drifted, re-discover\"\n * apart from \"refresh token is no longer honoured\". */\nexport class OAuthDiscoveryError extends Data.TaggedError(\"OAuthDiscoveryError\")<{\n readonly message: string;\n readonly status?: number;\n /** RFC 6749 §5.2 / RFC 7591 §3.2.2 error code, when the AS returned\n * one (`invalid_client_metadata`, `invalid_redirect_uri`, ...). Lets\n * the HTTP edge surface a structured error to the UI rather than\n * swallow the AS's response into a generic message string. */\n readonly error?: string;\n readonly errorDescription?: string;\n readonly cause?: unknown;\n}> {}\n\n// ---------------------------------------------------------------------------\n// Schemas (narrow structural parsing — the RFCs leave many fields\n// optional; we validate only the subset consumers read)\n// ---------------------------------------------------------------------------\n\nconst StringArray = Schema.Array(Schema.String);\n\nexport const OAuthProtectedResourceMetadataSchema = Schema.Struct({\n resource: Schema.optional(Schema.String),\n authorization_servers: Schema.optional(StringArray),\n scopes_supported: Schema.optional(StringArray),\n bearer_methods_supported: Schema.optional(StringArray),\n resource_documentation: Schema.optional(Schema.String),\n}).annotate({ identifier: \"OAuthProtectedResourceMetadata\" });\nexport type OAuthProtectedResourceMetadata = typeof OAuthProtectedResourceMetadataSchema.Type;\n\nexport const OAuthAuthorizationServerMetadataSchema = Schema.Struct({\n issuer: Schema.String,\n authorization_endpoint: Schema.String,\n token_endpoint: Schema.String,\n registration_endpoint: Schema.optional(Schema.String),\n scopes_supported: Schema.optional(StringArray),\n response_types_supported: Schema.optional(StringArray),\n grant_types_supported: Schema.optional(StringArray),\n code_challenge_methods_supported: Schema.optional(StringArray),\n token_endpoint_auth_methods_supported: Schema.optional(StringArray),\n revocation_endpoint: Schema.optional(Schema.String),\n introspection_endpoint: Schema.optional(Schema.String),\n userinfo_endpoint: Schema.optional(Schema.String),\n id_token_signing_alg_values_supported: Schema.optional(StringArray),\n}).annotate({ identifier: \"OAuthAuthorizationServerMetadata\" });\nexport type OAuthAuthorizationServerMetadata = typeof OAuthAuthorizationServerMetadataSchema.Type;\n\nexport type DynamicClientMetadata = {\n readonly client_name?: string;\n readonly redirect_uris: readonly string[];\n readonly grant_types?: readonly string[];\n readonly response_types?: readonly string[];\n readonly token_endpoint_auth_method?:\n | \"none\"\n | \"client_secret_basic\"\n | \"client_secret_post\"\n | \"private_key_jwt\";\n readonly scope?: string;\n readonly application_type?: \"web\" | \"native\";\n readonly client_uri?: string;\n readonly logo_uri?: string;\n readonly contacts?: readonly string[];\n readonly software_id?: string;\n readonly software_version?: string;\n /** Escape hatch for provider-specific extensions; merged last. */\n readonly extra?: Readonly<Record<string, unknown>>;\n};\n\nexport const OAuthClientInformationSchema = Schema.Struct({\n client_id: Schema.String,\n client_secret: Schema.optional(Schema.String),\n client_id_issued_at: Schema.optional(Schema.Number),\n client_secret_expires_at: Schema.optional(Schema.Number),\n registration_access_token: Schema.optional(Schema.String),\n registration_client_uri: Schema.optional(Schema.String),\n token_endpoint_auth_method: Schema.optional(Schema.String),\n grant_types: Schema.optional(StringArray),\n response_types: Schema.optional(StringArray),\n redirect_uris: Schema.optional(StringArray),\n client_name: Schema.optional(Schema.String),\n scope: Schema.optional(Schema.String),\n}).annotate({ identifier: \"OAuthClientInformation\" });\nexport type OAuthClientInformation = typeof OAuthClientInformationSchema.Type;\n\nconst decodeResourceMetadataJson = Schema.decodeUnknownEffect(\n Schema.fromJsonString(OAuthProtectedResourceMetadataSchema),\n);\nconst decodeAuthServerMetadata = Schema.decodeUnknownEffect(OAuthAuthorizationServerMetadataSchema);\nconst decodeClientInformationJson = Schema.decodeUnknownEffect(\n Schema.fromJsonString(OAuthClientInformationSchema),\n);\n\nexport interface DiscoveryRequestOptions {\n /** Injected for tests. Defaults to the platform fetch-backed HttpClient. */\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n /** Abort the request after this many ms. Default 20000. */\n readonly timeoutMs?: number;\n /** Send `MCP-Protocol-Version: <value>` on every request. Harmless\n * for non-MCP servers; required by the MCP authorization spec. */\n readonly mcpProtocolVersion?: string;\n /** Credentials needed to reach the protected resource itself. These\n * are intentionally used only for resource-side probes, never for\n * authorization-server metadata, DCR, authorization, or token calls. */\n readonly resourceHeaders?: Readonly<Record<string, string>>;\n readonly resourceQueryParams?: Readonly<Record<string, string>>;\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n}\n\nconst MCP_PROTOCOL_VERSION_HEADER = \"mcp-protocol-version\";\n\nconst validateEndpointUrl = (\n value: string,\n label: string,\n policy: OAuthEndpointUrlPolicy = {},\n): Effect.Effect<string, OAuthDiscoveryError> =>\n Effect.try({\n try: () => assertSupportedOAuthEndpointUrl(value, label, policy),\n catch: (cause) =>\n new OAuthDiscoveryError({\n message: `${label} must use https: or loopback http:`,\n cause,\n }),\n });\n\nconst validateAuthorizationServerMetadata = (\n metadata: OAuthAuthorizationServerMetadata,\n policy: OAuthEndpointUrlPolicy = {},\n): Effect.Effect<void, OAuthDiscoveryError> =>\n Effect.gen(function* () {\n yield* validateEndpointUrl(metadata.issuer, \"issuer\", policy);\n yield* validateEndpointUrl(metadata.authorization_endpoint, \"authorization_endpoint\", policy);\n yield* validateEndpointUrl(metadata.token_endpoint, \"token_endpoint\", policy);\n if (metadata.registration_endpoint) {\n yield* validateEndpointUrl(metadata.registration_endpoint, \"registration_endpoint\", policy);\n }\n });\n\nconst provideHttpClient = <A, E>(\n effect: Effect.Effect<A, E, HttpClient.HttpClient>,\n options: DiscoveryRequestOptions,\n): Effect.Effect<A, E> =>\n effect.pipe(Effect.provide(options.httpClientLayer ?? FetchHttpClient.layer));\n\nconst executeText = (\n request: HttpClientRequest.HttpClientRequest,\n options: DiscoveryRequestOptions,\n errorMessage: string,\n): Effect.Effect<{ readonly status: number; readonly body: string }, OAuthDiscoveryError> =>\n provideHttpClient(\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n const response = yield* client.execute(request).pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(options.timeoutMs ?? OAUTH2_DEFAULT_TIMEOUT_MS),\n orElse: () =>\n Effect.fail(\n new OAuthDiscoveryError({\n message: errorMessage,\n cause: \"timeout\",\n }),\n ),\n }),\n Effect.mapError((cause) =>\n Predicate.isTagged(cause, \"OAuthDiscoveryError\")\n ? cause\n : new OAuthDiscoveryError({\n message: errorMessage,\n cause,\n }),\n ),\n );\n const body = yield* response.text.pipe(\n Effect.catch(() => Effect.succeed(\"\")),\n Effect.mapError(\n (cause) =>\n new OAuthDiscoveryError({\n message: `${errorMessage}: response body could not be read`,\n status: response.status,\n cause,\n }),\n ),\n );\n return { status: response.status, body };\n }),\n options,\n );\n\n// ---------------------------------------------------------------------------\n// RFC 9728 — Protected Resource Metadata\n//\n// Not covered by `oauth4webapi`. Hand-rolled probe: try the path-scoped\n// well-known first, then the origin-scoped fallback.\n// ---------------------------------------------------------------------------\n\nconst buildResourceMetadataUrls = (resourceUrl: string): string[] => {\n const url = new URL(resourceUrl);\n const origin = `${url.protocol}//${url.host}`;\n const path = url.pathname.replace(/\\/+$/, \"\");\n const urls: string[] = [];\n if (path && path !== \"/\") {\n urls.push(`${origin}/.well-known/oauth-protected-resource${path}`);\n }\n urls.push(`${origin}/.well-known/oauth-protected-resource`);\n return urls;\n};\n\nconst withResourceQueryParams = (\n url: string,\n queryParams: Readonly<Record<string, string>> | undefined,\n): string => {\n if (!queryParams || Object.keys(queryParams).length === 0) return url;\n const parsed = new URL(url);\n for (const [key, value] of Object.entries(queryParams)) {\n parsed.searchParams.set(key, value);\n }\n return parsed.toString();\n};\n\nexport const discoverProtectedResourceMetadata = (\n resourceUrl: string,\n options: DiscoveryRequestOptions = {},\n): Effect.Effect<\n { readonly metadataUrl: string; readonly metadata: OAuthProtectedResourceMetadata } | null,\n OAuthDiscoveryError\n> =>\n Effect.gen(function* () {\n for (const url of buildResourceMetadataUrls(resourceUrl)) {\n const requestUrl = withResourceQueryParams(url, options.resourceQueryParams);\n let request = HttpClientRequest.get(requestUrl).pipe(\n HttpClientRequest.setHeader(\"accept\", \"application/json\"),\n );\n for (const [name, value] of Object.entries(options.resourceHeaders ?? {})) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n if (options.mcpProtocolVersion) {\n request = HttpClientRequest.setHeader(\n request,\n MCP_PROTOCOL_VERSION_HEADER,\n options.mcpProtocolVersion,\n );\n }\n\n const result = yield* executeText(\n request,\n options,\n `Failed to fetch protected resource metadata from ${url}`,\n );\n if (result.status === 404 || result.status === 405 || result.body.length === 0) continue;\n if (result.status < 200 || result.status >= 300) {\n return yield* new OAuthDiscoveryError({\n message: `Protected resource metadata returned status ${result.status}`,\n status: result.status,\n });\n }\n const metadata = yield* decodeResourceMetadataJson(result.body).pipe(\n Effect.mapError(\n (err) =>\n new OAuthDiscoveryError({\n message: \"Protected resource metadata is malformed\",\n cause: err,\n }),\n ),\n );\n return { metadataUrl: url, metadata };\n }\n return null;\n });\n\n// ---------------------------------------------------------------------------\n// RFC 8414 + OIDC Discovery — Authorization Server Metadata\n//\n// Try RFC 8414 (`oauth2`) first and fall back to OIDC Discovery. Keep the\n// probing in this module so the whole discovery stack shares the same Effect\n// HttpClient boundary and timeout behavior.\n// ---------------------------------------------------------------------------\n\nconst wellKnownUrlFor = (\n issuerOrigin: string,\n algorithm: \"oauth2\" | \"oidc\",\n issuerPath: string,\n): string => {\n // Mirrors the library's own well-known composition so the URL we\n // surface matches what was actually fetched.\n const suffix = algorithm === \"oauth2\" ? \"oauth-authorization-server\" : \"openid-configuration\";\n return issuerPath && issuerPath !== \"/\"\n ? `${issuerOrigin}/.well-known/${suffix}${issuerPath}`\n : `${issuerOrigin}/.well-known/${suffix}`;\n};\n\nexport const discoverAuthorizationServerMetadata = (\n issuer: string,\n options: DiscoveryRequestOptions = {},\n): Effect.Effect<\n {\n readonly metadataUrl: string;\n readonly metadata: OAuthAuthorizationServerMetadata;\n } | null,\n OAuthDiscoveryError\n> =>\n Effect.gen(function* () {\n yield* validateEndpointUrl(issuer, \"issuer\", options.endpointUrlPolicy);\n const issuerUrl = new URL(issuer);\n const issuerOrigin = `${issuerUrl.protocol}//${issuerUrl.host}`;\n const issuerPath = issuerUrl.pathname.replace(/\\/+$/, \"\");\n\n for (const algorithm of [\"oauth2\", \"oidc\"] as const) {\n const metadataUrl = wellKnownUrlFor(issuerOrigin, algorithm, issuerPath);\n let request = HttpClientRequest.get(metadataUrl).pipe(\n HttpClientRequest.setHeader(\"accept\", \"application/json\"),\n );\n if (options.mcpProtocolVersion) {\n request = HttpClientRequest.setHeader(\n request,\n MCP_PROTOCOL_VERSION_HEADER,\n options.mcpProtocolVersion,\n );\n }\n const result = yield* executeText(\n request,\n options,\n `Discovery (${algorithm}) failed for ${issuer}`,\n ).pipe(\n Effect.map((response) => {\n if (response.status === 404 || response.status === 405) return null;\n return response;\n }),\n // If one algorithm fails mid-roundtrip (network, parse, issuer\n // mismatch) we still want to try the other before giving up.\n Effect.result,\n );\n\n if (Result.isFailure(result)) continue;\n const response = result.success;\n if (response === null) continue;\n if (response.status < 200 || response.status >= 300) continue;\n\n const raw = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(\n response.body,\n ).pipe(\n Effect.mapError(\n (err) =>\n new OAuthDiscoveryError({\n message: \"Authorization server metadata is malformed\",\n cause: err,\n }),\n ),\n );\n const metadata = yield* decodeAuthServerMetadata(raw).pipe(\n Effect.mapError(\n (err) =>\n new OAuthDiscoveryError({\n message: \"Authorization server metadata is malformed\",\n cause: err,\n }),\n ),\n );\n yield* validateAuthorizationServerMetadata(metadata, options.endpointUrlPolicy);\n return { metadataUrl, metadata };\n }\n return null;\n });\n\n// ---------------------------------------------------------------------------\n// RFC 7591 — Dynamic Client Registration\n//\n// Hand-rolled instead of delegating to oauth4webapi. The library's\n// `processDynamicClientRegistrationResponse` requires the AS return\n// HTTP 201 Created (RFC 7591 §3.2.1), but Todoist (and others) return\n// 200 OK on success. We accept both, and still surface 4xx OAuth error\n// envelopes the same way oauth4webapi would.\n// ---------------------------------------------------------------------------\n\nexport interface RegisterDynamicClientInput {\n readonly registrationEndpoint: string;\n readonly metadata: DynamicClientMetadata;\n readonly initialAccessToken?: string | null;\n}\n\n// Internal failure modes — collapsed into `OAuthDiscoveryError` at the\n// boundary. Tagged so we can match without `instanceof`.\nclass DcrErrorBody extends Data.TaggedError(\"DcrErrorBody\")<{\n readonly status: number;\n readonly error: string;\n readonly error_description?: string;\n}> {}\n\nclass DcrTransport extends Data.TaggedError(\"DcrTransport\")<{\n readonly detail: string;\n readonly status?: number;\n readonly cause?: unknown;\n}> {}\n\nconst DcrErrorBodyJson = Schema.Struct({\n error: Schema.String,\n error_description: Schema.optional(Schema.String),\n});\nconst decodeDcrErrorBodyJson = Schema.decodeUnknownOption(Schema.fromJsonString(DcrErrorBodyJson));\n\nconst buildDcrBody = (m: DynamicClientMetadata): Record<string, unknown> => {\n const body: Record<string, unknown> = { redirect_uris: [...m.redirect_uris] };\n if (m.client_name !== undefined) body.client_name = m.client_name;\n if (m.grant_types !== undefined) body.grant_types = [...m.grant_types];\n if (m.response_types !== undefined) body.response_types = [...m.response_types];\n if (m.token_endpoint_auth_method !== undefined) {\n body.token_endpoint_auth_method = m.token_endpoint_auth_method;\n }\n if (m.scope !== undefined) body.scope = m.scope;\n if (m.application_type !== undefined) body.application_type = m.application_type;\n if (m.client_uri !== undefined) body.client_uri = m.client_uri;\n if (m.logo_uri !== undefined) body.logo_uri = m.logo_uri;\n if (m.contacts !== undefined) body.contacts = [...m.contacts];\n if (m.software_id !== undefined) body.software_id = m.software_id;\n if (m.software_version !== undefined) body.software_version = m.software_version;\n if (m.extra) for (const [k, v] of Object.entries(m.extra)) body[k] = v;\n return body;\n};\n\nconst interpretDcrFailure = (status: number, text: string): DcrErrorBody | DcrTransport => {\n // RFC 6749 error envelope: `{error, error_description?}` with 4xx.\n if (status >= 400 && status < 500) {\n const body = text ? decodeDcrErrorBodyJson(text) : null;\n return Option.match(body ?? Option.none(), {\n onNone: () =>\n new DcrTransport({\n detail: `Dynamic Client Registration endpoint returned status ${status}${\n text ? ` — ${text.slice(0, 200)}` : \"\"\n }`,\n status,\n }),\n onSome: (parsed) =>\n parsed.error.length > 0\n ? new DcrErrorBody({\n status,\n error: parsed.error,\n error_description: parsed.error_description,\n })\n : new DcrTransport({\n detail: `Dynamic Client Registration endpoint returned status ${status}${\n text ? ` — ${text.slice(0, 200)}` : \"\"\n }`,\n status,\n }),\n });\n }\n return new DcrTransport({\n detail: `Dynamic Client Registration endpoint returned status ${status}${\n text ? ` — ${text.slice(0, 200)}` : \"\"\n }`,\n status,\n });\n};\n\nexport const registerDynamicClient = (\n input: RegisterDynamicClientInput,\n options: DiscoveryRequestOptions = {},\n): Effect.Effect<OAuthClientInformation, OAuthDiscoveryError> =>\n Effect.gen(function* () {\n yield* validateEndpointUrl(\n input.registrationEndpoint,\n \"registration_endpoint\",\n options.endpointUrlPolicy,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new DcrTransport({\n detail: \"registration_endpoint must use https: or loopback http:\",\n cause,\n }),\n ),\n );\n\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n };\n if (input.initialAccessToken) {\n headers.authorization = `Bearer ${input.initialAccessToken}`;\n }\n\n let request = HttpClientRequest.post(input.registrationEndpoint).pipe(\n HttpClientRequest.bodyJsonUnsafe(buildDcrBody(input.metadata)),\n );\n for (const [name, value] of Object.entries(headers)) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n\n const response = yield* executeText(\n request,\n options,\n \"Dynamic Client Registration request failed\",\n ).pipe(\n Effect.mapError(\n (cause) =>\n new DcrTransport({\n detail: \"Dynamic Client Registration request failed\",\n cause,\n }),\n ),\n );\n\n // Accept both 200 and 201 as success — RFC 7591 mandates 201, but\n // Todoist (and others) return 200 OK with the client information body.\n if (response.status !== 200 && response.status !== 201) {\n return yield* interpretDcrFailure(response.status, response.body);\n }\n\n return yield* decodeClientInformationJson(response.body).pipe(\n Effect.mapError(\n (err) =>\n new OAuthDiscoveryError({\n message: \"Dynamic Client Registration response is malformed\",\n cause: err,\n }),\n ),\n );\n }).pipe(\n Effect.catchTags({\n DcrErrorBody: (err) =>\n Effect.fail(\n new OAuthDiscoveryError({\n message: `Dynamic Client Registration failed: ${err.error}${\n err.error_description ? ` — ${err.error_description}` : \"\"\n }`,\n status: err.status,\n error: err.error,\n errorDescription: err.error_description,\n cause: err,\n }),\n ),\n DcrTransport: (err) =>\n Effect.fail(\n new OAuthDiscoveryError({\n message: `Dynamic Client Registration failed: ${err.detail}`,\n status: err.status,\n cause: err.cause ?? err,\n }),\n ),\n }),\n );\n\n// ---------------------------------------------------------------------------\n// RFC 8707 — Resource Indicator canonicalisation\n//\n// MCP Authorization 2025-06-18 requires `resource` on /authorize and /token\n// requests. RFC 8707 §2 says the value is \"an absolute URI\" identifying the\n// protected resource — same scheme + host + (optional) path, no fragment,\n// no query, lowercased scheme/host.\n// ---------------------------------------------------------------------------\n\nexport const canonicalResourceUrl = (value: string): string => {\n const url = new URL(value);\n const scheme = url.protocol.toLowerCase();\n const host = url.host.toLowerCase();\n const path = url.pathname.replace(/\\/+$/, \"\");\n return `${scheme}//${host}${path}`;\n};\n\nconst validateResourceIndicator = (\n value: string,\n expected: string,\n): Effect.Effect<string, OAuthDiscoveryError> =>\n Effect.try({\n try: () => canonicalResourceUrl(value),\n catch: (cause) =>\n new OAuthDiscoveryError({\n message: \"Protected resource metadata resource is malformed\",\n cause,\n }),\n }).pipe(\n Effect.flatMap((actual) =>\n actual === expected || expected.startsWith(`${actual}/`)\n ? Effect.succeed(actual)\n : Effect.fail(\n new OAuthDiscoveryError({\n message: \"Protected resource metadata resource does not match requested endpoint\",\n cause: { expected, actual },\n }),\n ),\n ),\n );\n\n// ---------------------------------------------------------------------------\n// Token-endpoint auth method negotiation\n//\n// OAuth 2.1 §2.4 leaves the choice to the client; our preference order is\n// security-first: PKCE-only public client > client_secret_post >\n// client_secret_basic. Servers like Clay only advertise the secret variants;\n// servers like most MCP examples only advertise `none`.\n// ---------------------------------------------------------------------------\n\nconst SUPPORTED_DCR_AUTH_METHODS = [\"none\", \"client_secret_post\", \"client_secret_basic\"] as const;\n\ntype DcrAuthMethod = (typeof SUPPORTED_DCR_AUTH_METHODS)[number];\n\nconst negotiateAuthMethod = (advertised: readonly string[] | undefined): DcrAuthMethod | null => {\n if (!advertised || advertised.length === 0) return \"none\";\n for (const candidate of SUPPORTED_DCR_AUTH_METHODS) {\n if (advertised.includes(candidate)) return candidate;\n }\n return null;\n};\n\n// ---------------------------------------------------------------------------\n// Convenience: begin the full dynamic flow in one call\n// ---------------------------------------------------------------------------\n\nexport interface DynamicAuthorizationState {\n readonly resourceMetadata: OAuthProtectedResourceMetadata | null;\n readonly resourceMetadataUrl: string | null;\n readonly authorizationServerUrl: string;\n readonly authorizationServerMetadataUrl: string;\n readonly authorizationServerMetadata: OAuthAuthorizationServerMetadata;\n readonly clientInformation: OAuthClientInformation;\n /** RFC 8707 canonical resource URL passed on /authorize and persisted\n * for the matching /token + refresh calls. */\n readonly resource: string;\n /** Scopes ultimately requested at /authorize. Persisted so refresh\n * can replay the same set. */\n readonly scopes: readonly string[];\n}\n\nexport interface DynamicAuthorizationStartResult {\n readonly authorizationUrl: string;\n readonly codeVerifier: string;\n readonly state: DynamicAuthorizationState;\n}\n\nexport interface BeginDynamicAuthorizationInput {\n readonly endpoint: string;\n readonly redirectUrl: string;\n /** RFC 6749 `state` — callers typically pass a per-session random id. */\n readonly state: string;\n /** Defaults: `redirect_uris=[redirectUrl]`, `token_endpoint_auth_method=\"none\"`\n * (public client + PKCE). */\n readonly clientMetadata?: Partial<DynamicClientMetadata>;\n /** Scopes to request. Defaults to `scopes_supported`; omitted if\n * neither is set. */\n readonly scopes?: readonly string[];\n /** Pre-existing state from a previous flow. When provided, the\n * matching discovery / DCR step is skipped so multi-user sign-ins\n * against the same source don't re-pay those costs. */\n readonly previousState?: {\n readonly authorizationServerUrl?: string | null;\n readonly authorizationServerMetadata?: OAuthAuthorizationServerMetadata | null;\n readonly authorizationServerMetadataUrl?: string | null;\n readonly resourceMetadata?: OAuthProtectedResourceMetadata | null;\n readonly resourceMetadataUrl?: string | null;\n readonly clientInformation?: OAuthClientInformation | null;\n readonly resource?: string | null;\n readonly scopes?: readonly string[] | null;\n };\n}\n\nexport const beginDynamicAuthorization = (\n input: BeginDynamicAuthorizationInput,\n options: DiscoveryRequestOptions = {},\n): Effect.Effect<DynamicAuthorizationStartResult, OAuthDiscoveryError> =>\n Effect.gen(function* () {\n const prior = input.previousState ?? {};\n\n // Skip the resource-metadata probe when we already know (or can\n // derive) the authorization server URL. Saves two round-trips for\n // every second-and-later user signing into the same source.\n const canSkipResourceDiscovery =\n prior.resourceMetadata !== undefined ||\n !!prior.authorizationServerUrl ||\n !!prior.authorizationServerMetadata;\n\n const resource = canSkipResourceDiscovery\n ? prior.resourceMetadata\n ? {\n metadata: prior.resourceMetadata,\n metadataUrl: prior.resourceMetadataUrl ?? null,\n }\n : null\n : yield* discoverProtectedResourceMetadata(input.endpoint, options);\n\n const expectedResource = canonicalResourceUrl(input.endpoint);\n\n // RFC 9728 allows multiple authorization_servers — try each in\n // listed order. Fall back to the endpoint's origin only when no\n // PRM is advertised.\n const candidateAuthorizationServerUrls: readonly string[] = (() => {\n if (prior.authorizationServerUrl) return [prior.authorizationServerUrl];\n const fromResource = resource?.metadata.authorization_servers ?? [];\n if (fromResource.length > 0) return fromResource;\n const u = new URL(input.endpoint);\n return [`${u.protocol}//${u.host}`];\n })();\n\n const priorAuthServer =\n prior.authorizationServerMetadata && prior.authorizationServerMetadataUrl\n ? {\n metadata: prior.authorizationServerMetadata,\n metadataUrl: prior.authorizationServerMetadataUrl,\n url: prior.authorizationServerUrl ?? candidateAuthorizationServerUrls[0]!,\n }\n : null;\n\n const discovered = priorAuthServer\n ? priorAuthServer\n : yield* (() => {\n const tried: string[] = [];\n return Effect.gen(function* () {\n for (const candidate of candidateAuthorizationServerUrls) {\n tried.push(candidate);\n const md = yield* discoverAuthorizationServerMetadata(candidate, options).pipe(\n Effect.catchTag(\"OAuthDiscoveryError\", () => Effect.succeed(null)),\n );\n if (md) {\n return { metadata: md.metadata, metadataUrl: md.metadataUrl, url: candidate };\n }\n }\n return yield* new OAuthDiscoveryError({\n message: `No OAuth authorization server metadata found (tried: ${tried.join(\", \")})`,\n });\n });\n })();\n\n const authServer = { metadata: discovered.metadata, metadataUrl: discovered.metadataUrl };\n const authorizationServerUrl = discovered.url;\n\n const pkceMethods = authServer.metadata.code_challenge_methods_supported ?? [];\n if (pkceMethods.length > 0 && !pkceMethods.includes(\"S256\")) {\n return yield* new OAuthDiscoveryError({\n message: `Authorization server does not support PKCE S256 (advertised: ${pkceMethods.join(\", \")})`,\n });\n }\n\n const responseTypes = authServer.metadata.response_types_supported ?? [];\n if (responseTypes.length > 0 && !responseTypes.includes(\"code\")) {\n return yield* new OAuthDiscoveryError({\n message: `Authorization server does not support response_type=code (advertised: ${responseTypes.join(\", \")})`,\n });\n }\n\n // RFC 9728 §2: PRM `scopes_supported` is the resource-scoped list and is\n // authoritative when present. AS-level `scopes_supported` is global and\n // (per RFC 9728 §2) \"not meant to indicate that an OAuth client should\n // request all scopes in the list\", so we don't auto-expand it. When only\n // AS-level scopes are advertised we request none and let the AS apply\n // its default — callers wanting refresh tokens / specific scopes pass\n // them explicitly via `input.scopes`.\n const scopes: readonly string[] =\n input.scopes ??\n prior.scopes ??\n (resource?.metadata.scopes_supported && resource.metadata.scopes_supported.length > 0\n ? resource.metadata.scopes_supported\n : []);\n\n const negotiatedAuthMethod = negotiateAuthMethod(\n authServer.metadata.token_endpoint_auth_methods_supported,\n );\n if (!negotiatedAuthMethod) {\n return yield* new OAuthDiscoveryError({\n message: `Authorization server does not support a usable token_endpoint_auth_method (advertised: ${(\n authServer.metadata.token_endpoint_auth_methods_supported ?? []\n ).join(\", \")})`,\n });\n }\n\n // EXPLICIT registration shape (not a fallback of optional input): this DCR\n // flow always registers the interactive authorization_code + refresh_token\n // grants and the `code` response type. If the AS rejects refresh_token the\n // registration request fails loudly rather than silently downgrading.\n const baseClientMetadata: DynamicClientMetadata = {\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: negotiatedAuthMethod,\n client_name: \"Executor\",\n client_uri: \"https://executor.sh\",\n ...(scopes.length > 0 ? { scope: scopes.join(\" \") } : {}),\n ...(input.clientMetadata ?? {}),\n redirect_uris: input.clientMetadata?.redirect_uris ?? [input.redirectUrl],\n };\n\n const clientInformation =\n prior.clientInformation ??\n (yield* (() => {\n const reg = authServer.metadata.registration_endpoint;\n if (!reg) {\n return Effect.fail(\n new OAuthDiscoveryError({\n message:\n \"Authorization server does not advertise registration_endpoint — cannot auto-register a client\",\n }),\n );\n }\n return registerDynamicClient(\n { registrationEndpoint: reg, metadata: baseClientMetadata },\n options,\n );\n })());\n\n const resourceValue = prior.resource\n ? yield* validateResourceIndicator(prior.resource, expectedResource)\n : resource?.metadata.resource\n ? yield* validateResourceIndicator(resource.metadata.resource, expectedResource)\n : expectedResource;\n\n const codeVerifier = createPkceCodeVerifier();\n const codeChallenge = yield* Effect.promise(() => createPkceCodeChallenge(codeVerifier));\n\n const authorizationUrl = buildAuthorizationUrl({\n authorizationUrl: authServer.metadata.authorization_endpoint,\n clientId: clientInformation.client_id,\n redirectUrl: input.redirectUrl,\n scopes,\n state: input.state,\n codeChallenge,\n resource: resourceValue,\n endpointUrlPolicy: options.endpointUrlPolicy,\n });\n\n return {\n authorizationUrl,\n codeVerifier,\n state: {\n resourceMetadata: resource?.metadata ?? null,\n resourceMetadataUrl: resource?.metadataUrl ?? null,\n authorizationServerUrl,\n authorizationServerMetadataUrl: authServer.metadataUrl,\n authorizationServerMetadata: authServer.metadata,\n clientInformation,\n resource: resourceValue,\n scopes,\n },\n };\n });\n\nexport { createPkceCodeChallenge };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,SAAS,MAAM,QAAQ,MAAM,OAAO,iBAAiB;AAI9D,IAAM,eAAN,cAA2B,KAAK,YAAY,cAAc,EAG9D;AAAC;AAEG,IAAM,uBAAN,cAAmC,KAAK,YAAY,sBAAsB,EAE9E;AAAC;AAyBJ,IAAM,oBAAoB,CAAC,UAA4B;AACrD,MAAI,UAAU;AACd,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG;AAC7B,UAAM,MACJ,WAAW,OAAO,YAAY,WAAY,UAAsC;AAClF,QAAI,CAAC,IAAK,QAAO;AACjB,UAAM,OAAO,IAAI,MAAM;AAEvB,UAAM,UAAU,IAAI,SAAS;AAC7B,UAAM,aAAa,IAAI,OAAO;AAC9B,QAAI,SAAS,QAAS,QAAO;AAC7B,QACE,OAAO,YAAY,YACnB,8DAA8D,KAAK,OAAO,GAC1E;AACA,aAAO;AAAA,IACT;AACA,QAAI,CAAC,cAAc,eAAe,QAAS,QAAO;AAClD,cAAU;AAAA,EACZ;AACA,SAAO;AACT;AAEA,IAAM,eAAe,CAAC,UAAuC;AAC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N,IAAI,aAAa;AAAA,YACf,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAAA,QACL,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AAEH,QAAM,OAAO;AAAA,IACX,cAAc;AAAA,MACZ,MAAM;AAAA,MACN,KAAK;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,IACV;AAAA,IACA,aAAa;AAAA,MACX,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,KAAK;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ;AAAA,IACV;AAAA,IACA,WAAW;AAAA,MACT,MAAM;AAAA,MACN,OAAO;AAAA,IACT;AAAA,IACA,UAAU;AAAA,MACR,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,aAAa,CAAC,UAAuC;AAC3D,SAAO,WAAW,OAAO,OAAO,MAAM,UAAU,CAAC;AACnD,CAAC;","names":["table","Effect","Effect","Effect","table","changed","key","ast","minItems","maxItems","type","rules","schema","Effect","Effect","Option","Predicate","Schema","FetchHttpClient","Effect","Schema","Schema","Effect","Duration","Effect","Option","Schema","FetchHttpClient","Data","Effect","Predicate","Schema","Data","Schema","Effect","Predicate","response","Schema","Option","Effect","FetchHttpClient","Duration","registerDynamicClient","Effect","tool","Schema","Option","config","rules","effective","preview","policyRules","policy","oauth","FetchHttpClient","plugin","Predicate"]}