@executor-js/sdk 1.4.29 → 1.4.30

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 (142) hide show
  1. package/dist/blob.d.ts +2 -1
  2. package/dist/blob.d.ts.map +1 -1
  3. package/dist/chunk-2LU3SC64.js +7 -0
  4. package/dist/chunk-2LU3SC64.js.map +1 -0
  5. package/dist/chunk-7D4SUZUM.js +38 -0
  6. package/dist/chunk-7D4SUZUM.js.map +1 -0
  7. package/dist/chunk-B4YGTZF6.js +22 -0
  8. package/dist/chunk-B4YGTZF6.js.map +1 -0
  9. package/dist/chunk-BZNIRSMG.js +7873 -0
  10. package/dist/chunk-BZNIRSMG.js.map +1 -0
  11. package/dist/chunk-ECMCGZYE.js +5814 -0
  12. package/dist/chunk-ECMCGZYE.js.map +1 -0
  13. package/dist/{chunk-6SQWMOM4.js → chunk-MLNVNVRI.js} +2 -6
  14. package/dist/chunk-MLNVNVRI.js.map +1 -0
  15. package/dist/chunk-P2WKYAC5.js +1 -0
  16. package/dist/chunk-P2WKYAC5.js.map +1 -0
  17. package/dist/chunk-ZANQD7E2.js +1035 -0
  18. package/dist/chunk-ZANQD7E2.js.map +1 -0
  19. package/dist/client.d.ts +3 -0
  20. package/dist/client.d.ts.map +1 -1
  21. package/dist/client.js +2 -0
  22. package/dist/client.js.map +1 -1
  23. package/dist/config.d.ts +3 -7
  24. package/dist/config.d.ts.map +1 -1
  25. package/dist/core-schema.d.ts +283 -408
  26. package/dist/core-schema.d.ts.map +1 -1
  27. package/dist/core-tools.d.ts +6 -0
  28. package/dist/core-tools.d.ts.map +1 -0
  29. package/dist/core.js +120 -168
  30. package/dist/core.js.map +1 -1
  31. package/dist/credential-bindings.d.ts +86 -24
  32. package/dist/credential-bindings.d.ts.map +1 -1
  33. package/dist/errors.d.ts +1 -0
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/executor.d.ts +46 -12
  36. package/dist/executor.d.ts.map +1 -1
  37. package/dist/fuma-runtime.d.ts +50 -0
  38. package/dist/fuma-runtime.d.ts.map +1 -0
  39. package/dist/http-source.d.ts +109 -0
  40. package/dist/http-source.d.ts.map +1 -0
  41. package/dist/http-source.js +155 -0
  42. package/dist/http-source.js.map +1 -0
  43. package/dist/index.d.ts +17 -12
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +44 -21
  46. package/dist/index.js.map +1 -1
  47. package/dist/oauth-service.d.ts +2 -10
  48. package/dist/oauth-service.d.ts.map +1 -1
  49. package/dist/oauth.d.ts +9 -1
  50. package/dist/oauth.d.ts.map +1 -1
  51. package/dist/plugin-storage.d.ts +40 -0
  52. package/dist/plugin-storage.d.ts.map +1 -0
  53. package/dist/plugin.d.ts +110 -34
  54. package/dist/plugin.d.ts.map +1 -1
  55. package/dist/promise-executor.d.ts +33 -8
  56. package/dist/promise-executor.d.ts.map +1 -1
  57. package/dist/promise.d.ts +3 -3
  58. package/dist/promise.d.ts.map +1 -1
  59. package/dist/schema-refs.d.ts +1 -0
  60. package/dist/schema-refs.d.ts.map +1 -1
  61. package/dist/schema-refs.test.d.ts +2 -0
  62. package/dist/schema-refs.test.d.ts.map +1 -0
  63. package/dist/schema-types.d.ts +22 -8
  64. package/dist/schema-types.d.ts.map +1 -1
  65. package/dist/scope-policy.d.ts +23 -0
  66. package/dist/scope-policy.d.ts.map +1 -0
  67. package/dist/scope-policy.test.d.ts +2 -0
  68. package/dist/scope-policy.test.d.ts.map +1 -0
  69. package/dist/scope.d.ts +10 -0
  70. package/dist/scope.d.ts.map +1 -1
  71. package/dist/secrets.d.ts +1 -1
  72. package/dist/secrets.d.ts.map +1 -1
  73. package/dist/shared.d.ts +13 -0
  74. package/dist/shared.d.ts.map +1 -0
  75. package/dist/shared.js +103 -0
  76. package/dist/shared.js.map +1 -0
  77. package/dist/sqlite-test-db-OK2WQNR5.js +8 -0
  78. package/dist/sqlite-test-db-OK2WQNR5.js.map +1 -0
  79. package/dist/sqlite-test-db.d.ts +22 -0
  80. package/dist/sqlite-test-db.d.ts.map +1 -0
  81. package/dist/test-config.d.ts +45 -4
  82. package/dist/test-config.d.ts.map +1 -1
  83. package/dist/testing/oauth-test-server.d.ts +80 -0
  84. package/dist/testing/oauth-test-server.d.ts.map +1 -0
  85. package/dist/testing.d.ts +4 -1
  86. package/dist/testing.d.ts.map +1 -1
  87. package/dist/testing.js +706 -18
  88. package/dist/testing.js.map +1 -1
  89. package/dist/testing.test.d.ts +2 -0
  90. package/dist/testing.test.d.ts.map +1 -0
  91. package/dist/tool-result.d.ts +22 -0
  92. package/dist/tool-result.d.ts.map +1 -0
  93. package/dist/tool-result.test.d.ts +2 -0
  94. package/dist/tool-result.test.d.ts.map +1 -0
  95. package/dist/types.d.ts +1 -0
  96. package/dist/types.d.ts.map +1 -1
  97. package/dist/vendor/json-schema-to-typescript/applySchemaTyping.d.ts +3 -0
  98. package/dist/vendor/json-schema-to-typescript/applySchemaTyping.d.ts.map +1 -0
  99. package/dist/vendor/json-schema-to-typescript/compat.d.ts +10 -0
  100. package/dist/vendor/json-schema-to-typescript/compat.d.ts.map +1 -0
  101. package/dist/vendor/json-schema-to-typescript/formatter.d.ts +3 -0
  102. package/dist/vendor/json-schema-to-typescript/formatter.d.ts.map +1 -0
  103. package/dist/vendor/json-schema-to-typescript/generator.d.ts +7 -0
  104. package/dist/vendor/json-schema-to-typescript/generator.d.ts.map +1 -0
  105. package/dist/vendor/json-schema-to-typescript/index.d.ts +93 -0
  106. package/dist/vendor/json-schema-to-typescript/index.d.ts.map +1 -0
  107. package/dist/vendor/json-schema-to-typescript/linker.d.ts +8 -0
  108. package/dist/vendor/json-schema-to-typescript/linker.d.ts.map +1 -0
  109. package/dist/vendor/json-schema-to-typescript/normalizer.d.ts +5 -0
  110. package/dist/vendor/json-schema-to-typescript/normalizer.d.ts.map +1 -0
  111. package/dist/vendor/json-schema-to-typescript/optimizer.d.ts +4 -0
  112. package/dist/vendor/json-schema-to-typescript/optimizer.d.ts.map +1 -0
  113. package/dist/vendor/json-schema-to-typescript/optionValidator.d.ts +3 -0
  114. package/dist/vendor/json-schema-to-typescript/optionValidator.d.ts.map +1 -0
  115. package/dist/vendor/json-schema-to-typescript/parser.d.ts +8 -0
  116. package/dist/vendor/json-schema-to-typescript/parser.d.ts.map +1 -0
  117. package/dist/vendor/json-schema-to-typescript/resolver.d.ts +7 -0
  118. package/dist/vendor/json-schema-to-typescript/resolver.d.ts.map +1 -0
  119. package/dist/vendor/json-schema-to-typescript/types/AST.d.ts +108 -0
  120. package/dist/vendor/json-schema-to-typescript/types/AST.d.ts.map +1 -0
  121. package/dist/vendor/json-schema-to-typescript/types/JSONSchema.d.ts +103 -0
  122. package/dist/vendor/json-schema-to-typescript/types/JSONSchema.d.ts.map +1 -0
  123. package/dist/vendor/json-schema-to-typescript/types/json-schema.d.ts +34 -0
  124. package/dist/vendor/json-schema-to-typescript/types/json-schema.d.ts.map +1 -0
  125. package/dist/vendor/json-schema-to-typescript/typesOfSchema.d.ts +11 -0
  126. package/dist/vendor/json-schema-to-typescript/typesOfSchema.d.ts.map +1 -0
  127. package/dist/vendor/json-schema-to-typescript/utils.d.ts +30 -0
  128. package/dist/vendor/json-schema-to-typescript/utils.d.ts.map +1 -0
  129. package/dist/vendor/json-schema-to-typescript/validator.d.ts +3 -0
  130. package/dist/vendor/json-schema-to-typescript/validator.d.ts.map +1 -0
  131. package/package.json +17 -2
  132. package/dist/chunk-6SQWMOM4.js.map +0 -1
  133. package/dist/chunk-I2OEQ2GJ.js +0 -103
  134. package/dist/chunk-I2OEQ2GJ.js.map +0 -1
  135. package/dist/chunk-OIJL6F6M.js +0 -5507
  136. package/dist/chunk-OIJL6F6M.js.map +0 -1
  137. package/dist/error-handling.test.d.ts +0 -2
  138. package/dist/error-handling.test.d.ts.map +0 -1
  139. package/dist/scoped-adapter.d.ts +0 -28
  140. package/dist/scoped-adapter.d.ts.map +0 -1
  141. package/dist/scoped-adapter.test.d.ts +0 -2
  142. package/dist/scoped-adapter.test.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/blob.ts","../src/connections.ts","../src/plugin.ts","../src/tool-result.ts","../src/core-tools.ts","../src/elicitation.ts","../src/secrets.ts","../src/oauth-helpers.ts","../src/oauth-discovery.ts","../src/oauth-service.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/hosted-http-client.ts","../src/executor.ts","../src/scope.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\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\";\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 /** Walk the scope stack (innermost first) and return the first\n * non-null value for `key`. */\n readonly get: (key: string) => Effect.Effect<string | null, StorageError>;\n /** Write `value` under `key` at the named scope. Scope must be one\n * of the executor's configured scopes. */\n readonly put: (\n key: string,\n value: string,\n options: { readonly scope: string },\n ) => Effect.Effect<void, StorageError>;\n /** Delete `key` at the named scope. */\n readonly delete: (\n key: string,\n options: { readonly scope: string },\n ) => Effect.Effect<void, StorageError>;\n /** Walk the scope stack and return true if any scope has a value for `key`. */\n readonly has: (key: string) => Effect.Effect<boolean, StorageError>;\n}\n\nconst assertScope = (scope: string, scopes: readonly string[]): Effect.Effect<void, StorageError> =>\n scopes.includes(scope)\n ? Effect.void\n : Effect.fail(\n new StorageError({\n message:\n `Blob write targets scope \"${scope}\" which is not in the ` +\n `executor's scope stack [${scopes.join(\", \")}].`,\n cause: undefined,\n }),\n );\n\nconst nsFor = (scope: string, pluginId: string) => `${scope}/${pluginId}`;\n\n/**\n * Bind a `BlobStore` to a specific scope stack and plugin id. Reads\n * fall through the stack; writes require an explicit scope. Used by\n * the executor to build the `blobs` field handed to each plugin's\n * `storage` factory.\n */\nexport const pluginBlobStore = (\n store: BlobStore,\n scopes: readonly string[],\n pluginId: string,\n): PluginBlobStore => ({\n get: (key) =>\n Effect.gen(function* () {\n const namespaces = scopes.map((s) => nsFor(s, pluginId));\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(assertScope(options.scope, scopes), () =>\n store.put(nsFor(options.scope, pluginId), key, value),\n ),\n delete: (key, options) =>\n Effect.flatMap(assertScope(options.scope, scopes), () =>\n store.delete(nsFor(options.scope, pluginId), key),\n ),\n has: (key) =>\n store\n .getMany(\n scopes.map((s) => nsFor(s, pluginId)),\n key,\n )\n .pipe(Effect.map((hits) => hits.size > 0)),\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\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 { Data, Effect, Schema } from \"effect\";\n\nimport { ConnectionId, ScopeId, SecretId } from \"./ids\";\n\n// ---------------------------------------------------------------------------\n// Connections — the product-level \"sign-in state\" primitive. A Connection\n// owns one or more backing `secret` rows (access + refresh tokens) via\n// `secret.owned_by_connection_id`; the user sees the Connection, the SDK\n// handles every refresh internally. Plugins register a refresh handler\n// per provider via `plugin.connectionProviders`, mirroring the shape of\n// `plugin.secretProviders` for ordinary secret backends.\n// ---------------------------------------------------------------------------\n\n/** Minimal JSON-object carrier for the plugin-owned `providerState`\n * blob. The SDK never inspects its shape; plugins encode/decode their\n * own structure. Never sensitive — that's what the secret rows are\n * for. */\nexport const ConnectionProviderState = Schema.Record(Schema.String, Schema.Unknown);\nexport type ConnectionProviderState = typeof ConnectionProviderState.Type;\n\n// ---------------------------------------------------------------------------\n// ConnectionRef — metadata projection returned from `ctx.connections.list`\n// / `executor.connections.list`. Holds token secret ids (so a plugin can\n// reference them from its source config) but not token values.\n// ---------------------------------------------------------------------------\n\nexport const ConnectionRef = Schema.Struct({\n id: ConnectionId,\n scopeId: ScopeId,\n provider: Schema.String,\n identityLabel: Schema.NullOr(Schema.String),\n accessTokenSecretId: SecretId,\n refreshTokenSecretId: Schema.NullOr(SecretId),\n /** Epoch ms when the access token expires; null if not declared. */\n expiresAt: Schema.NullOr(Schema.Number),\n /** OAuth-style scope string as returned by the token endpoint. Named\n * `oauthScope` to avoid collision with the executor scope id. */\n oauthScope: Schema.NullOr(Schema.String),\n providerState: Schema.NullOr(ConnectionProviderState),\n createdAt: Schema.Date,\n updatedAt: Schema.Date,\n});\nexport type ConnectionRef = typeof ConnectionRef.Type;\n\n// ---------------------------------------------------------------------------\n// CreateConnectionInput — what a plugin passes to create a fresh\n// Connection after a successful OAuth exchange. The SDK writes the\n// backing secret rows and the connection row in one transaction, and\n// stamps `owned_by_connection_id` so `ctx.secrets.list` automatically\n// hides them from the bare-secrets UI.\n//\n// `provider` must match a registered `ConnectionProvider.key`. The SDK\n// validates this at create time so a typo surfaces immediately instead\n// of the first time a refresh is attempted.\n// ---------------------------------------------------------------------------\n\nexport const TokenMaterial = Schema.Struct({\n /** Target secret id. Plugins typically derive this from the source id\n * + a stable suffix (e.g. `${sourceId}.access_token`). */\n secretId: SecretId,\n /** Display name stamped on the secret row. Only visible to code — the\n * Connections UI hides connection-owned secrets. */\n name: Schema.String,\n value: Schema.String,\n});\nexport type TokenMaterial = typeof TokenMaterial.Type;\n\nexport const CreateConnectionInput = Schema.Struct({\n id: ConnectionId,\n /** Executor scope id that will own this connection + its backing\n * secrets. This is the sharing boundary: a user scope is personal,\n * an org/workspace scope is shared with descendants. */\n scope: ScopeId,\n provider: Schema.String,\n identityLabel: Schema.NullOr(Schema.String),\n accessToken: TokenMaterial,\n refreshToken: Schema.NullOr(TokenMaterial),\n expiresAt: Schema.NullOr(Schema.Number),\n /** OAuth-style scope string. Distinct from the executor scope above. */\n oauthScope: Schema.NullOr(Schema.String),\n providerState: Schema.NullOr(ConnectionProviderState),\n});\nexport type CreateConnectionInput = typeof CreateConnectionInput.Type;\n\n// ---------------------------------------------------------------------------\n// ConnectionRefreshError — typed error surface for refresh handlers.\n// Plugins either return a fresh token envelope or fail with this error;\n// the SDK rethrows it from `ctx.connections.accessToken` callers.\n// ---------------------------------------------------------------------------\n\nexport class ConnectionRefreshError extends Data.TaggedError(\"ConnectionRefreshError\")<{\n readonly connectionId: ConnectionId;\n readonly message: string;\n /**\n * Set by providers when the refresh failed in a way that the stored\n * refresh token cannot recover from (RFC 6749 §5.2 `invalid_grant`\n * — the AS has revoked the grant, the user changed their password,\n * the refresh token rotated out from under us, ...). The SDK\n * translates this into a `ConnectionReauthRequiredError` so callers\n * can prompt the user to sign in again instead of silently retrying.\n */\n readonly reauthRequired?: boolean;\n readonly cause?: unknown;\n}> {}\n\n// ---------------------------------------------------------------------------\n// ConnectionRefreshInput — what the SDK hands to a provider's `refresh`\n// callback. Includes the current refresh-token value (already resolved\n// from the secret row) and the opaque providerState blob so handlers\n// don't need to hit secrets themselves.\n// ---------------------------------------------------------------------------\n\nexport interface ConnectionRefreshInput {\n readonly connectionId: ConnectionId;\n readonly scopeId: ScopeId;\n readonly identityLabel: string | null;\n /** Resolved refresh token value, or null if the connection has none. */\n readonly refreshToken: string | null;\n /** Plugin-owned blob persisted at create / previous refresh. */\n readonly providerState: ConnectionProviderState | null;\n /** OAuth scope string from the last token issuance. */\n readonly oauthScope: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// ConnectionRefreshResult — what a provider's `refresh` callback returns\n// on success. The SDK writes the new token values through the secret\n// providers, updates `expires_at` / `scope` / `provider_state` on the\n// connection row, and returns the fresh access token to the caller.\n//\n// `refreshToken` is optional: if the AS rotates refresh tokens it's\n// present, if the AS issues long-lived refresh tokens it's absent. The\n// SDK updates the refresh secret only when a new value is supplied.\n// ---------------------------------------------------------------------------\n\nexport interface ConnectionRefreshResult {\n readonly accessToken: string;\n readonly refreshToken?: string | null;\n readonly expiresAt?: number | null;\n readonly oauthScope?: string | null;\n readonly providerState?: ConnectionProviderState | null;\n}\n\n// ---------------------------------------------------------------------------\n// ConnectionProvider — plugin contribution. Registered via\n// `plugin.connectionProviders`. One per refresh strategy (oauth2\n// authorization-code, oauth2 client-credentials, per-provider custom,\n// etc). Keyed by `key`; the connection row's `provider` column\n// references this key.\n//\n// Omitting `refresh` means \"tokens minted by this provider never\n// refresh\" — accessToken(id) just returns the stored value. Useful for\n// long-lived API tokens wrapped as connections for UX consistency.\n// ---------------------------------------------------------------------------\n\nexport interface ConnectionProvider {\n readonly key: string;\n readonly refresh?: (\n input: ConnectionRefreshInput,\n ) => Effect.Effect<ConnectionRefreshResult, ConnectionRefreshError>;\n}\n\n// ---------------------------------------------------------------------------\n// UpdateConnectionTokensInput — for flows that re-exchange tokens out\n// of band (e.g. an OAuth re-auth where the user signs in again). The\n// SDK overwrites the backing secrets and updates the connection row in\n// one transaction.\n// ---------------------------------------------------------------------------\n\nexport const UpdateConnectionTokensInput = Schema.Struct({\n id: ConnectionId,\n accessToken: Schema.String,\n refreshToken: Schema.optional(Schema.NullOr(Schema.String)),\n expiresAt: Schema.optional(Schema.NullOr(Schema.Number)),\n oauthScope: Schema.optional(Schema.NullOr(Schema.String)),\n providerState: Schema.optional(Schema.NullOr(ConnectionProviderState)),\n identityLabel: Schema.optional(Schema.NullOr(Schema.String)),\n});\nexport type UpdateConnectionTokensInput = typeof UpdateConnectionTokensInput.Type;\n\nexport const RemoveConnectionInput = Schema.Struct({\n id: ConnectionId,\n /** Scope id whose connection row and owned token secrets should be removed. */\n targetScope: ScopeId,\n});\nexport type RemoveConnectionInput = typeof RemoveConnectionInput.Type;\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 { FumaTables, IFumaClient, StorageFailure, TablesToFumaSchema } from \"./fuma-runtime\";\n\nimport type { PluginBlobStore } from \"./blob\";\nimport type {\n ConnectionProvider,\n ConnectionRef,\n ConnectionRefreshError,\n CreateConnectionInput,\n RemoveConnectionInput,\n UpdateConnectionTokensInput,\n} from \"./connections\";\nimport type {\n CredentialBindingRef,\n CredentialBindingsFacade,\n RemoveSourceCredentialBindingInput,\n SetSourceCredentialBindingInput,\n SourceCredentialBindingSlotInput,\n SourceCredentialBindingSourceInput,\n} from \"./credential-bindings\";\nimport type { DefinitionsInput, SourceInput, ToolAnnotations, ToolRow } from \"./core-schema\";\nimport type { ScopeId } from \"./ids\";\nimport type { RefreshSourceInput, RemoveSourceInput, Source, SourceDetectionResult } from \"./types\";\nimport type {\n ElicitationDeclinedError,\n ElicitationHandler,\n ElicitationRequest,\n ElicitationResponse,\n} from \"./elicitation\";\nimport type {\n ConnectionInUseError,\n ConnectionNotFoundError,\n ConnectionProviderNotRegisteredError,\n ConnectionReauthRequiredError,\n ConnectionRefreshNotSupportedError,\n SecretInUseError,\n SecretOwnedByConnectionError,\n SourceRemovalNotAllowedError,\n} from \"./errors\";\nimport type { OAuthService } from \"./oauth\";\nimport type { PluginStorageFacade } from \"./plugin-storage\";\nimport type {\n CreateToolPolicyInput,\n RemoveToolPolicyInput,\n ToolPolicy,\n UpdateToolPolicyInput,\n} from \"./policies\";\nimport type { Scope } from \"./scope\";\nimport type { RemoveSecretInput, SecretProvider, SecretRef, SetSecretInput } from \"./secrets\";\nimport type { Usage, UsagesForConnectionInput, UsagesForSecretInput } from \"./usages\";\n\n// ---------------------------------------------------------------------------\n// StorageDeps — backing passed to a plugin's `storage` factory. Plugins see\n// FumaDB through the Effect boundary, narrowed to their declared tables. Scope\n// behavior is domain code, not hidden adapter behavior: reads should include\n// `scopedWhere(...)` and writes stamp an explicit `scope_id`.\n// ---------------------------------------------------------------------------\n\nexport interface StorageDeps<TTables extends FumaTables | undefined = FumaTables> {\n /**\n * Precedence-ordered scope stack visible to this executor. Innermost\n * first. Reads on scoped tables walk every scope; writes require the\n * plugin to name a target scope explicitly (via `scope_id` on the\n * row payload, via `options.scope` on the blob store).\n */\n readonly scopes: readonly Scope[];\n /** Plugin-facing FumaDB query boundary. */\n readonly fuma: IFumaClient<TablesToFumaSchema<TTables>>;\n readonly blobs: PluginBlobStore;\n readonly pluginStorage: PluginStorageFacade;\n}\n\n// ---------------------------------------------------------------------------\n// Elicit — suspends the fiber, calls the invoke-time elicitation\n// handler, resumes with the user's response. Available on both static\n// tool handlers and dynamic `invokeTool` handlers. Threaded through\n// the executor from `createExecutor({ onElicitation })`.\n// ---------------------------------------------------------------------------\n\nexport type Elicit = (\n request: ElicitationRequest,\n) => Effect.Effect<ElicitationResponse, ElicitationDeclinedError>;\n\n// ---------------------------------------------------------------------------\n// PluginCtx — threaded into every extension method, static tool handler,\n// and dynamic tool handler. No raw adapter, no raw blobs. Core writes\n// go through `core.sources.register` / `core.definitions.register`.\n// ---------------------------------------------------------------------------\n\nexport interface PluginCtx<TStore = unknown> {\n /**\n * Precedence-ordered scope stack visible to this executor. Innermost\n * first. Plugins that write scoped rows must pick an element of\n * `scopes` as the `scope`/`scope_id` they stamp; reads should apply\n * explicit FumaDB scope predicates or use `ctx.secrets` / `ctx.connections`\n * helpers.\n */\n readonly scopes: readonly Scope[];\n readonly storage: TStore;\n readonly pluginStorage: PluginStorageFacade;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient>;\n\n readonly core: {\n readonly sources: {\n readonly register: (input: SourceInput) => Effect.Effect<void, StorageFailure>;\n readonly unregister: (input: RemoveSourceInput) => Effect.Effect<void, StorageFailure>;\n readonly update: (input: {\n readonly id: string;\n readonly scope: string;\n readonly name?: string;\n readonly url?: string | null;\n }) => Effect.Effect<void, StorageFailure>;\n readonly list: () => Effect.Effect<readonly Source[], StorageFailure>;\n readonly remove: (\n input: RemoveSourceInput,\n ) => Effect.Effect<void, SourceRemovalNotAllowedError | StorageFailure>;\n readonly refresh: (input: RefreshSourceInput) => Effect.Effect<void, StorageFailure>;\n readonly detect: (\n url: string,\n ) => Effect.Effect<readonly SourceDetectionResult[], StorageFailure>;\n readonly configure: (input: {\n readonly source: {\n readonly id: string;\n readonly scope: ScopeId | string;\n };\n readonly scope: ScopeId | string;\n readonly type?: string;\n readonly config: unknown;\n }) => Effect.Effect<unknown, StorageFailure>;\n readonly listBindings: (\n input: SourceCredentialBindingSourceInput,\n ) => Effect.Effect<readonly CredentialBindingRef[], StorageFailure>;\n readonly resolveBinding: (\n input: SourceCredentialBindingSlotInput,\n ) => Effect.Effect<CredentialBindingRef | null, StorageFailure>;\n readonly setBinding: (\n input: SetSourceCredentialBindingInput,\n ) => Effect.Effect<CredentialBindingRef, StorageFailure>;\n readonly removeBinding: (\n input: RemoveSourceCredentialBindingInput,\n ) => Effect.Effect<void, StorageFailure>;\n /** Source configuration declarations for every plugin that\n * supports `executor.sources.configure`. Exposed to core tools\n * so agent-facing configuration surfaces can describe the\n * plugin-specific payload shape before dispatching a write. */\n readonly configureSchemas: () => readonly SourceConfigureSchema[];\n readonly presets: () => readonly SourcePresetCatalogEntry[];\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 /** Register shared JSON-schema `$defs` for a source. Tool\n * input/output schemas registered via `sources.register` can carry\n * `$ref: \"#/$defs/X\"` pointers; `executor.tools.schema(toolId)`\n * returns matching reachable defs alongside the schema roots. Call\n * inside the same `ctx.transaction` as `sources.register` for atomicity.\n * Replaces any existing defs for the given sourceId. */\n readonly definitions: {\n readonly register: (input: DefinitionsInput) => Effect.Effect<void, StorageFailure>;\n };\n };\n\n readonly secrets: {\n readonly get: (\n id: string,\n ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>;\n readonly getAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>;\n /** List user-visible secrets. Connection-owned secrets (rows with\n * `owned_by_connection_id` set) are filtered out so they don't\n * clutter the UI — users see the Connection instead. */\n readonly list: () => Effect.Effect<\n readonly {\n readonly id: string;\n readonly scopeId: ScopeId;\n readonly name: string;\n readonly provider: string;\n }[],\n StorageFailure\n >;\n readonly status: (id: string) => Effect.Effect<\"resolved\" | \"missing\", StorageFailure>;\n readonly usages: (id: string) => Effect.Effect<readonly Usage[], StorageFailure>;\n readonly providers: () => Effect.Effect<readonly string[], never>;\n /** Write a secret value through a provider. Used by plugins that\n * mint secrets on behalf of the user (OAuth2 token storage,\n * interactive onboarding flows). Normally writes go through\n * `executor.secrets.set` on the host surface, but OAuth2 refresh\n * and one-shot token capture from plugin-owned flows need it here\n * too. Same routing rules as the host-level setter. */\n readonly set: (input: SetSecretInput) => Effect.Effect<SecretRef, StorageFailure>;\n /** Delete a secret from its pinned provider and the core table.\n * Rejects with `SecretOwnedByConnectionError` if the row is owned\n * by a connection — callers must go through `connections.remove`\n * to drop the whole sign-in. Rejects with `SecretInUseError` if\n * any plugin reports the secret as in use; the caller should ask\n * the user to detach the listed sources first. */\n readonly remove: (\n input: RemoveSecretInput,\n ) => Effect.Effect<void, SecretOwnedByConnectionError | SecretInUseError | StorageFailure>;\n };\n\n /** Connections — product-level sign-in state. Owns backing secret\n * rows via `secret.owned_by_connection_id`. Plugins call\n * `connections.accessToken(id)` at invoke time to get a guaranteed-\n * fresh token (the SDK handles refresh via the registered provider\n * keyed by `connection.provider`). */\n readonly connections: {\n readonly get: (id: string) => Effect.Effect<ConnectionRef | null, StorageFailure>;\n readonly getAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<ConnectionRef | null, StorageFailure>;\n readonly list: () => Effect.Effect<readonly ConnectionRef[], StorageFailure>;\n readonly usages: (id: string) => Effect.Effect<readonly Usage[], StorageFailure>;\n readonly providers: () => Effect.Effect<readonly string[], never>;\n readonly create: (\n input: CreateConnectionInput,\n ) => Effect.Effect<ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure>;\n readonly updateTokens: (\n input: UpdateConnectionTokensInput,\n ) => Effect.Effect<ConnectionRef, ConnectionNotFoundError | StorageFailure>;\n readonly setIdentityLabel: (\n id: string,\n label: string | null,\n ) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>;\n /** Get a guaranteed-fresh access token. Calls the provider's\n * `refresh` handler if `expires_at` is in the past / within the\n * refresh skew window. */\n readonly accessToken: (\n id: string,\n ) => Effect.Effect<\n string,\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure\n >;\n readonly accessTokenAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<\n string,\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure\n >;\n /** Refuses with `ConnectionInUseError` if any plugin reports the\n * connection as in use. Caller surfaces the `usages` list to the\n * user. */\n readonly remove: (\n input: RemoveConnectionInput,\n ) => Effect.Effect<void, ConnectionInUseError | StorageFailure>;\n };\n\n readonly credentialBindings: CredentialBindingsFacade;\n\n /** Shared OAuth service. Plugins use this to probe/start/complete OAuth\n * flows; invocation should still resolve tokens via `connections.accessToken`. */\n readonly oauth: OAuthService;\n\n /** Run `effect` inside a FumaDB transaction. Use this in extension methods that\n * need atomicity across plugin storage writes AND core source/tool\n * registration. */\n readonly transaction: <A, E>(effect: Effect.Effect<A, E>) => Effect.Effect<A, E | StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Static tool / source declarations. Pure data + handlers declared at\n// plugin-definition time.\n//\n// Importantly, `StaticToolDecl.handler` does NOT reference TExtension.\n// If it did, the nested generic would break inference for the whole\n// PluginSpec (TS would fall back to the `object` constraint on TExtension).\n// `self: NoInfer<TExtension>` lives on `staticSources` one level up\n// instead, and plugin authors close over it via the arrow-function\n// closure when they write their handler.\n// ---------------------------------------------------------------------------\n\nexport interface StaticToolHandlerInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly args: unknown;\n /** Suspend the fiber to request user input. The handler passed to\n * `createExecutor({ onElicitation })` is called. */\n readonly elicit: Elicit;\n}\n\nexport interface StaticToolExecuteContext<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n /** Suspend the fiber to request user input. The handler passed to\n * `createExecutor({ onElicitation })` is called. */\n readonly elicit: Elicit;\n}\n\nexport type StaticToolSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output> &\n StandardJSONSchemaV1<Input, Output>;\n\nexport interface StaticToolDecl<TStore = unknown> {\n readonly name: string;\n readonly description: string;\n readonly inputSchema?: StaticToolSchema;\n readonly outputSchema?: StaticToolSchema;\n /** Default-policy annotations — `requiresApproval`, `approvalDescription`,\n * `mayElicit`. Enforced by the executor before the handler runs.\n * Inline because static tools have no plugin storage to resolve from;\n * the plugin author literally writes this at definition time. */\n readonly annotations?: ToolAnnotations;\n readonly handler: (input: StaticToolHandlerInput<TStore>) => Effect.Effect<unknown, unknown>;\n}\n\nconst decodeStaticToolArgs = (\n schema: StaticToolSchema | undefined,\n args: unknown,\n): Effect.Effect<unknown, unknown> => {\n if (schema == null) return Effect.succeed(args);\n return Effect.promise(() => Promise.resolve(schema[\"~standard\"].validate(args))).pipe(\n Effect.flatMap((result) =>\n \"value\" in result ? Effect.succeed(result.value) : Effect.fail(result),\n ),\n );\n};\n\nexport interface StaticToolInput<\n TStore = unknown,\n TInputSchema extends StaticToolSchema | undefined = StaticToolSchema | undefined,\n> {\n readonly name: string;\n readonly description: string;\n readonly inputSchema?: TInputSchema;\n readonly outputSchema?: StaticToolSchema;\n /** Default-policy annotations — `requiresApproval`, `approvalDescription`,\n * `mayElicit`. Enforced by the executor before the handler runs. */\n readonly annotations?: ToolAnnotations;\n readonly execute: (\n args: TInputSchema extends StaticToolSchema\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : unknown,\n context: StaticToolExecuteContext<TStore>,\n ) => Effect.Effect<unknown, unknown>;\n}\n\nexport const tool = <\n TStore = unknown,\n TInputSchema extends StaticToolSchema | undefined = StaticToolSchema | undefined,\n>(\n input: StaticToolInput<TStore, TInputSchema>,\n): StaticToolDecl<TStore> => ({\n name: input.name,\n description: input.description,\n inputSchema: input.inputSchema,\n outputSchema: input.outputSchema,\n annotations: input.annotations,\n handler: ({ args, ctx, elicit }) =>\n decodeStaticToolArgs(input.inputSchema, args).pipe(\n Effect.flatMap((decoded) =>\n input.execute(\n decoded as TInputSchema extends StaticToolSchema\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : unknown,\n { ctx, elicit },\n ),\n ),\n ),\n});\n\nexport interface StaticSourceDecl<TStore = unknown> {\n readonly id: string;\n readonly kind: string;\n readonly name: string;\n readonly url?: string;\n /** Static sources default to `canRemove: false` because they are\n * plugin-provided surfaces and shouldn't usually be user-removable.\n * Override only if you really want that. */\n readonly canRemove?: boolean;\n readonly canRefresh?: boolean;\n readonly canEdit?: boolean;\n readonly tools: readonly StaticToolDecl<TStore>[];\n}\n\n// ---------------------------------------------------------------------------\n// Dynamic invoke / source lifecycle inputs.\n// ---------------------------------------------------------------------------\n\nexport interface InvokeToolInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n /** Already-loaded tool row. Plugin doesn't need to re-fetch or parse\n * the tool id. Carries source_id, name, input/output schemas,\n * annotations. */\n readonly toolRow: ToolRow;\n readonly args: unknown;\n /** Elicitation handle for plugins that need mid-invocation user input\n * (onepassword auth prompt, interactive MCP tools, etc.). */\n readonly elicit: Elicit;\n}\n\nexport interface SourceLifecycleInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly sourceId: string;\n /**\n * Scope of the source row being removed/refreshed — resolved by the\n * SDK's `sources.remove` / `sources.refresh` via innermost-wins lookup\n * across the executor's scope stack. Plugins that own a side table\n * keyed by (id, scope_id) must pin their own cleanup to this scope;\n * relying on stack-wide scope fall-through\n * would widen the mutation across the whole stack and wipe a\n * shadowed outer-scope row.\n */\n readonly scope: string;\n}\n\nexport interface ConfigureSourceHandlerInput<TStore = unknown> {\n readonly ctx: PluginCtx<TStore>;\n readonly sourceId: string;\n readonly sourceScope: string;\n readonly targetScope: string;\n readonly config: unknown;\n}\n\nexport interface SourceConfigureDecl<TStore = unknown> {\n readonly type: string;\n readonly schema?: StaticToolSchema | EffectSchema.Decoder<unknown, never>;\n readonly configure: (\n input: ConfigureSourceHandlerInput<TStore>,\n ) => Effect.Effect<unknown, unknown>;\n}\n\nexport interface SourceConfigureSchema {\n readonly pluginId: string;\n readonly type: string;\n readonly schema?: unknown;\n}\n\nexport interface SourcePreset {\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 SourcePresetCatalogEntry extends SourcePreset {\n readonly pluginId: string;\n}\n\n// ---------------------------------------------------------------------------\n// PluginSpec — what a `definePlugin(factory)` call returns.\n// ---------------------------------------------------------------------------\n\n// Defaults are `any` for slots that surface in contravariant positions\n// (storage/extension callbacks consume `TStore`/`TSchema`; `staticSources`\n// closes over `TExtension` via `NoInfer`). `any` is bivariant, so\n// `Plugin<string>` is a structural supertype of every concrete plugin\n// — `AnyPlugin = Plugin<string>` keeps the generic explosion contained\n// to this single declaration. Concrete specs ignore the defaults; TS\n// infers each slot from the literal returned by the author factory.\n//\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface PluginSpec<\n TId extends string = string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtension extends object = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TStore = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TSchema extends FumaTables | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = any,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n> {\n readonly id: TId;\n /** npm package name. The Vite plugin uses this to derive the\n * `./client` import path for the frontend bundle (so the same\n * `executor.config.ts` drives both server and client) — `${packageName}/client`\n * is what gets bundled. The author writes the same string they\n * publish to npm; no transforms, no scope conventions. Required for\n * plugins that ship a `./client` entry; can be omitted for SDK-only\n * plugins (no client bundle = nothing to resolve). */\n readonly packageName?: string;\n /** Plugin-declared schema. Merged with coreSchema and other plugins'\n * tables at executor startup via `collectTables`. The type flows\n * into the `storage` factory's `deps.fuma` as a FumaDB query boundary so\n * plugins get narrowed table names + typed rows for free. */\n readonly schema?: TSchema;\n /** Build the plugin's typed store from backing. `deps.fuma` is\n * already narrowed to this plugin's tables; `deps.blobs` is already\n * scoped to the plugin id so key collisions across plugins are\n * structurally impossible. */\n readonly storage: (deps: StorageDeps<TSchema>) => TStore;\n\n /** JSON-serializable config the plugin wants its `./client` bundle to\n * see. The Vite plugin reads this off each `executor.config.ts` spec\n * at build time and bakes it into the virtual `plugins-client`\n * module by calling the plugin's default `./client` export as a\n * factory: `__p(<JSON.stringify(clientConfig)>)`. Plugins that don't\n * set this stay as bare-value default exports — no churn.\n *\n * Use this when a server-side option (e.g. `dangerouslyAllowStdioMCP`)\n * needs to drive client UI behaviour: declaring it once in\n * `executor.config.ts` flows through to the bundle automatically,\n * with no runtime fetch and no parallel client-side flag to keep in\n * sync. */\n readonly clientConfig?: unknown;\n\n /** Source presets shown by the web UI's \"Popular sources\" list and\n * exposed through core tools for agents. Keep this server-safe:\n * no React components, only JSON-serializable metadata and optional\n * add-flow hints such as URL or stdio command. */\n readonly sourcePresets?: readonly SourcePreset[];\n\n /** Build the plugin's extension API. The returned object becomes\n * `executor[plugin.id]` and is also the `self` passed to\n * `staticSources`. Field order matters: `extension` MUST appear\n * before `staticSources` so TS infers TExtension from this\n * factory's return BEFORE type-checking `self: NoInfer<TExtension>`. */\n readonly extension?: (ctx: PluginCtx<TStore>) => TExtension;\n\n /** Static sources contributed by this plugin with inline tool\n * handlers. Lives entirely in memory — no DB writes at startup.\n * Handlers close over `self` via the closure, so a control tool\n * that delegates to the plugin's real API is a one-liner:\n * `({ args }) => self.addSpec(args)`. */\n readonly staticSources?: (self: NoInfer<TExtension>) => readonly StaticSourceDecl<TStore>[];\n\n /** HttpApiGroup contributed by this plugin. Composed into the host's\n * `HttpApi` via the `addGroup` helper at runtime. The host mounts\n * the group at `/_executor/plugins/{id}/...` (or wherever the\n * plugin declares its base path) with the host's auth + scope\n * middleware applied. Endpoints automatically appear in the\n * executor OpenAPI doc and the typed reactive client.\n *\n * TGroup is inferred from the plugin's own group declaration so the\n * precise group identity flows through `composePluginApi(plugins)` —\n * the host's typed `HttpApi<\"executor\", CoreGroups | PluginGroups>`\n * is derived from the plugin tuple alone, with no per-plugin Group\n * imports at the host. Per-endpoint typing already lives inside the\n * plugin — its `handlers` Layer is built against its own bundled\n * `HttpApi.make(\"foo\").add(FooApi)` for full `.handle(\"name\", ...)`\n * inference, and its client imports the same group directly. */\n readonly routes?: () => TGroup;\n\n /** Handlers Layer for this plugin's group. Built by the plugin against\n * its own bundled API for full type safety on `.handle(\"name\", ...)`,\n * composes into the host's runtime `FullApi` because\n * `HttpApiBuilder.group` keys the layer by group identity, not by the\n * surrounding API.\n *\n * Late-binding: the layer leaves the plugin's extension as a Service\n * Tag requirement (see `extensionService` below). The host satisfies\n * it however its runtime wants:\n * - local: at boot via `Layer.succeed(extensionService)(executor[id])`\n * (see `composePluginHandlers`)\n * - cloud: per-request via `Effect.provideService(extensionService,\n * requestExecutor[id])` in the auth middleware\n *\n * The Layer's channels are typed `any` because `Layer<RIn, E, ROut>`'s\n * `ROut` is contravariant — the host accepts any layer here and merges\n * them; per-plugin requirements flow through the merge. */\n readonly handlers?: () => THandlersLayer;\n\n /** Service tag the plugin's `handlers` layer requires. Set by plugins\n * whose handlers consume their extension via a `Context.Service` tag\n * (the established pattern: `*Handlers` reads `*ExtensionService`).\n * The host binds the tag to the live extension — at boot for local,\n * per request for cloud. Pairs with `handlers`; either both fields\n * are set or neither.\n *\n * Inferred via the `TExtensionService` generic so the per-plugin\n * Service class identity propagates through `composePluginHandlers`,\n * `composePluginHandlerLayer`, and `providePluginExtensions` —\n * cloud's per-request middleware needs the precise tag for layer\n * satisfaction. */\n readonly extensionService?: TExtensionService;\n\n /** Invoke a dynamic tool. Called when the executor's static-handler\n * map doesn't have the toolId. The plugin reads its own enrichment\n * via `ctx.storage` and returns the result. Optional — plugins with\n * only static tools can omit it. */\n readonly invokeTool?: (input: InvokeToolInput<TStore>) => Effect.Effect<unknown, unknown>;\n\n /** Bulk resolve annotations (requiresApproval, approvalDescription,\n * mayElicit) for a set of tool rows under a single source. Called\n * by the executor:\n * - at invoke time with a single-element `toolRows` array, to\n * enforce approval on the about-to-run tool\n * - at list time with every dynamic tool row under each source,\n * grouped by source_id, to populate `Tool.annotations` for UI\n *\n * The expected implementation for most plugins is: read plugin\n * storage once for the given source/rows, derive annotations from\n * the same data that was used to build the tool (HTTP method +\n * path for openapi, introspection kind for graphql, etc.), return\n * a map keyed by tool id.\n *\n * Omit if the plugin has no annotations to contribute — executor\n * treats tools from that plugin as auto-approved with no\n * elicitation. */\n readonly resolveAnnotations?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly sourceId: string;\n readonly toolRows: readonly ToolRow[];\n }) => Effect.Effect<Record<string, ToolAnnotations>, unknown>;\n\n /** Find every place a secret id is referenced by this plugin's stored\n * rows. Implementations query their normalized columns (e.g.\n * `WHERE secret_id = $1`) and return one `Usage` per hit, with\n * `ownerKind` / `slot` tagging the location. The executor fans out\n * across all plugins and the result powers the Secrets-tab \"Used\n * by\" list and the deletion-blocking check in `secrets.remove`.\n *\n * Plugins that never store secret refs (secret-provider-only\n * plugins like keychain / file-secrets / 1password) omit this. */\n readonly usagesForSecret?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly args: UsagesForSecretInput;\n }) => Effect.Effect<readonly Usage[], unknown>;\n\n /** Same shape as `usagesForSecret`, but for connection refs. */\n readonly usagesForConnection?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly args: UsagesForConnectionInput;\n }) => Effect.Effect<readonly Usage[], unknown>;\n\n /** Called when `executor.sources.remove({ id, targetScope })` targets\n * a source owned by this plugin. Plugin-side cleanup only; the\n * executor deletes the core source/tool rows after this callback\n * returns, inside the same transaction. */\n readonly removeSource?: (input: SourceLifecycleInput<TStore>) => Effect.Effect<void, unknown>;\n\n readonly refreshSource?: (input: SourceLifecycleInput<TStore>) => Effect.Effect<void, unknown>;\n\n /** Core-dispatched source configuration. The executor resolves the\n * source row, finds the owning plugin, and calls this handler with\n * an explicit source scope plus explicit target scope for credential\n * values. Plugin-native `openapi.configure` style methods can call\n * the same implementation, but callers do not need to know about\n * low-level credential bindings. */\n readonly sourceConfigure?: SourceConfigureDecl<TStore>;\n\n /** URL autodetection hook. When the user pastes a URL in the\n * onboarding UI, `executor.sources.detect(url)` fans out to every\n * plugin's `detect`. Return a `SourceDetectionResult` if you\n * recognize the URL, `null` otherwise. Implementations should be\n * defensive — swallow fetch errors and return null rather than\n * throwing. First high-confidence match wins. */\n readonly detect?: (input: {\n readonly ctx: PluginCtx<TStore>;\n readonly url: string;\n }) => Effect.Effect<SourceDetectionResult | null, unknown>;\n\n /** Secret providers contributed by this plugin. Either a static\n * array, a function of ctx (for providers that need per-instance\n * state like the keychain's scope-derived service name), or a\n * function returning an Effect so plugins can probe for backend\n * availability at startup and register conditionally. Called once\n * at executor startup after `storage` and `extension` have been\n * built. */\n readonly secretProviders?:\n | readonly SecretProvider[]\n | ((ctx: PluginCtx<TStore>) => readonly SecretProvider[])\n | ((ctx: PluginCtx<TStore>) => Effect.Effect<readonly SecretProvider[]>);\n\n /** Connection providers contributed by this plugin. Same registration\n * shape as `secretProviders`. Each provider's `key` is what\n * `connection.provider` references in the core table; the `refresh`\n * handler is the SDK's single entry point for token lifecycle —\n * plugins don't run their own refresh loops anymore. */\n readonly connectionProviders?:\n | readonly ConnectionProvider[]\n | ((ctx: PluginCtx<TStore>) => readonly ConnectionProvider[])\n | ((ctx: PluginCtx<TStore>) => Effect.Effect<readonly ConnectionProvider[]>);\n\n readonly close?: () => Effect.Effect<void, unknown>;\n}\n\nexport interface Plugin<\n TId extends string = string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtension extends object = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TStore = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TSchema extends FumaTables | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = any,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n> extends PluginSpec<TId, TExtension, TStore, TSchema, TExtensionService, THandlersLayer, TGroup> {}\n\n// ---------------------------------------------------------------------------\n// definePlugin — factory-returning-spec. Options from the author factory\n// are merged with a storage override so consumers can swap the default\n// store implementation without touching plugin internals.\n// ---------------------------------------------------------------------------\n\nexport type ConfiguredPlugin<\n TId extends string,\n TExtension extends object,\n TStore,\n TOptions extends object,\n TSchema extends FumaTables | undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = Layer.Layer<unknown, never, never>,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n> = (\n options?: TOptions & {\n readonly storage?: (deps: StorageDeps<TSchema>) => TStore;\n },\n) => Plugin<TId, TExtension, TStore, TSchema, TExtensionService, THandlersLayer, TGroup>;\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function definePlugin<\n TId extends string,\n TExtension extends object,\n TStore,\n TSchema extends FumaTables | undefined = undefined,\n TOptions extends object = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TExtensionService extends Context.Service<any, any> | undefined = undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n THandlersLayer extends Layer.Layer<any, any, any> = Layer.Layer<unknown, never, never>,\n TGroup extends HttpApiGroup.Any = HttpApiGroup.Any,\n>(\n authorFactory: (\n options?: TOptions,\n ) => PluginSpec<TId, TExtension, TStore, TSchema, TExtensionService, THandlersLayer, TGroup>,\n): ConfiguredPlugin<\n TId,\n TExtension,\n TStore,\n TOptions,\n TSchema,\n TExtensionService,\n THandlersLayer,\n TGroup\n> {\n return (options) => {\n const {\n storage: storageOverride,\n ...rest\n }: {\n storage?: (deps: StorageDeps<TSchema>) => TStore;\n [key: string]: unknown;\n } = options ?? {};\n\n const hasAuthorOptions = Object.keys(rest).length > 0;\n const spec = authorFactory(hasAuthorOptions ? (rest as TOptions) : undefined);\n\n return {\n ...spec,\n storage: storageOverride ?? spec.storage,\n };\n };\n}\n\n// ---------------------------------------------------------------------------\n// AnyPlugin / PluginExtensions — type-level glue for the Executor surface.\n// ---------------------------------------------------------------------------\n\n// `Plugin<string>` (with all subsequent slots taking their wide defaults)\n// is structurally any concrete plugin — the `any` cascade stays inside\n// the spec's defaults instead of leaking into every consumer.\nexport type AnyPlugin = Plugin<string>;\n\nexport type PluginExtensions<TPlugins extends readonly AnyPlugin[]> = {\n readonly [P in TPlugins[number] as P[\"id\"]]: P extends Plugin<string, infer TExt> ? TExt : never;\n};\n\n/** Lightweight projection of a secret entry as returned by `ctx.secrets.list`. */\nexport interface SecretListEntry {\n readonly id: string;\n readonly name: string;\n readonly provider: string;\n}\n\n// Re-exported for consumers that check the elicitation handler type.\nexport type { ElicitationHandler };\n","// ---------------------------------------------------------------------------\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 { 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 type ToolResult<T> =\n | { readonly ok: true; readonly data: T }\n | { readonly ok: false; readonly error: ToolError };\n\nexport const ToolResult = {\n ok: <T>(data: T): ToolResult<T> => ({ ok: true, data }),\n fail: <T = never>(error: ToolError): ToolResult<T> => ({ ok: false, error }),\n} as const;\n\nconst ToolResultSchema = Schema.Union([\n Schema.Struct({ ok: Schema.Literal(true), data: Schema.Unknown }),\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// core-tools plugin\n//\n// Built-in plugin that contributes agent-facing static tools for configuring\n// executor-level primitives. The important boundary: sensitive values never\n// travel through tool arguments. Agents create secret placeholders and OAuth\n// sessions, then hand the returned browser URL to the user.\n// ---------------------------------------------------------------------------\n\nimport { Data, Effect, Schema } from \"effect\";\n\nimport { ConnectionRef } from \"./connections\";\nimport { CredentialBindingRef, CredentialBindingValue } from \"./credential-bindings\";\nimport { ConnectionId, ScopeId, SecretId } from \"./ids\";\nimport { OAuthStrategy as OAuthStrategySchema } from \"./oauth\";\nimport { definePlugin, tool, type StaticToolSchema } from \"./plugin\";\nimport { ToolPolicyActionSchema } from \"./policies\";\nimport { ToolResult } from \"./tool-result\";\nimport { SourceDetectionResult } from \"./types\";\nimport { Usage } from \"./usages\";\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 UnknownRecord = Schema.Record(Schema.String, Schema.Unknown);\n\nconst ScopeName = Schema.String;\n\nconst ScopesListOutput = Schema.Struct({\n scopes: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n name: Schema.String,\n }),\n ),\n});\n\nconst SecretRefOutput = Schema.Struct({\n id: Schema.String,\n scopeId: Schema.String,\n name: Schema.String,\n provider: Schema.String,\n});\n\nconst SecretsListOutput = Schema.Struct({\n secrets: Schema.Array(SecretRefOutput),\n});\n\nconst SecretsCreateInput = Schema.Struct({\n name: Schema.String,\n scope: Schema.optional(ScopeName),\n provider: Schema.optional(Schema.String),\n});\n\nconst SecretsCreateOutput = Schema.Struct({\n id: Schema.String,\n url: Schema.String,\n instructions: Schema.String,\n});\n\nconst SecretPointerInput = Schema.Struct({\n id: Schema.String,\n});\n\nconst SecretScopedPointerInput = Schema.Struct({\n id: Schema.String,\n targetScope: Schema.String,\n});\n\nconst SecretStatusOutput = Schema.Struct({\n id: Schema.String,\n status: Schema.Literals([\"resolved\", \"missing\"]),\n});\n\nconst SecretUsagesOutput = Schema.Struct({\n usages: Schema.Array(Usage),\n});\n\nconst ProvidersOutput = Schema.Struct({\n providers: Schema.Array(Schema.String),\n});\n\nconst RemovedOutput = Schema.Struct({\n removed: Schema.Boolean,\n});\n\nconst RefreshedOutput = Schema.Struct({\n refreshed: Schema.Boolean,\n});\n\nconst SourceOutput = Schema.Struct({\n id: Schema.String,\n scopeId: Schema.optional(Schema.String),\n kind: Schema.String,\n name: Schema.String,\n url: Schema.optional(Schema.String),\n pluginId: Schema.String,\n canRemove: Schema.Boolean,\n canRefresh: Schema.Boolean,\n canEdit: Schema.Boolean,\n runtime: Schema.Boolean,\n});\n\nconst SourcesListOutput = Schema.Struct({\n sources: Schema.Array(SourceOutput),\n});\n\nconst SourcesDetectInput = Schema.Struct({\n url: Schema.String,\n});\n\nconst SourcesDetectOutput = Schema.Struct({\n results: Schema.Array(SourceDetectionResult),\n});\n\nconst SourcePresetOutput = Schema.Struct({\n pluginId: Schema.String,\n id: Schema.String,\n name: Schema.String,\n summary: Schema.String,\n url: Schema.optional(Schema.String),\n endpoint: Schema.optional(Schema.String),\n icon: Schema.optional(Schema.String),\n featured: Schema.optional(Schema.Boolean),\n transport: Schema.optional(Schema.Literals([\"remote\", \"stdio\"])),\n command: Schema.optional(Schema.String),\n args: Schema.optional(Schema.Array(Schema.String)),\n env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n});\n\nconst SourcesPresetsInput = Schema.Struct({\n query: Schema.optional(Schema.String),\n pluginId: Schema.optional(Schema.String),\n featuredOnly: Schema.optional(Schema.Boolean),\n limit: Schema.optional(Schema.Number),\n});\n\nconst SourcesPresetsOutput = Schema.Struct({\n presets: Schema.Array(SourcePresetOutput),\n});\n\nconst SourcePointer = Schema.Struct({\n id: Schema.String,\n scope: Schema.String,\n});\n\nconst SourcesConfigureInput = Schema.Struct({\n source: SourcePointer,\n scope: Schema.String,\n type: Schema.optional(Schema.String),\n config: Schema.Unknown,\n});\n\nconst SourcesConfigureOutput = Schema.Struct({\n result: Schema.Unknown,\n});\n\nconst SourceLifecycleInput = Schema.Struct({\n id: Schema.String,\n targetScope: Schema.String,\n});\n\nconst SourceBindingsListInput = Schema.Struct({\n source: SourcePointer,\n});\n\nconst SourceBindingsResolveInput = Schema.Struct({\n source: SourcePointer,\n slotKey: Schema.String,\n});\n\nconst SourceBindingsSetInput = Schema.Struct({\n scope: Schema.String,\n source: SourcePointer,\n slotKey: Schema.String,\n value: CredentialBindingValue,\n});\n\nconst SourceBindingsRemoveInput = Schema.Struct({\n scope: Schema.String,\n source: SourcePointer,\n slotKey: Schema.String,\n});\n\nconst SourceBindingsListOutput = Schema.Struct({\n bindings: Schema.Array(CredentialBindingRef),\n});\n\nconst SourceBindingsResolveOutput = Schema.Struct({\n binding: Schema.NullOr(CredentialBindingRef),\n});\n\nconst SourceBindingsSetOutput = Schema.Struct({\n binding: CredentialBindingRef,\n});\n\nconst ConnectionsListOutput = Schema.Struct({\n connections: Schema.Array(ConnectionRef),\n});\n\nconst ConnectionPointerInput = Schema.Struct({\n id: Schema.String,\n});\n\nconst ConnectionScopedPointerInput = Schema.Struct({\n id: Schema.String,\n targetScope: Schema.String,\n});\n\nconst ConnectionUsagesOutput = Schema.Struct({\n usages: Schema.Array(Usage),\n});\n\nconst PolicyOutput = Schema.Struct({\n id: Schema.String,\n scopeId: Schema.String,\n pattern: Schema.String,\n action: ToolPolicyActionSchema,\n position: Schema.String,\n createdAt: Schema.Number,\n updatedAt: Schema.Number,\n});\n\nconst PoliciesListOutput = Schema.Struct({\n policies: Schema.Array(PolicyOutput),\n});\n\nconst PolicyCreateInput = Schema.Struct({\n targetScope: Schema.String,\n pattern: Schema.String,\n action: ToolPolicyActionSchema,\n position: Schema.optional(Schema.String),\n});\n\nconst PolicyUpdateInput = Schema.Struct({\n id: Schema.String,\n targetScope: Schema.String,\n pattern: Schema.optional(Schema.String),\n action: Schema.optional(ToolPolicyActionSchema),\n position: Schema.optional(Schema.String),\n});\n\nconst PolicyRemoveInput = Schema.Struct({\n id: Schema.String,\n targetScope: Schema.String,\n});\n\nconst PolicyMutationOutput = Schema.Struct({\n policy: PolicyOutput,\n});\n\nconst OAuthProbeInput = Schema.Struct({\n endpoint: Schema.String,\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n});\n\nconst OAuthProbeOutput = Schema.Struct({\n resourceMetadata: Schema.NullOr(UnknownRecord),\n resourceMetadataUrl: Schema.NullOr(Schema.String),\n authorizationServerMetadata: Schema.NullOr(UnknownRecord),\n authorizationServerMetadataUrl: Schema.NullOr(Schema.String),\n authorizationServerUrl: Schema.NullOr(Schema.String),\n supportsDynamicRegistration: Schema.Boolean,\n isBearerChallengeEndpoint: Schema.Boolean,\n});\n\nconst OAuthStartInput = Schema.Struct({\n credentialScope: Schema.optional(Schema.String),\n endpoint: Schema.String,\n connectionId: Schema.String,\n pluginId: Schema.String,\n identityLabel: Schema.optional(Schema.String),\n redirectUrl: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n strategy: OAuthStrategySchema,\n});\n\nconst OAuthStartOutput = Schema.Struct({\n sessionId: Schema.String,\n authorizationUrl: Schema.NullOr(Schema.String),\n completedConnection: Schema.NullOr(Schema.Struct({ connectionId: Schema.String })),\n instructions: Schema.String,\n});\n\nconst OAuthCancelInput = Schema.Struct({\n credentialScope: Schema.optional(Schema.String),\n sessionId: Schema.String,\n});\n\nconst OAuthCancelOutput = Schema.Struct({\n cancelled: Schema.Boolean,\n});\n\nconst ScopesListOutputStd = schemaToStandard(ScopesListOutput);\nconst SecretsListOutputStd = schemaToStandard(SecretsListOutput);\nconst SecretsCreateInputStd = schemaToStandard<\n typeof SecretsCreateInput.Type,\n typeof SecretsCreateInput.Encoded\n>(SecretsCreateInput);\nconst SecretsCreateOutputStd = schemaToStandard(SecretsCreateOutput);\nconst SecretPointerInputStd = schemaToStandard<\n typeof SecretPointerInput.Type,\n typeof SecretPointerInput.Encoded\n>(SecretPointerInput);\nconst SecretScopedPointerInputStd = schemaToStandard<\n typeof SecretScopedPointerInput.Type,\n typeof SecretScopedPointerInput.Encoded\n>(SecretScopedPointerInput);\nconst SecretStatusOutputStd = schemaToStandard(SecretStatusOutput);\nconst SecretUsagesOutputStd = schemaToStandard(SecretUsagesOutput);\nconst ProvidersOutputStd = schemaToStandard(ProvidersOutput);\nconst RemovedOutputStd = schemaToStandard(RemovedOutput);\nconst RefreshedOutputStd = schemaToStandard(RefreshedOutput);\nconst SourcesListOutputStd = schemaToStandard(SourcesListOutput);\nconst SourcesDetectInputStd = schemaToStandard<\n typeof SourcesDetectInput.Type,\n typeof SourcesDetectInput.Encoded\n>(SourcesDetectInput);\nconst SourcesDetectOutputStd = schemaToStandard(SourcesDetectOutput);\nconst SourcesPresetsInputStd = schemaToStandard<\n typeof SourcesPresetsInput.Type,\n typeof SourcesPresetsInput.Encoded\n>(SourcesPresetsInput);\nconst SourcesPresetsOutputStd = schemaToStandard(SourcesPresetsOutput);\nconst SourcesConfigureInputStd = schemaToStandard<\n typeof SourcesConfigureInput.Type,\n typeof SourcesConfigureInput.Encoded\n>(SourcesConfigureInput);\nconst SourcesConfigureOutputStd = schemaToStandard(SourcesConfigureOutput);\nconst SourceLifecycleInputStd = schemaToStandard<\n typeof SourceLifecycleInput.Type,\n typeof SourceLifecycleInput.Encoded\n>(SourceLifecycleInput);\nconst SourceBindingsListInputStd = schemaToStandard<\n typeof SourceBindingsListInput.Type,\n typeof SourceBindingsListInput.Encoded\n>(SourceBindingsListInput);\nconst SourceBindingsResolveInputStd = schemaToStandard<\n typeof SourceBindingsResolveInput.Type,\n typeof SourceBindingsResolveInput.Encoded\n>(SourceBindingsResolveInput);\nconst SourceBindingsSetInputStd = schemaToStandard<\n typeof SourceBindingsSetInput.Type,\n typeof SourceBindingsSetInput.Encoded\n>(SourceBindingsSetInput);\nconst SourceBindingsRemoveInputStd = schemaToStandard<\n typeof SourceBindingsRemoveInput.Type,\n typeof SourceBindingsRemoveInput.Encoded\n>(SourceBindingsRemoveInput);\nconst SourceBindingsListOutputStd = schemaToStandard(SourceBindingsListOutput);\nconst SourceBindingsResolveOutputStd = schemaToStandard(SourceBindingsResolveOutput);\nconst SourceBindingsSetOutputStd = schemaToStandard(SourceBindingsSetOutput);\nconst ConnectionsListOutputStd = schemaToStandard(ConnectionsListOutput);\nconst ConnectionPointerInputStd = schemaToStandard<\n typeof ConnectionPointerInput.Type,\n typeof ConnectionPointerInput.Encoded\n>(ConnectionPointerInput);\nconst ConnectionScopedPointerInputStd = schemaToStandard<\n typeof ConnectionScopedPointerInput.Type,\n typeof ConnectionScopedPointerInput.Encoded\n>(ConnectionScopedPointerInput);\nconst ConnectionUsagesOutputStd = schemaToStandard(ConnectionUsagesOutput);\nconst PoliciesListOutputStd = schemaToStandard(PoliciesListOutput);\nconst PolicyCreateInputStd = schemaToStandard<\n typeof PolicyCreateInput.Type,\n typeof PolicyCreateInput.Encoded\n>(PolicyCreateInput);\nconst PolicyUpdateInputStd = schemaToStandard<\n typeof PolicyUpdateInput.Type,\n typeof PolicyUpdateInput.Encoded\n>(PolicyUpdateInput);\nconst PolicyRemoveInputStd = schemaToStandard<\n typeof PolicyRemoveInput.Type,\n typeof PolicyRemoveInput.Encoded\n>(PolicyRemoveInput);\nconst PolicyMutationOutputStd = schemaToStandard(PolicyMutationOutput);\nconst OAuthProbeInputStd = schemaToStandard<\n typeof OAuthProbeInput.Type,\n typeof OAuthProbeInput.Encoded\n>(OAuthProbeInput);\nconst OAuthProbeOutputStd = schemaToStandard(OAuthProbeOutput);\nconst OAuthStartInputStd = schemaToStandard<\n typeof OAuthStartInput.Type,\n typeof OAuthStartInput.Encoded\n>(OAuthStartInput);\nconst OAuthStartOutputStd = schemaToStandard(OAuthStartOutput);\nconst OAuthCancelInputStd = schemaToStandard<\n typeof OAuthCancelInput.Type,\n typeof OAuthCancelInput.Encoded\n>(OAuthCancelInput);\nconst OAuthCancelOutputStd = schemaToStandard(OAuthCancelOutput);\n\nexport interface CoreToolsPluginOptions {\n readonly webBaseUrl?: string;\n}\n\nclass CoreToolsConfigurationError extends Data.TaggedError(\"CoreToolsConfigurationError\")<{\n readonly message: string;\n}> {}\n\nclass CoreToolsScopeNotFoundError extends Data.TaggedError(\"CoreToolsScopeNotFoundError\")<{\n readonly scope: string;\n readonly message: string;\n}> {}\n\nconst findScopeByNameOrId = (\n scopes: readonly { readonly id: ScopeId; readonly name: string }[],\n value: string,\n) => scopes.find((scope) => scope.name === value || String(scope.id) === value);\n\nconst resolveScopeInput = (\n scopes: readonly { readonly id: ScopeId; readonly name: string }[],\n value: string | undefined,\n) => {\n if (value === undefined) {\n const [onlyScope] = scopes;\n return onlyScope && scopes.length === 1\n ? Effect.succeed(String(onlyScope.id))\n : Effect.fail(\n new CoreToolsScopeNotFoundError({\n scope: \"\",\n message:\n scopes.length === 0\n ? \"No visible scopes are available.\"\n : \"Multiple scopes are visible. Call scopes.list and pass the target scope id or name.\",\n }),\n );\n }\n\n const scope = findScopeByNameOrId(scopes, value);\n return scope\n ? Effect.succeed(String(scope.id))\n : Effect.fail(\n new CoreToolsScopeNotFoundError({\n scope: value,\n message: `Unknown scope \"${value}\". Call scopes.list to see valid scope ids and names.`,\n }),\n );\n};\n\nconst normalizeCredentialBindingValue = (\n value: typeof CredentialBindingValue.Encoded,\n): CredentialBindingValue => {\n if (value.kind === \"text\") {\n return value;\n }\n if (value.kind === \"secret\") {\n return {\n kind: \"secret\",\n secretId: SecretId.make(value.secretId),\n ...(value.secretScopeId ? { secretScopeId: ScopeId.make(value.secretScopeId) } : {}),\n };\n }\n return {\n kind: \"connection\",\n connectionId: ConnectionId.make(value.connectionId),\n };\n};\n\nconst oauthToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\nconst requireWebBaseUrl = (value: string | undefined) =>\n value\n ? Effect.succeed(value.replace(/\\/$/, \"\"))\n : Effect.fail(\n new CoreToolsConfigurationError({\n message: \"This executor did not provide a webBaseUrl for browser handoff flows.\",\n }),\n );\n\nconst policyOutput = (policy: {\n readonly id: string;\n readonly scopeId: string;\n readonly pattern: string;\n readonly action: typeof ToolPolicyActionSchema.Type;\n readonly position: string;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}) => ({\n id: String(policy.id),\n scopeId: String(policy.scopeId),\n pattern: policy.pattern,\n action: policy.action,\n position: policy.position,\n createdAt: policy.createdAt.getTime(),\n updatedAt: policy.updatedAt.getTime(),\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: \"scopes.list\",\n description:\n \"List visible executor scopes. Call this before write tools when more than one scope is visible; single-scope local executors can usually omit scope inputs.\",\n outputSchema: ScopesListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.succeed({\n scopes: ctx.scopes.map((s) => ({ id: String(s.id), name: s.name })),\n }),\n }),\n tool({\n name: \"secrets.list\",\n description:\n \"List visible secrets by id, name, and provider. This never returns values. Use returned ids in source configuration or OAuth client credential strategies.\",\n outputSchema: SecretsListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.secrets.list(), (refs) => ({\n secrets: refs.map((r) => ({\n id: String(r.id),\n scopeId: String(r.scopeId),\n name: r.name,\n provider: r.provider,\n })),\n })),\n }),\n tool({\n name: \"secrets.create\",\n description:\n \"Create a secret placeholder and return a browser URL for the user to enter the sensitive value. Never ask the user to paste passwords, tokens, client secrets, or API keys into chat. In a single-scope local executor, omit `scope`; otherwise call `scopes.list` and pass the target credential scope id or name. The optional `provider` is the Executor secret storage backend, not the API vendor; omit it unless the user explicitly chose a value returned by `secrets.providers`.\",\n inputSchema: SecretsCreateInputStd,\n outputSchema: SecretsCreateOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const webBaseUrl = yield* requireWebBaseUrl(options.webBaseUrl);\n if (input.provider) {\n const providers = yield* ctx.secrets.providers();\n if (!providers.includes(input.provider)) {\n return oauthToolFailure(\n \"secret_provider_not_found\",\n `Unknown secret storage provider \"${input.provider}\". Omit provider unless the user chose one from secrets.providers.`,\n { providers },\n );\n }\n }\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.scope);\n\n const secretId = crypto.randomUUID();\n const url = new URL(`${webBaseUrl}/secrets`);\n url.searchParams.set(\"scope\", targetScope);\n url.searchParams.set(\"name\", input.name);\n url.searchParams.set(\"secretId\", secretId);\n if (input.provider) url.searchParams.set(\"provider\", input.provider);\n return {\n id: secretId,\n url: url.toString(),\n instructions:\n \"The user needs to open this URL and set the secret value in the browser. Until the user saves the value there, this secret is only a placeholder and will not be available for binding. After the user saves it, call secrets.status for this id before using it in source configuration.\",\n };\n }).pipe(\n Effect.catchTags({\n CoreToolsConfigurationError: ({ message }) =>\n Effect.succeed(oauthToolFailure(\"secret_handoff_not_configured\", message)),\n CoreToolsScopeNotFoundError: ({ message, scope }) =>\n Effect.succeed(oauthToolFailure(\"scope_not_found\", message, { scope })),\n }),\n ),\n }),\n tool({\n name: \"secrets.status\",\n description:\n \"Check whether a user-visible secret id has a backing value without revealing that value. Use this after a browser handoff from `secrets.create` before wiring the secret into a source.\",\n inputSchema: SecretPointerInputStd,\n outputSchema: SecretStatusOutputStd,\n execute: (input, { ctx }) =>\n Effect.map(ctx.secrets.status(input.id), (status) => ({ id: input.id, status })),\n }),\n tool({\n name: \"secrets.usages\",\n description:\n \"List sources and credential slots that reference a secret. Call this before removing a secret so the user can detach it first if needed.\",\n inputSchema: SecretPointerInputStd,\n outputSchema: SecretUsagesOutputStd,\n execute: (input, { ctx }) =>\n Effect.map(ctx.secrets.usages(input.id), (usages) => ({ usages })),\n }),\n tool({\n name: \"secrets.providers\",\n description:\n \"List registered secret storage providers. Only use these exact values for the optional `provider` field in `secrets.create`; do not use API vendor names such as Vercel, GitHub, Stripe, or Google. Sensitive values still must be entered through the returned browser URL.\",\n outputSchema: ProvidersOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.secrets.providers(), (providers) => ({ providers })),\n }),\n tool({\n name: \"secrets.remove\",\n description:\n \"Remove a user-visible secret from a target scope. Call `secrets.usages` first; removal is refused while sources still reference the secret. Connection-owned token secrets cannot be removed here; remove the connection instead.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Remove an Executor secret\",\n },\n inputSchema: SecretScopedPointerInputStd,\n outputSchema: RemovedOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);\n return yield* Effect.as(\n ctx.secrets.remove({\n id: SecretId.make(input.id),\n targetScope: ScopeId.make(targetScope),\n }),\n { removed: true },\n );\n }),\n }),\n tool({\n name: \"sources.list\",\n description:\n \"List configured and built-in sources. Use this to find source ids/scopes before calling plugin-specific configureSource tools, `sources.bindings.*`, refresh, remove, or tool discovery.\",\n outputSchema: SourcesListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.core.sources.list(), (sources) => ({ sources })),\n }),\n tool({\n name: \"sources.detect\",\n description:\n \"Detect which plugin can add or configure a URL. This is the same URL auto-detection used by the Executor web Connect dialog. Use this when the user gives a URL but not a source type; then call the matching plugin add tool such as `openapi.previewSpec` + `openapi.addSource`, `graphql.addSource`, or `mcp.addSource`.\",\n inputSchema: SourcesDetectInputStd,\n outputSchema: SourcesDetectOutputStd,\n execute: (input, { ctx }) =>\n Effect.map(ctx.core.sources.detect(input.url), (results) => ({ results })),\n }),\n tool({\n name: \"sources.presets\",\n description:\n \"List the same popular source presets shown in Executor web's Connect dialog. Use this before asking the user what to connect; filter with `query` for names like GitHub, Stripe, Axiom, Google Calendar, Linear, or OpenAI. For MCP and GraphQL presets, pass `endpoint` to the probe/add tools. For OpenAPI and Google Discovery presets, pass `url` to the preview/probe and add tools. For stdio MCP presets, use the returned command/args/env.\",\n inputSchema: SourcesPresetsInputStd,\n outputSchema: SourcesPresetsOutputStd,\n execute: (input, { ctx }) =>\n Effect.sync(() => {\n const query = input.query?.trim().toLowerCase() ?? \"\";\n const pluginId = input.pluginId?.trim();\n const featuredOnly = input.featuredOnly ?? false;\n const limit = Math.max(0, Math.trunc(input.limit ?? 50));\n const presets = ctx.core.sources\n .presets()\n .filter((preset) => (pluginId ? preset.pluginId === pluginId : true))\n .filter((preset) => (featuredOnly ? preset.featured === true : true))\n .filter((preset) => {\n if (query.length === 0) return true;\n const corpus =\n `${preset.name} ${preset.summary} ${preset.pluginId} ${preset.id}`.toLowerCase();\n return corpus.includes(query);\n })\n .slice(0, limit);\n return { presets };\n }),\n }),\n tool({\n name: \"sources.configure\",\n description:\n 'Low-level escape hatch for configuring an existing source through its owning plugin. Prefer plugin-specific tools such as `openapi.configureSource`, `graphql.configureSource`, `mcp.configureSource`, or `googleDiscovery.configureSource`; this accepts plugin config as `unknown` for repair and compatibility cases. Use `secrets.create`/`oauth.start` first for sensitive inputs. Pass secret refs as `{kind:\"secret\", secretId}` and OAuth connections as `{kind:\"connection\", connectionId}` when the plugin schema supports them.',\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Configure an Executor source\",\n },\n inputSchema: SourcesConfigureInputStd,\n outputSchema: SourcesConfigureOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.scope);\n const result = yield* ctx.core.sources.configure({\n ...input,\n source: { ...input.source, scope: sourceScope },\n scope: targetScope,\n });\n return { result };\n }),\n }),\n tool({\n name: \"sources.refresh\",\n description:\n \"Refresh a configurable source's registered tools from its backing spec/server. Use `sources.list` first to get the source id and owning scope, then refresh the owning scope.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Refresh an Executor source\",\n },\n inputSchema: SourceLifecycleInputStd,\n outputSchema: RefreshedOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);\n return yield* Effect.as(ctx.core.sources.refresh({ ...input, targetScope }), {\n refreshed: true,\n });\n }),\n }),\n tool({\n name: \"sources.remove\",\n description:\n \"Remove a configurable source and its registered tools from a target scope. Use `sources.list` and, when credentials are involved, `sources.bindings.list` first so the user can confirm exactly what will be removed.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Remove an Executor source\",\n },\n inputSchema: SourceLifecycleInputStd,\n outputSchema: RemovedOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);\n return yield* Effect.as(ctx.core.sources.remove({ ...input, targetScope }), {\n removed: true,\n });\n }),\n }),\n tool({\n name: \"sources.bindings.list\",\n description:\n \"List credential bindings for a source. Use this to verify that secrets or OAuth connections were bound after a plugin-specific configureSource tool.\",\n inputSchema: SourceBindingsListInputStd,\n outputSchema: SourceBindingsListOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);\n const bindings = yield* ctx.core.sources.listBindings({\n source: { id: input.source.id, scope: ScopeId.make(sourceScope) },\n });\n return { bindings };\n }),\n }),\n tool({\n name: \"sources.bindings.resolve\",\n description:\n \"Resolve the effective credential binding for one source slot, accounting for scope shadowing. Values are references only; plaintext is never returned.\",\n inputSchema: SourceBindingsResolveInputStd,\n outputSchema: SourceBindingsResolveOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);\n const binding = yield* ctx.core.sources.resolveBinding({\n source: { id: input.source.id, scope: ScopeId.make(sourceScope) },\n slotKey: input.slotKey,\n });\n return { binding };\n }),\n }),\n tool({\n name: \"sources.bindings.set\",\n description:\n \"Set one credential binding for a source slot. Prefer plugin-specific configureSource tools for normal flows because they name the right credential fields. Use this low-level tool only when a plugin or status output has given an exact slot key.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Set a source credential binding\",\n },\n inputSchema: SourceBindingsSetInputStd,\n outputSchema: SourceBindingsSetOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const scope = yield* resolveScopeInput(ctx.scopes, input.scope);\n const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);\n const binding = yield* ctx.core.sources.setBinding({\n scope: ScopeId.make(scope),\n source: { id: input.source.id, scope: ScopeId.make(sourceScope) },\n slotKey: input.slotKey,\n value: normalizeCredentialBindingValue(input.value),\n });\n return { binding };\n }),\n }),\n tool({\n name: \"sources.bindings.remove\",\n description:\n \"Remove one credential binding from a source slot at a target scope. Use `sources.bindings.list` first so the user can confirm the exact binding being removed.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Remove a source credential binding\",\n },\n inputSchema: SourceBindingsRemoveInputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const scope = yield* resolveScopeInput(ctx.scopes, input.scope);\n const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);\n return yield* Effect.asVoid(\n ctx.core.sources.removeBinding({\n scope: ScopeId.make(scope),\n source: { id: input.source.id, scope: ScopeId.make(sourceScope) },\n slotKey: input.slotKey,\n }),\n );\n }),\n }),\n tool({\n name: \"connections.list\",\n description:\n \"List OAuth/sign-in connections. This returns metadata and token secret ids, never token values. Use it to verify that `oauth.start` completed, then bind the connection id with the relevant plugin-specific configureSource tool.\",\n outputSchema: ConnectionsListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.connections.list(), (connections) => ({ connections })),\n }),\n tool({\n name: \"connections.usages\",\n description:\n \"List sources and credential slots that reference an OAuth/sign-in connection. Call this before removing a connection so the user can detach it first if needed.\",\n inputSchema: ConnectionPointerInputStd,\n outputSchema: ConnectionUsagesOutputStd,\n execute: (input, { ctx }) =>\n Effect.map(ctx.connections.usages(input.id), (usages) => ({ usages })),\n }),\n tool({\n name: \"connections.providers\",\n description:\n \"List registered connection providers. Use this to understand which OAuth/sign-in connection kinds this executor can mint and refresh.\",\n outputSchema: ProvidersOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.connections.providers(), (providers) => ({ providers })),\n }),\n tool({\n name: \"connections.remove\",\n description:\n \"Remove an OAuth/sign-in connection and its owned token secrets from a target scope. Call `connections.usages` first; removal is refused while sources still reference the connection.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Remove an Executor connection\",\n },\n inputSchema: ConnectionScopedPointerInputStd,\n outputSchema: RemovedOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);\n return yield* Effect.as(\n ctx.connections.remove({\n id: ConnectionId.make(input.id),\n targetScope: ScopeId.make(targetScope),\n }),\n { removed: true },\n );\n }),\n }),\n tool({\n name: \"policies.list\",\n description:\n \"List tool approval policies visible to this executor, sorted in evaluation order. Use this before creating, updating, reordering, or removing policies.\",\n outputSchema: PoliciesListOutputStd,\n execute: (_args, { ctx }) =>\n Effect.map(ctx.core.policies.list(), (policies) => ({\n policies: policies.map(policyOutput),\n })),\n }),\n tool({\n name: \"policies.create\",\n description:\n 'Create a tool approval policy. Patterns are exact tool ids, a trailing wildcard such as `executor.openapi.*`, or `*`. Actions are `\"approve\"`, `\"require_approval\"`, or `\"block\"`. Omit `position` to place the policy at the top of the target scope.',\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Create an Executor tool policy\",\n },\n inputSchema: PolicyCreateInputStd,\n outputSchema: PolicyMutationOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);\n const policy = yield* ctx.core.policies.create({ ...input, targetScope });\n return { policy: policyOutput(policy) };\n }),\n }),\n tool({\n name: \"policies.update\",\n description:\n \"Update or reorder an approval policy. Use `policies.list` first; preserve fields you are not changing, and use the listed `position` values when computing a new order.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Update an Executor tool policy\",\n },\n inputSchema: PolicyUpdateInputStd,\n outputSchema: PolicyMutationOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);\n const policy = yield* ctx.core.policies.update({ ...input, targetScope });\n return { policy: policyOutput(policy) };\n }),\n }),\n tool({\n name: \"policies.remove\",\n description:\n \"Remove an approval policy from a target scope. Use `policies.list` first so the user can confirm the exact rule id and pattern.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Remove an Executor tool policy\",\n },\n inputSchema: PolicyRemoveInputStd,\n outputSchema: RemovedOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);\n return yield* Effect.as(ctx.core.policies.remove({ ...input, targetScope }), {\n removed: true,\n });\n }),\n }),\n tool({\n name: \"oauth.probe\",\n description:\n 'Probe an OAuth-protected endpoint before starting OAuth. For dynamic MCP-style OAuth, call this first; if `supportsDynamicRegistration` is true, call `oauth.start` with strategy `{kind:\"dynamic-dcr\"}`. If false, create client id/secret secrets in the browser and use an `authorization-code` strategy.',\n inputSchema: OAuthProbeInputStd,\n outputSchema: OAuthProbeOutputStd,\n execute: (input, { ctx }) =>\n ctx.oauth\n .probe(input)\n .pipe(\n Effect.catchTag(\"OAuthProbeError\", ({ message }) =>\n Effect.succeed(oauthToolFailure(\"oauth_probe_failed\", message)),\n ),\n ),\n }),\n tool({\n name: \"oauth.start\",\n description:\n \"Start an OAuth flow and return the authorization URL the user must open in a browser. `credentialScope` chooses where Executor stores the OAuth connection/token secrets; omit it only in a single-scope local executor, otherwise call `scopes.list` and ask whether the connection should be personal/user-scoped or organization-scoped. OAuth permission scopes belong in `strategy.scopes`. Never put OAuth passwords, authorization codes, or client secrets in chat. For confidential clients, first call `secrets.create` for client id/secret and pass those secret ids in the strategy. After the browser callback completes, call `connections.list`, then configure the source with the returned connection id.\",\n inputSchema: OAuthStartInputStd,\n outputSchema: OAuthStartOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const webBaseUrl = yield* requireWebBaseUrl(options.webBaseUrl);\n const tokenScope = yield* resolveScopeInput(ctx.scopes, input.credentialScope);\n const result = yield* ctx.oauth.start({\n endpoint: input.endpoint,\n headers: input.headers,\n queryParams: input.queryParams,\n redirectUrl: input.redirectUrl ?? `${webBaseUrl}/api/oauth/callback`,\n connectionId: input.connectionId,\n tokenScope,\n strategy: input.strategy,\n pluginId: input.pluginId,\n identityLabel: input.identityLabel,\n });\n return {\n ...result,\n instructions:\n result.authorizationUrl === null\n ? \"This OAuth flow completed without a browser handoff. The OAuth connection/token secrets were saved to the selected credential scope. Call connections.list to verify the connection id, then pass that connection id to the relevant source configuration tool.\"\n : \"The user needs to open this authorization URL in a browser and complete the OAuth/sign-in flow. Until the browser callback completes, no connection is available for binding. After the user finishes sign-in, call connections.list to find the connection id, then pass that connection id to the relevant source configuration tool. The OAuth connection/token secrets are saved to the selected credential scope.\",\n };\n }).pipe(\n Effect.catchTags({\n CoreToolsConfigurationError: ({ message }) =>\n Effect.succeed(oauthToolFailure(\"oauth_start_not_configured\", message)),\n CoreToolsScopeNotFoundError: ({ message, scope }) =>\n Effect.succeed(oauthToolFailure(\"scope_not_found\", message, { scope })),\n OAuthStartError: ({ message, error, errorDescription }) =>\n Effect.succeed(\n oauthToolFailure(\"oauth_start_failed\", message, {\n ...(error ? { error } : {}),\n ...(errorDescription ? { errorDescription } : {}),\n }),\n ),\n }),\n ),\n }),\n tool({\n name: \"oauth.cancel\",\n description:\n \"`credentialScope` must match where `oauth.start` saved the pending browser handoff. Cancel it if the user declines or the wrong flow was started.\",\n inputSchema: OAuthCancelInputStd,\n outputSchema: OAuthCancelOutputStd,\n execute: (input, { ctx }) =>\n Effect.gen(function* () {\n const scope = yield* resolveScopeInput(ctx.scopes, input.credentialScope);\n return yield* Effect.as(ctx.oauth.cancel(input.sessionId, scope), {\n cancelled: true,\n });\n }).pipe(\n Effect.catchTag(\"CoreToolsScopeNotFoundError\", ({ message, scope }) =>\n Effect.succeed(oauthToolFailure(\"scope_not_found\", message, { scope })),\n ),\n ),\n }),\n ],\n },\n ],\n}));\n\nexport default coreToolsPlugin;\n","import { Effect, Schema } from \"effect\";\n\nimport { ToolId } from \"./ids\";\n\n// ---------------------------------------------------------------------------\n// Elicitation request — what a tool sends when it needs user input\n// ---------------------------------------------------------------------------\n\n/** Tool needs structured input from the user (render a form) */\nexport const FormElicitation = Schema.TaggedStruct(\"FormElicitation\", {\n message: Schema.String,\n /** JSON Schema describing the fields to collect */\n requestedSchema: Schema.Record(Schema.String, Schema.Unknown),\n});\nexport type FormElicitation = typeof FormElicitation.Type;\n\n/** Tool needs the user to visit a URL (OAuth, approval page, etc.) */\nexport const UrlElicitation = Schema.TaggedStruct(\"UrlElicitation\", {\n message: Schema.String,\n url: Schema.String,\n /** Unique ID so the host can correlate the callback */\n elicitationId: Schema.String,\n});\nexport type UrlElicitation = typeof UrlElicitation.Type;\n\nexport type ElicitationRequest = FormElicitation | UrlElicitation;\n\n// ---------------------------------------------------------------------------\n// Elicitation response — what the host sends back\n// ---------------------------------------------------------------------------\n\nexport const ElicitationAction = Schema.Literals([\"accept\", \"decline\", \"cancel\"]);\nexport type ElicitationAction = typeof ElicitationAction.Type;\n\nexport const ElicitationResponse = Schema.Struct({\n action: ElicitationAction,\n /** Present when action is \"accept\" — the data the user provided */\n content: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n});\nexport type ElicitationResponse = typeof ElicitationResponse.Type;\n\n// ---------------------------------------------------------------------------\n// Elicitation handler — the host provides this to handle requests\n// ---------------------------------------------------------------------------\n\nexport interface ElicitationContext {\n readonly toolId: ToolId;\n readonly args: unknown;\n readonly request: ElicitationRequest;\n}\n\n/**\n * A function the host provides to handle elicitation.\n * The SDK calls this when a tool suspends to ask for user input.\n * The host renders UI / prompts the user / does OAuth / etc.\n */\nexport type ElicitationHandler = (ctx: ElicitationContext) => Effect.Effect<ElicitationResponse>;\n\n// ---------------------------------------------------------------------------\n// Elicitation error — tool was declined or cancelled\n// ---------------------------------------------------------------------------\n\nexport class ElicitationDeclinedError extends Schema.TaggedErrorClass<ElicitationDeclinedError>()(\n \"ElicitationDeclinedError\",\n {\n toolId: ToolId,\n action: Schema.Literals([\"decline\", \"cancel\"]),\n },\n) {}\n","import { Effect, Schema } from \"effect\";\n\nimport type { StorageFailure } from \"./fuma-runtime\";\n\nimport { SecretId, ScopeId } from \"./ids\";\n\n// ---------------------------------------------------------------------------\n// SecretProvider — what a concrete backend (keychain, 1password, file,\n// memory, workos-vault, …) implements. Providers are contributed by\n// plugins via `plugin.secretProviders` and registered in the executor\n// at startup; there's no runtime registration.\n//\n// The `key` field is the provider's identifier in the secret table's\n// `provider` column and in `executor.secrets.set({ provider, ... })`.\n// Unique per executor.\n// ---------------------------------------------------------------------------\n\nexport interface SecretProvider {\n /** Unique key (e.g. \"keychain\", \"env\", \"1password\", \"memory\"). */\n readonly key: string;\n /** If false, `set` and `delete` are never called. The executor\n * honours this before routing writes — trying to write to a\n * read-only provider is an error, not a silent drop. */\n readonly writable: boolean;\n /** Get a secret value. `scope` is the executor scope the lookup is\n * being made on behalf of — providers that partition their storage\n * by scope (memory, keychain via service name, per-vault in\n * 1password) use it; providers without tenancy ignore it and fall\n * back to a flat lookup. Failures (provider unreachable, decryption\n * failed, etc.) surface as `StorageFailure` — the executor treats\n * a provider call the same as a DB call; `StorageError` is captured\n * at the HTTP edge to `InternalError`, `UniqueViolationError` dies. */\n readonly get: (id: string, scope: string) => Effect.Effect<string | null, StorageFailure>;\n /** Check whether a provider has a backing value without returning it.\n * Providers that can answer this cheaply should implement it so\n * stale core routing rows don't appear as selectable secrets. */\n readonly has?: (id: string, scope: string) => Effect.Effect<boolean, StorageFailure>;\n /** Set a secret value at a named scope. Only called on writable\n * providers. Providers that partition by scope use this arg to\n * decide where to write; flat providers ignore it. */\n readonly set?: (id: string, value: string, scope: string) => Effect.Effect<void, StorageFailure>;\n /** Delete a secret at a named scope. Only called on writable providers.\n * Returns true if something was deleted. */\n readonly delete?: (id: string, scope: string) => Effect.Effect<boolean, StorageFailure>;\n /** Enumerate known secret entries. Optional — not all backends can\n * enumerate (env-backed providers, for example). */\n readonly list?: () => Effect.Effect<\n readonly { readonly id: string; readonly name: string }[],\n StorageFailure\n >;\n /** Whether the provider may be asked during id-only fallback resolution.\n * Providers whose own auth depends on `ctx.secrets.get` should opt out to\n * avoid recursive fallback through themselves. */\n readonly allowFallback?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// SecretRef — metadata about a stored secret. Returned from\n// `executor.secrets.list()`. The actual value lives in the provider\n// and is only reachable via `executor.secrets.get(id)`.\n// ---------------------------------------------------------------------------\n\nexport const SecretRef = Schema.Struct({\n id: SecretId,\n scopeId: ScopeId,\n /** Human-readable label (e.g. \"Cloudflare API Token\") */\n name: Schema.String,\n /** Which provider holds the value */\n provider: Schema.String,\n createdAt: Schema.Date,\n});\nexport type SecretRef = typeof SecretRef.Type;\n\n// ---------------------------------------------------------------------------\n// SetSecretInput — all the metadata to write a secret in one call.\n// `executor.secrets.set(input)` takes this and writes both the\n// value (to the provider) and the ref (to the `secret` table).\n//\n// `scope` is required — there's no default write target. Callers name\n// which scope in the executor's stack should own the secret. Typical\n// pattern: UI wiring up org-level API keys writes to the org scope;\n// OAuth token exchange writes to the innermost per-user scope.\n// ---------------------------------------------------------------------------\n\nexport const SetSecretInput = Schema.Struct({\n id: SecretId,\n /** Scope id to own this secret. Must be one of the executor's\n * configured scopes. */\n scope: ScopeId,\n /** Display name shown in secret-list UI. */\n name: Schema.String,\n /** The secret value itself — never persisted outside the provider. */\n value: Schema.String,\n /** Optional provider routing. If unset the executor picks the first\n * writable provider in registration order. */\n provider: Schema.optional(Schema.String),\n});\nexport type SetSecretInput = typeof SetSecretInput.Type;\n\nexport const RemoveSecretInput = Schema.Struct({\n id: SecretId,\n /** Scope id whose secret row/value should be removed. Must be one of\n * the executor's configured scopes. */\n targetScope: ScopeId,\n});\nexport type RemoveSecretInput = typeof RemoveSecretInput.Type;\n","// ---------------------------------------------------------------------------\n// OAuth 2.0 helpers — generic, isomorphic building blocks.\n//\n// Thin wrappers around `oauth4webapi` (stateless; pure Web Crypto +\n// `fetch`, no deps; runs unchanged in Node, CF Workers, and browsers).\n// Each public helper is a single `Effect.tryPromise` call that delegates\n// the RFC work to the library and normalises the failure surface into\n// `OAuth2Error`.\n//\n// What stays hand-rolled:\n// - `OAuth2Error` — our tagged error; we want a stable shape across\n// every token-endpoint call\n// - `shouldRefreshToken` — skew check, trivial\n// - `buildAuthorizationUrl` — the library doesn't expose a raw\n// authorization-URL builder (it prefers PAR); a 30-line manual\n// construction keeps the call sync and lets callers opt out of PAR\n// ---------------------------------------------------------------------------\n\nimport { Data, Effect, Predicate } from \"effect\";\nimport * as oauth from \"oauth4webapi\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class OAuth2Error extends Data.TaggedError(\"OAuth2Error\")<{\n readonly message: string;\n /**\n * RFC 6749 §5.2 error code, when the token endpoint returned one\n * (`invalid_grant`, `invalid_client`, `unauthorized_client`, ...).\n * Callers use this to distinguish terminal failures (a refresh token\n * the AS no longer honours → re-auth required) from transient ones.\n */\n readonly error?: string;\n readonly cause?: unknown;\n}> {}\n\n// ---------------------------------------------------------------------------\n// Token response shape (RFC 6749 §5.1)\n// ---------------------------------------------------------------------------\n\nexport type OAuth2TokenResponse = {\n readonly access_token: string;\n readonly token_type?: string;\n readonly refresh_token?: string;\n readonly expires_in?: number;\n readonly scope?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Refresh tokens this many ms before expiry to avoid mid-request expiration. */\nexport const OAUTH2_REFRESH_SKEW_MS = 60_000;\n\n/** Default token-endpoint timeout. */\nexport const OAUTH2_DEFAULT_TIMEOUT_MS = 20_000;\n\nexport interface OAuthEndpointUrlPolicy {\n readonly allowHttp?: boolean;\n}\n\nconst isLoopbackHttpUrl = (value: string): boolean => {\n if (!URL.canParse(value)) return false;\n const url = new URL(value);\n if (url.protocol !== \"http:\") return false;\n const hostname = url.hostname.toLowerCase();\n return (\n hostname === \"localhost\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n};\n\nexport const isSupportedOAuthEndpointUrl = (\n value: string,\n policy: OAuthEndpointUrlPolicy = {},\n): boolean => {\n if (!URL.canParse(value)) return false;\n const url = new URL(value);\n return (\n url.protocol === \"https:\" ||\n isLoopbackHttpUrl(value) ||\n (url.protocol === \"http:\" && policy.allowHttp === true)\n );\n};\n\nexport const assertSupportedOAuthEndpointUrl = (\n value: string,\n label = \"OAuth endpoint URL\",\n policy: OAuthEndpointUrlPolicy = {},\n): string => {\n if (isSupportedOAuthEndpointUrl(value, policy)) return value;\n // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: synchronous assertion helper used by URL constructors and Effect.try wrappers\n throw new TypeError(`${label} must use https: or loopback http:`);\n};\n\n// ---------------------------------------------------------------------------\n// PKCE (RFC 7636) — straight delegation to `oauth4webapi`\n// ---------------------------------------------------------------------------\n\nexport const createPkceCodeVerifier = (): string => oauth.generateRandomCodeVerifier();\n\nexport const createPkceCodeChallenge = (verifier: string): Promise<string> =>\n oauth.calculatePKCECodeChallenge(verifier);\n\n// ---------------------------------------------------------------------------\n// Authorization URL builder\n// ---------------------------------------------------------------------------\n\nexport type BuildAuthorizationUrlInput = {\n readonly authorizationUrl: string;\n readonly clientId: string;\n readonly redirectUrl: string;\n readonly scopes: readonly string[];\n readonly state: string;\n /** Pre-computed base64url S256 challenge (from `createPkceCodeChallenge`). */\n readonly codeChallenge: string;\n /** Separator between scopes. RFC 6749 says space; some providers use comma. */\n readonly scopeSeparator?: string;\n /** RFC 8707 Resource Indicator. MCP Authorization 2025-06-18 §\"Resource\n * Parameter Implementation\" requires clients to send this on every\n * authorization request, regardless of AS support. */\n readonly resource?: string;\n /** Provider-specific extras (e.g. Google's `access_type=offline`). */\n readonly extraParams?: Readonly<Record<string, string>>;\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n};\n\n/** Build an RFC 6749 §4.1.1 authorization URL. Sync; pre-computed\n * challenge lets this stay out of the Promise world. */\nexport const buildAuthorizationUrl = (input: BuildAuthorizationUrlInput): string => {\n const url = new URL(\n assertSupportedOAuthEndpointUrl(\n input.authorizationUrl,\n \"Authorization URL\",\n input.endpointUrlPolicy,\n ),\n );\n const separator = input.scopeSeparator ?? \" \";\n url.searchParams.set(\"client_id\", input.clientId);\n url.searchParams.set(\"redirect_uri\", input.redirectUrl);\n url.searchParams.set(\"response_type\", \"code\");\n if (input.scopes.length > 0) {\n url.searchParams.set(\"scope\", input.scopes.join(separator));\n }\n url.searchParams.set(\"state\", input.state);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"code_challenge\", input.codeChallenge);\n if (input.resource) {\n url.searchParams.set(\"resource\", input.resource);\n }\n if (input.extraParams) {\n for (const [k, v] of Object.entries(input.extraParams)) {\n url.searchParams.set(k, v);\n }\n }\n return url.toString();\n};\n\n// ---------------------------------------------------------------------------\n// Error mapping — `oauth4webapi`'s `process*Response` failure shapes are\n// either a WWW-Authenticate challenge or an RFC 6749 §5.2 error body,\n// both exposed via `.error` / `.error_description`. Probing the envelope\n// preserves RFC 6749 error-code semantics (e.g., mapping `invalid_grant`\n// to reauth-required) across wrappers.\n// ---------------------------------------------------------------------------\n\nconst isOAuth2Error = Predicate.isTagged(\"OAuth2Error\") as (cause: unknown) => cause is OAuth2Error;\n\nconst responseFromOAuthErrorCause = (cause: unknown): Response | undefined => {\n if (cause instanceof Response) return cause;\n if (typeof cause !== \"object\" || cause === null) return undefined;\n const envelope = cause as {\n readonly cause?: unknown;\n readonly response?: unknown;\n };\n if (envelope.response instanceof Response) return envelope.response;\n if (envelope.cause instanceof Response) return envelope.cause;\n return undefined;\n};\n\nconst redactTokenEndpointBody = (body: string): string =>\n body\n .replaceAll(\n /(\"(?:access_token|refresh_token|id_token|client_secret)\"\\s*:\\s*\")[^\"]*(\")/gi,\n \"$1[redacted]$2\",\n )\n .replaceAll(\n /((?:access_token|refresh_token|id_token|client_secret|code)=)[^&\\s]*/gi,\n \"$1[redacted]\",\n );\n\nconst tokenEndpointHttpSummary = async (response: Response): Promise<string> => {\n const status = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}`;\n const contentType = response.headers.get(\"content-type\");\n const url = response.url ? ` from ${response.url}` : \"\";\n const parts = [`${status}${url}`];\n if (contentType) parts.push(`content-type ${contentType}`);\n const preview = await bodyPreviewFromResponse(response);\n if (preview) parts.push(`body: ${preview}`);\n return parts.join(\"; \");\n};\n\nconst bodyPreviewFromResponse = async (response: Response): Promise<string | undefined> => {\n const text = await Promise.resolve()\n .then(() => response.clone().text())\n .then(\n (value) => value.trim(),\n () => \"\",\n );\n if (!text) return undefined;\n const redacted = redactTokenEndpointBody(text.replaceAll(/\\s+/g, \" \"));\n return redacted.length > 500 ? `${redacted.slice(0, 500)}...` : redacted;\n};\n\nconst toOAuth2Error = (cause: unknown): OAuth2Error => {\n if (isOAuth2Error(cause)) return cause;\n if (typeof cause === \"object\" && cause !== null) {\n const c = cause as {\n error?: unknown;\n error_description?: unknown;\n message?: unknown;\n };\n const code = typeof c.error === \"string\" ? c.error : undefined;\n const description =\n typeof c.error_description === \"string\"\n ? c.error_description\n : typeof c.message === \"string\"\n ? c.message\n : undefined;\n return new OAuth2Error({\n message: `OAuth token exchange failed: ${description ?? code ?? \"unknown error\"}`,\n error: code,\n cause,\n });\n }\n return new OAuth2Error({\n message: \"OAuth token exchange failed\",\n cause,\n });\n};\n\nconst toOAuth2ErrorWithHttpSummary = (cause: unknown): Effect.Effect<OAuth2Error> => {\n if (isOAuth2Error(cause)) return Effect.succeed(cause);\n const base = toOAuth2Error(cause);\n const response = responseFromOAuthErrorCause(cause);\n if (!response) return Effect.succeed(base);\n return Effect.promise(() => tokenEndpointHttpSummary(response)).pipe(\n Effect.map(\n (summary) =>\n new OAuth2Error({\n message: `${base.message} (${summary})`,\n error: base.error,\n cause,\n }),\n ),\n );\n};\n\nconst failOAuth2WithHttpSummary = (cause: unknown): Effect.Effect<never, OAuth2Error> =>\n toOAuth2ErrorWithHttpSummary(cause).pipe(Effect.flatMap((error) => Effect.fail(error)));\n\n// ---------------------------------------------------------------------------\n// oauth4webapi adapter helpers\n// ---------------------------------------------------------------------------\n\nexport type ClientAuthMethod = \"body\" | \"basic\";\n\nconst asFromTokenUrl = (\n tokenUrl: string,\n endpointUrlPolicy: OAuthEndpointUrlPolicy = {},\n): oauth.AuthorizationServer => {\n assertSupportedOAuthEndpointUrl(tokenUrl, \"Token URL\", endpointUrlPolicy);\n const url = new URL(tokenUrl);\n return {\n issuer: `${url.protocol}//${url.host}`,\n token_endpoint: tokenUrl,\n };\n};\n\nconst asFromTokenUrlAndIssuer = (\n tokenUrl: string,\n issuerUrl: string | null | undefined,\n options: {\n readonly idTokenSigningAlgValuesSupported?: readonly string[];\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n } = {},\n): oauth.AuthorizationServer => {\n const as = asFromTokenUrl(tokenUrl, options.endpointUrlPolicy);\n const withIssuer = issuerUrl ? { ...as, issuer: issuerUrl } : as;\n return options.idTokenSigningAlgValuesSupported\n ? {\n ...withIssuer,\n id_token_signing_alg_values_supported: [...options.idTokenSigningAlgValuesSupported],\n }\n : withIssuer;\n};\n\nconst oauth4webapiRequestOptions = (\n targetUrl: string,\n timeoutMs: number | undefined,\n endpointUrlPolicy: OAuthEndpointUrlPolicy = {},\n): Record<string, unknown> => {\n const options: Record<string, unknown> = {\n signal: AbortSignal.timeout(timeoutMs ?? OAUTH2_DEFAULT_TIMEOUT_MS),\n };\n if (\n isLoopbackHttpUrl(targetUrl) ||\n (URL.canParse(targetUrl) &&\n new URL(targetUrl).protocol === \"http:\" &&\n endpointUrlPolicy.allowHttp === true)\n ) {\n (options as { [oauth.allowInsecureRequests]?: boolean })[oauth.allowInsecureRequests] = true;\n }\n return options;\n};\n\nconst pickClientAuth = (\n clientSecret: string | null | undefined,\n method: ClientAuthMethod,\n): oauth.ClientAuth => {\n if (!clientSecret) return oauth.None();\n return method === \"basic\"\n ? oauth.ClientSecretBasic(clientSecret)\n : oauth.ClientSecretPost(clientSecret);\n};\n\nconst tokenResponseFrom = (r: oauth.TokenEndpointResponse): OAuth2TokenResponse => ({\n access_token: r.access_token,\n token_type: r.token_type,\n refresh_token: r.refresh_token,\n expires_in: typeof r.expires_in === \"number\" ? r.expires_in : undefined,\n scope: r.scope,\n});\n\n// MCP source connections are pure OAuth 2.0 — we never request `openid` and\n// never consume `id_token`. Some providers (PostHog, etc.) front an OIDC\n// backend and emit an `id_token` anyway; oauth4webapi then strict-validates\n// its claims against the AS metadata and rejects mismatches we don't care\n// about. Strip the field before delegation.\nconst stripIdToken = async (response: Response): Promise<Response> => {\n const body = await response\n .clone()\n .json()\n .then(\n (value: unknown) => value,\n () => null,\n );\n if (!body || typeof body !== \"object\" || !(\"id_token\" in (body as Record<string, unknown>))) {\n return response;\n }\n const { id_token: _ignored, ...rest } = body as Record<string, unknown>;\n return new Response(JSON.stringify(rest), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n};\n\nconst processTokenEndpointResponse = async (\n as: oauth.AuthorizationServer,\n client: oauth.Client,\n response: Response,\n): Promise<OAuth2TokenResponse> =>\n tokenResponseFrom(\n await oauth.processGenericTokenEndpointResponse(as, client, await stripIdToken(response)),\n );\n\n// ---------------------------------------------------------------------------\n// Exchange authorization code → tokens\n// ---------------------------------------------------------------------------\n\nexport type ExchangeAuthorizationCodeInput = {\n readonly tokenUrl: string;\n readonly issuerUrl?: string | null;\n readonly clientId: string;\n readonly clientSecret?: string | null;\n readonly redirectUrl: string;\n readonly codeVerifier: string;\n readonly code: string;\n readonly clientAuth?: ClientAuthMethod;\n readonly idTokenSigningAlgValuesSupported?: readonly string[];\n /** RFC 8707 Resource Indicator. MCP Auth spec MUST-requires this on\n * the token request when the client knows the resource it intends\n * to call. */\n readonly resource?: string;\n readonly timeoutMs?: number;\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n};\n\nexport const exchangeAuthorizationCode = (\n input: ExchangeAuthorizationCodeInput,\n): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>\n Effect.tryPromise({\n try: async () => {\n const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {\n idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,\n endpointUrlPolicy: input.endpointUrlPolicy,\n });\n const client: oauth.Client = { client_id: input.clientId };\n const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? \"body\");\n // `authorizationCodeGrantRequest` requires its `callbackParameters`\n // to have been returned from `validateAuthResponse`. Our public API\n // takes the `code` directly (the UI already validated `state` by\n // looking up the session), so skip the library's state-validation\n // rail and go through the generic grant request instead.\n const params = new URLSearchParams({\n code: input.code,\n redirect_uri: input.redirectUrl,\n code_verifier: input.codeVerifier,\n });\n if (input.resource) {\n params.set(\"resource\", input.resource);\n }\n const response = await oauth.genericTokenEndpointRequest(\n as,\n client,\n clientAuth,\n \"authorization_code\",\n params,\n oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs, input.endpointUrlPolicy),\n );\n return await processTokenEndpointResponse(as, client, response);\n },\n catch: (cause) => cause,\n }).pipe(Effect.catch(failOAuth2WithHttpSummary));\n\n// ---------------------------------------------------------------------------\n// Exchange client credentials → tokens (RFC 6749 §4.4)\n// ---------------------------------------------------------------------------\n\nexport type ExchangeClientCredentialsInput = {\n readonly tokenUrl: string;\n readonly clientId: string;\n readonly clientSecret: string;\n readonly scopes?: readonly string[];\n readonly scopeSeparator?: string;\n readonly clientAuth?: ClientAuthMethod;\n readonly timeoutMs?: number;\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n};\n\nexport const exchangeClientCredentials = (\n input: ExchangeClientCredentialsInput,\n): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>\n Effect.tryPromise({\n try: async () => {\n const as = asFromTokenUrl(input.tokenUrl, input.endpointUrlPolicy);\n const client: oauth.Client = { client_id: input.clientId };\n const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? \"body\");\n const params = new URLSearchParams();\n if (input.scopes && input.scopes.length > 0) {\n params.set(\"scope\", input.scopes.join(input.scopeSeparator ?? \" \"));\n }\n const response = await oauth.clientCredentialsGrantRequest(\n as,\n client,\n clientAuth,\n params,\n oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs, input.endpointUrlPolicy),\n );\n const result = await oauth.processClientCredentialsResponse(as, client, response);\n return tokenResponseFrom(result);\n },\n catch: (cause) => cause,\n }).pipe(Effect.catch(failOAuth2WithHttpSummary));\n\n// ---------------------------------------------------------------------------\n// Refresh access token\n// ---------------------------------------------------------------------------\n\nexport type RefreshAccessTokenInput = {\n readonly tokenUrl: string;\n readonly issuerUrl?: string | null;\n readonly clientId: string;\n readonly clientSecret?: string | null;\n readonly refreshToken: string;\n readonly scopes?: readonly string[];\n readonly scopeSeparator?: string;\n readonly clientAuth?: ClientAuthMethod;\n readonly idTokenSigningAlgValuesSupported?: readonly string[];\n /** RFC 8707 Resource Indicator — MCP spec MUST-requires this on\n * refresh requests so the new access token's audience is bound to\n * the same resource. */\n readonly resource?: string;\n readonly timeoutMs?: number;\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n};\n\nexport const refreshAccessToken = (\n input: RefreshAccessTokenInput,\n): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>\n Effect.tryPromise({\n try: async () => {\n const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {\n idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,\n endpointUrlPolicy: input.endpointUrlPolicy,\n });\n const client: oauth.Client = { client_id: input.clientId };\n const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? \"body\");\n const extraParams = new URLSearchParams();\n if (input.scopes && input.scopes.length > 0) {\n extraParams.set(\"scope\", input.scopes.join(input.scopeSeparator ?? \" \"));\n }\n if (input.resource) {\n extraParams.set(\"resource\", input.resource);\n }\n const additionalParameters =\n Array.from(extraParams.keys()).length > 0 ? extraParams : undefined;\n const response = await oauth.refreshTokenGrantRequest(\n as,\n client,\n clientAuth,\n input.refreshToken,\n {\n ...oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs, input.endpointUrlPolicy),\n additionalParameters,\n },\n );\n const result = await oauth.processRefreshTokenResponse(\n as,\n client,\n await stripIdToken(response),\n );\n return tokenResponseFrom(result);\n },\n catch: (cause) => cause,\n }).pipe(Effect.catch(failOAuth2WithHttpSummary));\n\n// ---------------------------------------------------------------------------\n// Refresh-needed predicate\n// ---------------------------------------------------------------------------\n\nexport const shouldRefreshToken = (input: {\n readonly expiresAt: number | null;\n readonly now?: number;\n readonly skewMs?: number;\n}): boolean => {\n if (input.expiresAt === null) return false;\n const now = input.now ?? Date.now();\n const skew = input.skewMs ?? OAUTH2_REFRESH_SKEW_MS;\n return input.expiresAt <= now + skew;\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 };\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 (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 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 = 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","// ---------------------------------------------------------------------------\n// OAuth service implementation — the runtime behind `ctx.oauth`.\n//\n// Owns three flows, all on one codepath:\n//\n// - probe(endpoint) RFC 9728 + 8414 metadata lookup without\n// starting a flow. Used by onboarding UI\n// to decide between dynamic-DCR and\n// paste-your-credentials strategies.\n//\n// - start({strategy, ...}) Persists an `oauth2_session` row.\n// * `dynamic-dcr` runs discovery +\n// DCR + PKCE, emits\n// an authorization URL.\n// * `authorization-code`\n// uses pre-configured\n// client_id (secret)\n// + endpoints + PKCE.\n// * `client-credentials`\n// no user step —\n// mints the Connection\n// inline, returns\n// authorizationUrl=null.\n//\n// - complete({state, code}) Looks up the session, exchanges code\n// for tokens, creates the Connection via\n// `ctx.connections.create`, deletes the\n// session. Idempotent-ish in the sense\n// that a retried code past TTL fails\n// clean rather than draining the AS.\n//\n// The service also exposes a canonical `\"oauth2\"` `ConnectionProvider`\n// for refresh. The provider reads `providerState.kind` to pick which\n// token endpoint + client credentials to present; one handler covers\n// every strategy because refresh semantics are strategy-independent.\n// ---------------------------------------------------------------------------\n\nimport { Duration, Effect, Layer, Match, Option, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nimport type { IFumaClient, StorageFailure } from \"./fuma-runtime\";\n\nimport {\n ConnectionRefreshError,\n CreateConnectionInput,\n TokenMaterial,\n type ConnectionProvider,\n type ConnectionRefreshInput,\n type ConnectionRefreshResult,\n type ConnectionRef,\n} from \"./connections\";\nimport type { ConnectionProviderNotRegisteredError } from \"./errors\";\nimport { ConnectionId, ScopeId, SecretId } from \"./ids\";\nimport { SetSecretInput, type SecretRef } from \"./secrets\";\nimport {\n OAUTH2_PROVIDER_KEY,\n OAUTH2_SESSION_TTL_MS,\n OAuthCompleteError,\n OAuthProbeError,\n OAuthProviderState as OAuthProviderStateSchema,\n OAuthSessionNotFoundError,\n OAuthStartError,\n type OAuthAuthorizationCodeStrategy,\n type OAuthClientCredentialsStrategy,\n type OAuthCompleteInput,\n type OAuthCompleteResult,\n type OAuthDynamicDcrStrategy,\n type OAuthProbeInput,\n type OAuthProbeResult,\n type OAuthProviderState,\n type OAuthService,\n type OAuthStartInput,\n type OAuthStartResult,\n} from \"./oauth\";\nimport {\n beginDynamicAuthorization,\n discoverAuthorizationServerMetadata,\n discoverProtectedResourceMetadata,\n} from \"./oauth-discovery\";\nimport {\n buildAuthorizationUrl,\n createPkceCodeChallenge,\n createPkceCodeVerifier,\n exchangeAuthorizationCode,\n exchangeClientCredentials,\n type OAuth2Error,\n type OAuthEndpointUrlPolicy,\n refreshAccessToken,\n} from \"./oauth-helpers\";\n\n// ---------------------------------------------------------------------------\n// Session payload — persisted under `oauth2_session.payload` as opaque\n// JSON. Shape is strategy-specific; the discriminator matches\n// `OAuthStrategy[\"kind\"]` so completion picks the right exchange path.\n// ---------------------------------------------------------------------------\n\nconst OAuthAuthorizationServerMetadataJson = Schema.Record(Schema.String, Schema.Unknown);\nconst OAuthClientInformationJson = Schema.Record(Schema.String, Schema.Unknown);\n\nconst DynamicDcrSessionPayload = Schema.Struct({\n kind: Schema.Literal(\"dynamic-dcr\"),\n identityLabel: Schema.NullOr(Schema.String),\n codeVerifier: Schema.String,\n authorizationServerUrl: Schema.String,\n authorizationServerMetadataUrl: Schema.String,\n authorizationServerMetadata: OAuthAuthorizationServerMetadataJson,\n clientInformation: OAuthClientInformationJson,\n resourceMetadataUrl: Schema.NullOr(Schema.String),\n resourceMetadata: Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown)),\n scopes: Schema.Array(Schema.String),\n resource: Schema.NullOr(Schema.String).pipe(Schema.withDecodingDefaultType(Effect.succeed(null))),\n});\n\nconst AuthorizationCodeSessionPayload = Schema.Struct({\n kind: Schema.Literal(\"authorization-code\"),\n identityLabel: Schema.NullOr(Schema.String),\n codeVerifier: Schema.String,\n authorizationEndpoint: Schema.String,\n tokenEndpoint: Schema.String,\n issuerUrl: Schema.NullOr(Schema.String).pipe(\n Schema.withDecodingDefaultType(Effect.succeed(null)),\n ),\n clientIdSecretId: Schema.String,\n clientIdSecretScopeId: Schema.NullOr(Schema.String).pipe(\n Schema.withDecodingDefaultType(Effect.succeed(null)),\n ),\n clientSecretSecretId: Schema.NullOr(Schema.String),\n clientSecretSecretScopeId: Schema.NullOr(Schema.String).pipe(\n Schema.withDecodingDefaultType(Effect.succeed(null)),\n ),\n scopes: Schema.Array(Schema.String),\n scopeSeparator: Schema.optional(Schema.String),\n clientAuth: Schema.Literals([\"body\", \"basic\"]),\n});\n\n/** `client-credentials` doesn't produce a session row — it mints the\n * Connection inline during `start`. The shape is included here for\n * completeness / future device-code use. */\nconst OAuthSessionPayload = Schema.Union([\n DynamicDcrSessionPayload,\n AuthorizationCodeSessionPayload,\n]);\ntype OAuthSessionPayload = typeof OAuthSessionPayload.Type;\n\nconst decodeSessionPayload = Schema.decodeUnknownSync(OAuthSessionPayload);\nconst encodeSessionPayload = Schema.encodeSync(OAuthSessionPayload);\n\nconst UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);\nconst decodeUnknownJsonOption = Schema.decodeUnknownOption(UnknownFromJsonString);\n\nconst decodeProviderStateSync = Schema.decodeUnknownSync(OAuthProviderStateSchema);\nconst encodeProviderStateSync = Schema.encodeSync(OAuthProviderStateSchema);\n\nconst coerceJson = (value: unknown): unknown => {\n if (typeof value !== \"string\") return value;\n return decodeUnknownJsonOption(value).pipe(Option.getOrElse(() => value));\n};\n\nconst decodeProviderState = (value: unknown): OAuthProviderState =>\n decodeProviderStateSync(coerceJson(value));\n\n// ---------------------------------------------------------------------------\n// Service dependencies — the executor wires these up when it constructs\n// the service. Every dep is a narrow surface so the service stays\n// testable: point to a FumaDB handle + a secrets stub and every\n// code path is exercisable.\n// ---------------------------------------------------------------------------\n\nexport interface OAuthServiceDeps {\n readonly fuma: IFumaClient;\n /** Resolves client-id / client-secret refs at start + refresh time.\n * A `null` return means \"secret row is gone\" and aborts the flow. */\n readonly secretsGet: (id: string) => Effect.Effect<string | null, StorageFailure>;\n readonly secretsGetResolved?: (\n id: string,\n ) => Effect.Effect<\n { readonly value: string; readonly scopeId: string | null } | null,\n StorageFailure\n >;\n readonly secretsGetAtScope?: (\n id: string,\n scope: string,\n ) => Effect.Effect<string | null, StorageFailure>;\n readonly secretsSet: (input: SetSecretInput) => Effect.Effect<SecretRef, StorageFailure>;\n /** Mints the Connection row + backing secret rows. Called from\n * `complete` (and from `start` for `client-credentials`). */\n readonly connectionsCreate: (\n input: CreateConnectionInput,\n ) => Effect.Effect<ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure>;\n /** Random session id generator. Tests override to make outputs\n * deterministic. */\n readonly newSessionId?: () => string;\n /** `Date.now()` substitute — tests override to drive TTL behavior. */\n readonly now?: () => number;\n /** Outbound HTTP client used for OAuth metadata/DCR probes. */\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n readonly endpointUrlPolicy?: OAuthEndpointUrlPolicy;\n}\n\nconst defaultSessionId = (): string => {\n const crypto = globalThis.crypto;\n if (crypto?.randomUUID) return `oauth2_session_${crypto.randomUUID()}`;\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return `oauth2_session_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n )}`;\n};\n\nconst secretIdPart = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"oauth\";\n\nconst oauthSecretId = (\n connectionId: string,\n suffix: \"access-token\" | \"refresh-token\" | \"client-secret\",\n): string => {\n const base = secretIdPart(connectionId);\n const readable = base.length <= 48 ? base : base.slice(0, 40);\n return `oauth2-${readable}-${suffix}`;\n};\n\nconst scopedSessionId = (scopeId: string, sessionId: string): string =>\n `${sessionId}_${secretIdPart(scopeId).slice(0, 24)}`;\n\nconst terminalRefreshErrors = new Set([\"invalid_grant\", \"invalid_client\", \"unauthorized_client\"]);\n\n// ---------------------------------------------------------------------------\n// Service factory\n// ---------------------------------------------------------------------------\n\nexport const makeOAuth2Service = (\n deps: OAuthServiceDeps,\n): { readonly service: OAuthService; readonly connectionProvider: ConnectionProvider } => {\n const now = deps.now ?? (() => Date.now());\n const newSessionId = deps.newSessionId ?? defaultSessionId;\n const httpClientLayer = deps.httpClientLayer;\n const endpointUrlPolicy = deps.endpointUrlPolicy;\n const secretsGetResolved =\n deps.secretsGetResolved ??\n ((id: string) =>\n deps\n .secretsGet(id)\n .pipe(Effect.map((value) => (value === null ? null : { value, scopeId: null }))));\n const getSecretFromRecordedScope = (params: {\n readonly secretId: string;\n readonly scopeId: string | null;\n }) =>\n params.scopeId && deps.secretsGetAtScope\n ? deps.secretsGetAtScope(params.secretId, params.scopeId)\n : deps.secretsGet(params.secretId);\n const secretsGetResolvedAtScope = (params: {\n readonly secretId: string;\n readonly scopeId?: string | null;\n }) =>\n params.scopeId && deps.secretsGetAtScope\n ? deps\n .secretsGetAtScope(params.secretId, params.scopeId)\n .pipe(\n Effect.map((value) =>\n value === null ? null : { value, scopeId: params.scopeId ?? null },\n ),\n )\n : secretsGetResolved(params.secretId);\n\n // -------------------------------------------------------------------\n // probe\n // -------------------------------------------------------------------\n const probe = (input: OAuthProbeInput): Effect.Effect<OAuthProbeResult, OAuthProbeError> =>\n Effect.gen(function* () {\n const resource = yield* discoverProtectedResourceMetadata(input.endpoint, {\n httpClientLayer,\n resourceHeaders: input.headers,\n resourceQueryParams: input.queryParams,\n }).pipe(\n Effect.catchTag(\"OAuthDiscoveryError\", ({ message }) =>\n Effect.fail(\n new OAuthProbeError({\n message: `Protected resource metadata probe failed: ${message}`,\n }),\n ),\n ),\n );\n\n const authorizationServerUrl = yield* (() => {\n const fromResource = resource?.metadata.authorization_servers?.[0];\n if (fromResource) return Effect.succeed(fromResource);\n return Effect.try({\n try: () => {\n const u = new URL(input.endpoint);\n return `${u.protocol}//${u.host}`;\n },\n catch: () => null,\n }).pipe(Effect.catch(() => Effect.succeed(null)));\n })();\n\n const authServer = authorizationServerUrl\n ? yield* discoverAuthorizationServerMetadata(authorizationServerUrl, {\n httpClientLayer,\n }).pipe(Effect.catchTag(\"OAuthDiscoveryError\", () => Effect.succeed(null)))\n : null;\n\n // Dynamic registration is only viable when the AS advertises a\n // registration_endpoint AND a token_endpoint_auth_method we can use\n // (`none`, `client_secret_post`, or `client_secret_basic`). If the AS\n // doesn't list any methods we assume `none` is acceptable per OAuth\n // 2.1 §2.4 (server's choice).\n const advertisedAuthMethods =\n authServer?.metadata.token_endpoint_auth_methods_supported ?? [];\n const hasNegotiableAuthMethod =\n advertisedAuthMethods.length === 0 ||\n advertisedAuthMethods.some(\n (m) => m === \"none\" || m === \"client_secret_post\" || m === \"client_secret_basic\",\n );\n const supportsDynamicRegistration = !!(\n authServer?.metadata.registration_endpoint && hasNegotiableAuthMethod\n );\n\n // Bearer challenge probe — POST the endpoint unauth, look for\n // 401 + WWW-Authenticate: Bearer. Harmless against non-MCP\n // endpoints (Railway/GraphQL endpoints respond 200 or 400 with\n // protocol-specific bodies that we simply read as \"not a bearer\n // challenge\").\n const isBearerChallengeEndpoint = yield* Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n const probeUrl = new URL(input.endpoint);\n for (const [key, value] of Object.entries(input.queryParams ?? {})) {\n probeUrl.searchParams.set(key, value);\n }\n let request = HttpClientRequest.post(probeUrl.toString()).pipe(\n HttpClientRequest.setHeader(\"content-type\", \"application/json\"),\n HttpClientRequest.setHeader(\"accept\", \"application/json, text/event-stream\"),\n HttpClientRequest.bodyJsonUnsafe({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"initialize\",\n params: {\n protocolVersion: \"2025-06-18\",\n capabilities: {},\n clientInfo: { name: \"executor-probe\", version: \"0\" },\n },\n }),\n );\n for (const [name, value] of Object.entries(input.headers ?? {})) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n const response = yield* client.execute(request).pipe(Effect.timeout(Duration.seconds(6)));\n if (response.status !== 401) return false;\n const wwwAuth =\n response.headers[\"www-authenticate\"] ?? response.headers[\"WWW-Authenticate\"];\n return !!wwwAuth && /^\\s*bearer\\b/i.test(wwwAuth);\n }).pipe(\n Effect.provide(httpClientLayer ?? FetchHttpClient.layer),\n Effect.catch(() => Effect.succeed(false)),\n );\n\n return {\n resourceMetadata: (resource?.metadata as Record<string, unknown> | undefined) ?? null,\n resourceMetadataUrl: resource?.metadataUrl ?? null,\n authorizationServerMetadata:\n (authServer?.metadata as Record<string, unknown> | undefined) ?? null,\n authorizationServerMetadataUrl: authServer?.metadataUrl ?? null,\n authorizationServerUrl: authorizationServerUrl ?? null,\n supportsDynamicRegistration,\n isBearerChallengeEndpoint,\n };\n });\n\n // -------------------------------------------------------------------\n // start — branches on strategy.kind\n // -------------------------------------------------------------------\n const startDynamicDcr = (\n input: OAuthStartInput,\n strategy: OAuthDynamicDcrStrategy,\n ): Effect.Effect<OAuthStartResult, OAuthStartError | StorageFailure> =>\n Effect.gen(function* () {\n const started = yield* beginDynamicAuthorization(\n {\n endpoint: input.endpoint,\n redirectUrl: input.redirectUrl,\n state: \"\",\n scopes: strategy.scopes,\n },\n {\n httpClientLayer,\n resourceHeaders: input.headers,\n resourceQueryParams: input.queryParams,\n endpointUrlPolicy,\n },\n ).pipe(\n Effect.catchTag(\"OAuthDiscoveryError\", ({ message, error, errorDescription }) =>\n Effect.fail(\n new OAuthStartError({\n message: `Dynamic authorization setup failed: ${message}`,\n error,\n errorDescription,\n }),\n ),\n ),\n );\n\n const sessionId = scopedSessionId(input.tokenScope, newSessionId());\n\n // beginDynamicAuthorization returns an authorizationUrl already\n // signed with whatever `state` we passed. We need the session id\n // to be the state parameter so completion can look up the row.\n // Re-build the URL with the corrected state — cheap, one SHA-256\n // for the PKCE challenge, no network calls.\n const codeChallenge = yield* Effect.promise(() =>\n createPkceCodeChallenge(started.codeVerifier),\n );\n const authorizationUrl = buildAuthorizationUrl({\n authorizationUrl: started.state.authorizationServerMetadata.authorization_endpoint,\n clientId: started.state.clientInformation.client_id,\n redirectUrl: input.redirectUrl,\n scopes: started.state.scopes,\n state: sessionId,\n codeChallenge,\n resource: started.state.resource,\n endpointUrlPolicy,\n });\n\n const payload: OAuthSessionPayload = {\n kind: \"dynamic-dcr\",\n identityLabel: input.identityLabel ?? null,\n codeVerifier: started.codeVerifier,\n authorizationServerUrl: started.state.authorizationServerUrl,\n authorizationServerMetadataUrl: started.state.authorizationServerMetadataUrl,\n authorizationServerMetadata: started.state.authorizationServerMetadata as Record<\n string,\n unknown\n >,\n clientInformation: (() => {\n const value: unknown = started.state.clientInformation;\n return value as Record<string, unknown>;\n })(),\n resourceMetadataUrl: started.state.resourceMetadataUrl,\n resourceMetadata:\n (started.state.resourceMetadata as Record<string, unknown> | null) ?? null,\n scopes: [...started.state.scopes],\n resource: started.state.resource,\n };\n\n yield* writeSession({\n sessionId,\n input,\n payload,\n strategyKind: \"dynamic-dcr\",\n });\n\n return {\n sessionId,\n authorizationUrl,\n completedConnection: null,\n };\n });\n\n const startAuthorizationCode = (\n input: OAuthStartInput,\n strategy: OAuthAuthorizationCodeStrategy,\n ): Effect.Effect<OAuthStartResult, OAuthStartError | StorageFailure> =>\n Effect.gen(function* () {\n const clientIdRef = yield* secretsGetResolvedAtScope({\n secretId: strategy.clientIdSecretId,\n scopeId: strategy.clientIdSecretScopeId,\n }).pipe(\n Effect.mapError(\n (err) =>\n // Storage failure propagates; null returns aren't errors — the\n // branch below handles them.\n err,\n ),\n );\n if (clientIdRef === null) {\n return yield* new OAuthStartError({\n message: `client_id secret \"${strategy.clientIdSecretId}\" not found`,\n });\n }\n\n const sessionId = scopedSessionId(input.tokenScope, newSessionId());\n const codeVerifier = createPkceCodeVerifier();\n const codeChallenge = yield* Effect.promise(() => createPkceCodeChallenge(codeVerifier));\n\n const authorizationUrl = buildAuthorizationUrl({\n authorizationUrl: strategy.authorizationEndpoint,\n clientId: clientIdRef.value,\n redirectUrl: input.redirectUrl,\n scopes: strategy.scopes,\n state: sessionId,\n codeChallenge,\n scopeSeparator: strategy.scopeSeparator,\n extraParams: strategy.extraAuthorizationParams,\n endpointUrlPolicy,\n });\n\n const payload: OAuthSessionPayload = {\n kind: \"authorization-code\",\n identityLabel: input.identityLabel ?? null,\n codeVerifier,\n authorizationEndpoint: strategy.authorizationEndpoint,\n tokenEndpoint: strategy.tokenEndpoint,\n issuerUrl: strategy.issuerUrl ?? new URL(strategy.authorizationEndpoint).origin,\n clientIdSecretId: strategy.clientIdSecretId,\n clientIdSecretScopeId: clientIdRef.scopeId,\n clientSecretSecretId: strategy.clientSecretSecretId ?? null,\n clientSecretSecretScopeId: strategy.clientSecretSecretId\n ? ((yield* secretsGetResolvedAtScope({\n secretId: strategy.clientSecretSecretId,\n scopeId: strategy.clientSecretSecretScopeId,\n }))?.scopeId ?? null)\n : null,\n scopes: [...strategy.scopes],\n scopeSeparator: strategy.scopeSeparator,\n clientAuth: strategy.clientAuth ?? \"body\",\n };\n\n yield* writeSession({\n sessionId,\n input,\n payload,\n strategyKind: \"authorization-code\",\n });\n\n return {\n sessionId,\n authorizationUrl,\n completedConnection: null,\n };\n });\n\n const startClientCredentials = (\n input: OAuthStartInput,\n strategy: OAuthClientCredentialsStrategy,\n ): Effect.Effect<OAuthStartResult, OAuthStartError | StorageFailure> =>\n Effect.gen(function* () {\n const clientIdRef = yield* secretsGetResolvedAtScope({\n secretId: strategy.clientIdSecretId,\n scopeId: strategy.clientIdSecretScopeId,\n });\n const clientSecretRef = yield* secretsGetResolvedAtScope({\n secretId: strategy.clientSecretSecretId,\n scopeId: strategy.clientSecretSecretScopeId,\n });\n if (clientIdRef === null || clientSecretRef === null) {\n return yield* new OAuthStartError({\n message: \"client_id / client_secret secret not found\",\n });\n }\n\n const tokens = yield* exchangeClientCredentials({\n tokenUrl: strategy.tokenEndpoint,\n clientId: clientIdRef.value,\n clientSecret: clientSecretRef.value,\n scopes: strategy.scopes,\n scopeSeparator: strategy.scopeSeparator,\n clientAuth: strategy.clientAuth ?? \"body\",\n endpointUrlPolicy,\n }).pipe(\n Effect.mapError(\n ({ message }: OAuth2Error) =>\n new OAuthStartError({\n message: `Client credentials exchange failed: ${message}`,\n }),\n ),\n );\n\n const expiresAt =\n typeof tokens.expires_in === \"number\" ? now() + tokens.expires_in * 1000 : null;\n\n const providerState: OAuthProviderState = {\n kind: \"client-credentials\",\n tokenEndpoint: strategy.tokenEndpoint,\n clientIdSecretId: strategy.clientIdSecretId,\n clientIdSecretScopeId: clientIdRef.scopeId,\n clientSecretSecretId: strategy.clientSecretSecretId,\n clientSecretSecretScopeId: clientSecretRef.scopeId,\n scopes: [...(strategy.scopes ?? [])],\n scopeSeparator: strategy.scopeSeparator,\n clientAuth: strategy.clientAuth ?? \"body\",\n scope: tokens.scope ?? null,\n };\n\n yield* deps\n .connectionsCreate(\n CreateConnectionInput.make({\n id: ConnectionId.make(input.connectionId),\n scope: ScopeId.make(input.tokenScope),\n provider: OAUTH2_PROVIDER_KEY,\n identityLabel: input.identityLabel ?? safeHostname(input.endpoint),\n accessToken: TokenMaterial.make({\n secretId: SecretId.make(oauthSecretId(input.connectionId, \"access-token\")),\n name: \"OAuth Access Token\",\n value: tokens.access_token,\n }),\n refreshToken: null,\n expiresAt,\n oauthScope: tokens.scope ?? null,\n providerState: encodeProviderStateSync(providerState) as Record<string, unknown>,\n }),\n )\n .pipe(\n Effect.catchTags({\n ConnectionProviderNotRegisteredError: () =>\n Effect.fail(\n new OAuthStartError({\n message: \"Failed to mint connection: ConnectionProviderNotRegisteredError\",\n }),\n ),\n StorageError: ({ message }) =>\n Effect.fail(\n new OAuthStartError({\n message: `Failed to mint connection: ${message}`,\n }),\n ),\n UniqueViolationError: () =>\n Effect.fail(\n new OAuthStartError({\n message: \"Failed to mint connection: UniqueViolationError\",\n }),\n ),\n }),\n );\n\n return {\n sessionId: \"\",\n authorizationUrl: null,\n completedConnection: { connectionId: input.connectionId },\n };\n });\n\n const start = (\n input: OAuthStartInput,\n ): Effect.Effect<OAuthStartResult, OAuthStartError | StorageFailure> =>\n Match.value(input.strategy).pipe(\n Match.when({ kind: \"dynamic-dcr\" }, (strategy) => startDynamicDcr(input, strategy)),\n Match.when({ kind: \"authorization-code\" }, (strategy) =>\n startAuthorizationCode(input, strategy),\n ),\n Match.when({ kind: \"client-credentials\" }, (strategy) =>\n startClientCredentials(input, strategy),\n ),\n Match.exhaustive,\n );\n\n const writeSession = (args: {\n sessionId: string;\n input: OAuthStartInput;\n payload: OAuthSessionPayload;\n strategyKind: string;\n }): Effect.Effect<void, StorageFailure> =>\n deps.fuma\n .use(\"oauth2_session.create\", (db) =>\n db.create(\"oauth2_session\", {\n id: args.sessionId,\n scope_id: args.input.tokenScope,\n plugin_id: args.input.pluginId,\n strategy: args.strategyKind,\n connection_id: args.input.connectionId,\n token_scope: args.input.tokenScope,\n redirect_url: args.input.redirectUrl,\n payload: encodeSessionPayload(args.payload) as Record<string, unknown>,\n expires_at: now() + OAUTH2_SESSION_TTL_MS,\n created_at: new Date(),\n }),\n )\n .pipe(Effect.asVoid);\n\n // -------------------------------------------------------------------\n // complete — exchange the code, mint the Connection, delete the session\n // -------------------------------------------------------------------\n const complete = (\n input: OAuthCompleteInput,\n ): Effect.Effect<\n OAuthCompleteResult,\n OAuthCompleteError | OAuthSessionNotFoundError | StorageFailure\n > =>\n Effect.gen(function* () {\n const row = (yield* deps.fuma.use(\"oauth2_session.findForComplete\", (db) =>\n db.findFirst(\"oauth2_session\", {\n where: (b) => b(\"id\", \"=\", input.state),\n }),\n )) as {\n readonly id: string;\n readonly scope_id: string;\n readonly connection_id: string;\n readonly token_scope: string;\n readonly redirect_url: string;\n readonly payload: unknown;\n readonly expires_at: number | bigint | string;\n } | null;\n if (!row) {\n return yield* new OAuthSessionNotFoundError({ sessionId: input.state });\n }\n if (input.tokenScope !== undefined && row.token_scope !== input.tokenScope) {\n return yield* new OAuthSessionNotFoundError({ sessionId: input.state });\n }\n\n const deleteSession = deps.fuma.use(\"oauth2_session.deleteForComplete\", (db) =>\n db.deleteMany(\"oauth2_session\", {\n where: (b) => b.and(b(\"id\", \"=\", input.state), b(\"scope_id\", \"=\", row.scope_id)),\n }),\n );\n\n if (input.error) {\n yield* deleteSession;\n return yield* new OAuthCompleteError({\n message: `Authorization server returned error: ${input.error}`,\n code: input.error,\n });\n }\n if (!input.code) {\n yield* deleteSession;\n return yield* new OAuthCompleteError({\n message: \"Missing authorization code\",\n });\n }\n const expiresAt = Number(row.expires_at as number | bigint);\n if (expiresAt <= now()) {\n yield* deleteSession;\n return yield* new OAuthCompleteError({\n message: \"OAuth session expired\",\n });\n }\n\n const payload = decodeSessionPayload(coerceJson(row.payload));\n const endpoint = \"\"; // not stored on the row — the payload's own\n // endpoint fields drive exchange; we just need\n // a display string for the identity label.\n const connectionId = row.connection_id;\n const tokenScope = row.token_scope;\n const redirectUrl = row.redirect_url;\n\n // Dispatch to the strategy-specific exchange.\n const inputCode = input.code;\n const exchangeResult = yield* Match.value(payload)\n .pipe(\n Match.when({ kind: \"dynamic-dcr\" }, (p) => exchangeDynamicDcr(p, inputCode, redirectUrl)),\n Match.when({ kind: \"authorization-code\" }, (p) =>\n exchangeAuthorizationCodeStrategy(p, inputCode, redirectUrl),\n ),\n Match.exhaustive,\n )\n .pipe(Effect.tapError(() => deleteSession));\n\n const connectionExpiresAt =\n typeof exchangeResult.tokens.expires_in === \"number\"\n ? now() + exchangeResult.tokens.expires_in * 1000\n : null;\n\n const dynamicClientSecretSecretId = yield* (() => {\n if (payload.kind !== \"dynamic-dcr\") return Effect.succeed(null);\n const clientSecret = payload.clientInformation.client_secret;\n if (typeof clientSecret !== \"string\" || clientSecret.length === 0) {\n return Effect.succeed(null);\n }\n const secretId = oauthSecretId(connectionId, \"client-secret\");\n return deps\n .secretsSet(\n SetSecretInput.make({\n id: SecretId.make(secretId),\n scope: ScopeId.make(tokenScope),\n name: \"OAuth Client Secret\",\n value: clientSecret,\n }),\n )\n .pipe(\n Effect.as(secretId),\n Effect.catchTags({\n StorageError: ({ message }) =>\n Effect.fail(\n new OAuthCompleteError({\n message: `Failed to persist DCR client_secret: ${message}`,\n }),\n ),\n UniqueViolationError: () =>\n Effect.fail(\n new OAuthCompleteError({\n message: \"Failed to persist DCR client_secret: UniqueViolationError\",\n }),\n ),\n }),\n );\n })();\n\n const providerState: OAuthProviderState =\n payload.kind === \"dynamic-dcr\"\n ? {\n kind: \"dynamic-dcr\",\n tokenEndpoint: (\n payload.authorizationServerMetadata as {\n token_endpoint: string;\n }\n ).token_endpoint,\n issuerUrl:\n (payload.authorizationServerMetadata as { issuer?: string }).issuer ?? null,\n authorizationServerUrl: payload.authorizationServerUrl,\n authorizationServerMetadataUrl: payload.authorizationServerMetadataUrl,\n idTokenSigningAlgValuesSupported: (\n payload.authorizationServerMetadata as {\n id_token_signing_alg_values_supported?: string[];\n }\n ).id_token_signing_alg_values_supported,\n clientId: (payload.clientInformation as { client_id: string }).client_id,\n clientSecretSecretId: dynamicClientSecretSecretId,\n clientAuth:\n (payload.clientInformation as { token_endpoint_auth_method?: string })\n .token_endpoint_auth_method === \"client_secret_basic\"\n ? \"basic\"\n : \"body\",\n clientSecretSecretScopeId: dynamicClientSecretSecretId ? tokenScope : null,\n scopes: [...payload.scopes],\n scope: exchangeResult.tokens.scope ?? null,\n resource: payload.resource,\n }\n : {\n kind: \"authorization-code\",\n tokenEndpoint: payload.tokenEndpoint,\n issuerUrl: payload.issuerUrl,\n clientIdSecretId: payload.clientIdSecretId,\n clientIdSecretScopeId: payload.clientIdSecretScopeId,\n clientSecretSecretId: payload.clientSecretSecretId,\n clientSecretSecretScopeId: payload.clientSecretSecretScopeId,\n clientAuth: payload.clientAuth,\n scopes: [...payload.scopes],\n scopeSeparator: payload.scopeSeparator,\n scope: exchangeResult.tokens.scope ?? null,\n };\n\n yield* deps\n .connectionsCreate(\n CreateConnectionInput.make({\n id: ConnectionId.make(connectionId),\n scope: ScopeId.make(tokenScope),\n provider: OAUTH2_PROVIDER_KEY,\n identityLabel: safeHostname(\n payload.identityLabel ?? exchangeResult.endpointForDisplay ?? endpoint,\n ),\n accessToken: TokenMaterial.make({\n secretId: SecretId.make(oauthSecretId(connectionId, \"access-token\")),\n name: \"OAuth Access Token\",\n value: exchangeResult.tokens.access_token,\n }),\n refreshToken: exchangeResult.tokens.refresh_token\n ? TokenMaterial.make({\n secretId: SecretId.make(oauthSecretId(connectionId, \"refresh-token\")),\n name: \"OAuth Refresh Token\",\n value: exchangeResult.tokens.refresh_token,\n })\n : null,\n expiresAt: connectionExpiresAt,\n oauthScope: exchangeResult.tokens.scope ?? null,\n providerState: encodeProviderStateSync(providerState) as Record<string, unknown>,\n }),\n )\n .pipe(\n Effect.catchTags({\n ConnectionProviderNotRegisteredError: () =>\n Effect.fail(\n new OAuthCompleteError({\n message: \"Failed to mint connection: ConnectionProviderNotRegisteredError\",\n }),\n ),\n StorageError: ({ message }) =>\n Effect.fail(\n new OAuthCompleteError({\n message: `Failed to mint connection: ${message}`,\n }),\n ),\n UniqueViolationError: () =>\n Effect.fail(\n new OAuthCompleteError({\n message: \"Failed to mint connection: UniqueViolationError\",\n }),\n ),\n }),\n );\n\n yield* deleteSession;\n\n return {\n connectionId,\n expiresAt: connectionExpiresAt,\n scope: exchangeResult.tokens.scope ?? null,\n };\n });\n\n interface ExchangeResult {\n readonly tokens: {\n readonly access_token: string;\n readonly refresh_token?: string;\n readonly expires_in?: number;\n readonly scope?: string;\n readonly token_type?: string;\n };\n readonly endpointForDisplay: string | null;\n }\n\n const exchangeDynamicDcr = (\n payload: Extract<OAuthSessionPayload, { kind: \"dynamic-dcr\" }>,\n code: string,\n redirectUrl: string,\n ): Effect.Effect<ExchangeResult, OAuthCompleteError> =>\n Effect.gen(function* () {\n const md = payload.authorizationServerMetadata as {\n token_endpoint: string;\n issuer?: string;\n id_token_signing_alg_values_supported?: string[];\n };\n const ci = payload.clientInformation as {\n client_id: string;\n client_secret?: string;\n token_endpoint_auth_method?: string;\n };\n const tokens = yield* exchangeAuthorizationCode({\n tokenUrl: md.token_endpoint,\n issuerUrl: md.issuer,\n clientId: ci.client_id,\n clientSecret: ci.client_secret ?? undefined,\n redirectUrl,\n codeVerifier: payload.codeVerifier,\n code,\n idTokenSigningAlgValuesSupported: md.id_token_signing_alg_values_supported,\n clientAuth: ci.token_endpoint_auth_method === \"client_secret_basic\" ? \"basic\" : \"body\",\n resource: payload.resource ?? undefined,\n endpointUrlPolicy,\n }).pipe(\n Effect.mapError(\n ({ message, error }: OAuth2Error) =>\n new OAuthCompleteError({\n message: `Token exchange failed: ${message}`,\n code: error,\n }),\n ),\n );\n return {\n tokens,\n endpointForDisplay: payload.authorizationServerUrl,\n };\n });\n\n const exchangeAuthorizationCodeStrategy = (\n payload: Extract<OAuthSessionPayload, { kind: \"authorization-code\" }>,\n code: string,\n redirectUrl: string,\n ): Effect.Effect<ExchangeResult, OAuthCompleteError | StorageFailure> =>\n Effect.gen(function* () {\n const clientId = payload.clientIdSecretScopeId\n ? yield* getSecretFromRecordedScope({\n secretId: payload.clientIdSecretId,\n scopeId: payload.clientIdSecretScopeId,\n })\n : yield* deps.secretsGet(payload.clientIdSecretId);\n if (clientId === null) {\n return yield* new OAuthCompleteError({\n message: `client_id secret \"${payload.clientIdSecretId}\" not found`,\n });\n }\n const clientSecret = payload.clientSecretSecretId\n ? yield* getSecretFromRecordedScope({\n secretId: payload.clientSecretSecretId,\n scopeId: payload.clientSecretSecretScopeId,\n })\n : null;\n if (payload.clientSecretSecretId && clientSecret === null) {\n return yield* new OAuthCompleteError({\n message: `client_secret secret \"${payload.clientSecretSecretId}\" not found`,\n });\n }\n\n const tokens = yield* exchangeAuthorizationCode({\n tokenUrl: payload.tokenEndpoint,\n issuerUrl: payload.issuerUrl,\n clientId,\n clientSecret: clientSecret ?? undefined,\n redirectUrl,\n codeVerifier: payload.codeVerifier,\n code,\n clientAuth: payload.clientAuth,\n endpointUrlPolicy,\n }).pipe(\n Effect.mapError(\n ({ message, error }: OAuth2Error) =>\n new OAuthCompleteError({\n message: `Token exchange failed: ${message}`,\n code: error,\n }),\n ),\n );\n return {\n tokens,\n endpointForDisplay: null,\n };\n });\n\n const cancel = (sessionId: string, tokenScope: string): Effect.Effect<void, StorageFailure> =>\n deps.fuma\n .use(\"oauth2_session.cancel\", (db) =>\n db.deleteMany(\"oauth2_session\", {\n where: (b) => b.and(b(\"id\", \"=\", sessionId), b(\"scope_id\", \"=\", tokenScope)),\n }),\n )\n .pipe(Effect.asVoid);\n\n // -------------------------------------------------------------------\n // Canonical connection provider — refresh handler\n // -------------------------------------------------------------------\n const connectionProvider: ConnectionProvider = {\n key: OAUTH2_PROVIDER_KEY,\n refresh: (input: ConnectionRefreshInput) =>\n Effect.gen(function* () {\n if (!input.providerState) {\n return yield* new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: \"oauth2 connection missing providerState\",\n });\n }\n const state = yield* Effect.try({\n try: () => decodeProviderState(input.providerState),\n catch: (cause) =>\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: \"oauth2 providerState is malformed\",\n cause,\n }),\n });\n\n if (state.kind !== \"client-credentials\" && !input.refreshToken) {\n return yield* new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: \"oauth2 connection has no refresh token\",\n reauthRequired: true,\n });\n }\n\n // Resolve client credentials depending on strategy. Dynamic-DCR\n // embeds `client_id` inline (DCR-minted public client);\n // authorization-code reads it off a secret; client-credentials\n // reads both id + secret.\n const { clientId, clientSecret } = yield* Match.value(state).pipe(\n Match.when({ kind: \"dynamic-dcr\" }, (s) =>\n Effect.gen(function* () {\n const csec = s.clientSecretSecretId\n ? yield* getSecretFromRecordedScope({\n secretId: s.clientSecretSecretId,\n scopeId: s.clientSecretSecretScopeId ?? null,\n }).pipe(\n Effect.catchTags({\n StorageError: ({ message, cause }) =>\n Effect.fail(\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: `Failed to resolve DCR client_secret: ${message}`,\n cause,\n }),\n ),\n UniqueViolationError: (cause) =>\n Effect.fail(\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: \"Failed to resolve DCR client_secret: UniqueViolationError\",\n cause,\n }),\n ),\n }),\n )\n : null;\n if (s.clientSecretSecretId && csec === null) {\n return yield* new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: `client_secret secret \"${s.clientSecretSecretId}\" not found`,\n reauthRequired: true,\n });\n }\n return { clientId: s.clientId, clientSecret: csec };\n }),\n ),\n Match.whenOr({ kind: \"authorization-code\" }, { kind: \"client-credentials\" }, (s) =>\n Effect.gen(function* () {\n const cid = yield* getSecretFromRecordedScope({\n secretId: s.clientIdSecretId,\n scopeId: s.clientIdSecretScopeId ?? null,\n }).pipe(\n Effect.catchTags({\n StorageError: ({ message, cause }) =>\n Effect.fail(\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: `Failed to resolve client_id secret: ${message}`,\n cause,\n }),\n ),\n UniqueViolationError: (cause) =>\n Effect.fail(\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: \"Failed to resolve client_id secret: UniqueViolationError\",\n cause,\n }),\n ),\n }),\n );\n if (cid === null) {\n return yield* new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: `client_id secret \"${s.clientIdSecretId}\" not found`,\n reauthRequired: true,\n });\n }\n const csec = s.clientSecretSecretId\n ? yield* getSecretFromRecordedScope({\n secretId: s.clientSecretSecretId,\n scopeId: s.clientSecretSecretScopeId ?? null,\n }).pipe(\n Effect.catchTags({\n StorageError: ({ message, cause }) =>\n Effect.fail(\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: `Failed to resolve client_secret: ${message}`,\n cause,\n }),\n ),\n UniqueViolationError: (cause) =>\n Effect.fail(\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: \"Failed to resolve client_secret: UniqueViolationError\",\n cause,\n }),\n ),\n }),\n )\n : null;\n if (s.clientSecretSecretId && csec === null) {\n return yield* new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: `client_secret secret \"${s.clientSecretSecretId}\" not found`,\n reauthRequired: true,\n });\n }\n return { clientId: cid, clientSecret: csec };\n }),\n ),\n Match.exhaustive,\n );\n\n const tokenEndpoint = yield* (() => {\n if (state.tokenEndpoint) return Effect.succeed(state.tokenEndpoint);\n return Effect.fail(\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: \"oauth2 providerState is missing token endpoint\",\n reauthRequired: true,\n }),\n );\n })();\n\n const tokens = yield* (\n state.kind === \"client-credentials\"\n ? exchangeClientCredentials({\n tokenUrl: tokenEndpoint,\n clientId,\n clientSecret: clientSecret ?? \"\",\n scopes: state.scopes,\n scopeSeparator: state.scopeSeparator,\n clientAuth: state.clientAuth,\n endpointUrlPolicy,\n })\n : refreshAccessToken({\n tokenUrl: tokenEndpoint,\n issuerUrl:\n state.kind === \"dynamic-dcr\" || state.kind === \"authorization-code\"\n ? (state.issuerUrl ?? undefined)\n : undefined,\n clientId,\n clientSecret: clientSecret ?? undefined,\n refreshToken: input.refreshToken!,\n scopes:\n state.kind === \"dynamic-dcr\" || state.kind === \"authorization-code\"\n ? state.scopes\n : undefined,\n scopeSeparator:\n state.kind === \"dynamic-dcr\" || state.kind === \"authorization-code\"\n ? state.scopeSeparator\n : undefined,\n clientAuth: state.clientAuth,\n idTokenSigningAlgValuesSupported:\n state.kind === \"dynamic-dcr\" ? state.idTokenSigningAlgValuesSupported : undefined,\n endpointUrlPolicy,\n resource:\n state.kind === \"dynamic-dcr\" || state.kind === \"authorization-code\"\n ? (state.resource ?? undefined)\n : undefined,\n })\n ).pipe(\n Effect.mapError(\n ({ message, error }: OAuth2Error) =>\n new ConnectionRefreshError({\n connectionId: input.connectionId,\n message: `OAuth refresh failed: ${message}`,\n // Terminal RFC 6749 §5.2 errors mean retrying won't heal it.\n reauthRequired: error ? terminalRefreshErrors.has(error) : false,\n }),\n ),\n );\n\n const expiresAt =\n typeof tokens.expires_in === \"number\" ? now() + tokens.expires_in * 1000 : null;\n\n const result: ConnectionRefreshResult = {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token,\n expiresAt,\n oauthScope: tokens.scope ?? input.oauthScope,\n providerState: encodeProviderStateSync({\n ...state,\n tokenEndpoint,\n scope: tokens.scope ?? state.scope,\n }) as Record<string, unknown>,\n };\n return result;\n }),\n };\n\n const service: OAuthService = { probe, start, complete, cancel };\n\n return { service, connectionProvider };\n};\n\nconst safeHostname = (value: string | null): string | null => {\n if (!value) return null;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: URL constructor is the platform parser; non-URL labels remain display labels\n try {\n return new URL(value).host;\n } catch {\n return value;\n }\n};\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","import { Effect, Layer, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient } from \"effect/unstable/http\";\n\nexport class HostedOutboundRequestBlocked extends Schema.TaggedErrorClass<HostedOutboundRequestBlocked>()(\n \"HostedOutboundRequestBlocked\",\n {\n url: Schema.String,\n reason: Schema.String,\n },\n) {}\n\nexport interface HostedHttpClientOptions {\n readonly allowLocalNetwork?: boolean;\n readonly maxRedirects?: number;\n readonly fetch?: typeof globalThis.fetch;\n}\n\nconst parseIpv4 = (hostname: string): readonly [number, number, number, number] | null => {\n const parts = hostname.split(\".\");\n if (parts.length !== 4) return null;\n const parsed: number[] = [];\n for (const part of parts) {\n if (!/^\\d+$/.test(part)) return null;\n const value = Number(part);\n if (!Number.isInteger(value) || value < 0 || value > 255) return null;\n parsed.push(value);\n }\n return parsed as [number, number, number, number];\n};\n\nconst parseIpv4MappedIpv6 = (\n hostname: string,\n): readonly [number, number, number, number] | null => {\n const prefix = \"::ffff:\";\n if (!hostname.startsWith(prefix)) return null;\n const embedded = hostname.slice(prefix.length);\n const dotted = parseIpv4(embedded);\n if (dotted) return dotted;\n\n const parts = embedded.split(\":\");\n if (parts.length !== 2) return null;\n\n const words = parts.map((part) => Number.parseInt(part, 16));\n if (\n words.some(\n (word, index) =>\n parts[index] === \"\" ||\n !/^[0-9a-f]+$/i.test(parts[index]) ||\n !Number.isInteger(word) ||\n word < 0 ||\n word > 0xffff,\n )\n ) {\n return null;\n }\n\n const [high, low] = words;\n return [high >> 8, high & 0xff, low >> 8, low & 0xff];\n};\n\nconst isPrivateIpv4 = ([a, b]: readonly [number, number, number, number]): boolean =>\n a === 0 ||\n a === 10 ||\n a === 127 ||\n (a === 169 && b === 254) ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168);\n\nconst isBlockedMetadataHostname = (hostname: string): boolean => {\n const normalized = hostname.toLowerCase();\n return (\n normalized === \"metadata.google.internal\" ||\n normalized === \"metadata\" ||\n normalized === \"instance-data\" ||\n normalized === \"169.254.169.254\"\n );\n};\n\nconst isLocalOrPrivateHostname = (hostname: string): boolean => {\n const normalized = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (normalized === \"localhost\" || normalized.endsWith(\".localhost\")) return true;\n const ipv4 = parseIpv4(normalized);\n if (ipv4) return isPrivateIpv4(ipv4);\n const mappedIpv4 = parseIpv4MappedIpv6(normalized);\n if (mappedIpv4) return isPrivateIpv4(mappedIpv4);\n return (\n normalized === \"::1\" ||\n normalized.startsWith(\"fe80:\") ||\n normalized.startsWith(\"fc\") ||\n normalized.startsWith(\"fd\")\n );\n};\n\nexport const validateHostedOutboundUrl = (\n value: string,\n options: HostedHttpClientOptions = {},\n): Effect.Effect<void, HostedOutboundRequestBlocked> =>\n Effect.gen(function* () {\n const url = yield* Effect.try({\n try: () => new URL(value),\n catch: () =>\n new HostedOutboundRequestBlocked({\n url: value,\n reason: \"URL is invalid\",\n }),\n });\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return yield* new HostedOutboundRequestBlocked({\n url: value,\n reason: \"Only HTTP and HTTPS outbound requests are allowed\",\n });\n }\n\n if (isBlockedMetadataHostname(url.hostname)) {\n return yield* new HostedOutboundRequestBlocked({\n url: value,\n reason: \"Metadata service addresses are not allowed\",\n });\n }\n\n if (!options.allowLocalNetwork && isLocalOrPrivateHostname(url.hostname)) {\n return yield* new HostedOutboundRequestBlocked({\n url: value,\n reason: \"Local and private network addresses are not allowed\",\n });\n }\n });\n\nconst guardFetch = (\n underlying: typeof globalThis.fetch,\n options: HostedHttpClientOptions,\n): typeof globalThis.fetch =>\n (async (input, init) => {\n const maxRedirects = options.maxRedirects ?? 10;\n let current: Parameters<typeof globalThis.fetch>[0] | URL = input;\n for (let redirects = 0; redirects <= maxRedirects; redirects++) {\n const url = current instanceof Request ? current.url : String(current);\n Effect.runSync(validateHostedOutboundUrl(url, options));\n const response = await underlying(current, { ...init, redirect: \"manual\" });\n if (\n response.status >= 300 &&\n response.status < 400 &&\n response.headers.has(\"location\") &&\n redirects < maxRedirects\n ) {\n const next = new URL(response.headers.get(\"location\")!, url);\n if (next.origin !== new URL(url).origin) {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: fetch-compatible adapter must reject blocked requests\n throw new HostedOutboundRequestBlocked({\n url: next.toString(),\n reason: \"Cross-origin redirects are not allowed\",\n });\n }\n current = next.toString();\n continue;\n }\n return response;\n }\n return await underlying(current, { ...init, redirect: \"manual\" });\n }) as typeof globalThis.fetch;\n\nexport const makeHostedHttpClientLayer = (\n options: HostedHttpClientOptions = {},\n): Layer.Layer<HttpClient.HttpClient> =>\n FetchHttpClient.layer.pipe(\n Layer.provide(\n options.fetch\n ? Layer.succeed(FetchHttpClient.Fetch)(guardFetch(options.fetch, options))\n : Layer.effect(\n FetchHttpClient.Fetch,\n Effect.map(Effect.service(FetchHttpClient.Fetch), (underlying) =>\n guardFetch(underlying, options),\n ),\n ),\n ),\n );\n","import {\n Deferred,\n Duration,\n Effect,\n Layer,\n Match,\n Option,\n Predicate,\n Result,\n Schema,\n Semaphore,\n} from \"effect\";\nimport { FetchHttpClient, type HttpClient } from \"effect/unstable/http\";\nimport { fumadb } from \"fumadb\";\nimport { memoryAdapter } from \"fumadb/adapters/memory\";\nimport { withQueryContext, type Condition, type ConditionBuilder } from \"fumadb/query\";\nimport { schema as fumaSchema, type RelationsMap } from \"fumadb/schema\";\nimport type { AnyColumn } from \"fumadb/schema\";\nimport type { OAuthEndpointUrlPolicy } from \"./oauth-helpers\";\nimport { generateKeyBetween } from \"fractional-indexing\";\nimport {\n StorageError,\n isStorageFailure,\n makeFumaClient,\n type FumaDb,\n type FumaRow,\n type FumaTables,\n type StorageFailure,\n} from \"./fuma-runtime\";\n\nimport { makeFumaBlobStore, pluginBlobStore } from \"./blob\";\nimport { coreToolsPlugin } from \"./core-tools\";\nimport {\n ConnectionProviderState,\n ConnectionRef,\n ConnectionRefreshError,\n type ConnectionProvider,\n type ConnectionRefreshResult,\n type CreateConnectionInput,\n type RemoveConnectionInput,\n type UpdateConnectionTokensInput,\n} from \"./connections\";\nimport {\n credentialBindingId,\n credentialBindingRowToRef,\n type CredentialBindingRef,\n type CredentialBindingsFacade,\n type CredentialBindingSlotInput,\n type CredentialBindingSourceInput,\n type RemoveCredentialBindingInput,\n type RemoveSourceCredentialBindingInput,\n type ReplaceCredentialBindingsInput,\n type ReplaceSourceCredentialBindingsInput,\n ResolvedCredentialSlot,\n type SetPluginCredentialBindingInput,\n type SetSourceCredentialBindingInput,\n type SourceCredentialBindingSlotInput,\n type SourceCredentialBindingSourceInput,\n} from \"./credential-bindings\";\nimport {\n coreSchema,\n isToolPolicyAction,\n type ConnectionRow,\n type CredentialBindingRow,\n type CoreSchema,\n type DefinitionsInput,\n type SecretRow,\n type SourceInput,\n type SourceRow,\n type ToolAnnotations,\n type ToolPolicyRow,\n type ToolRow,\n} from \"./core-schema\";\nimport {\n ElicitationDeclinedError,\n ElicitationResponse,\n FormElicitation,\n type ElicitationHandler,\n type ElicitationRequest,\n} from \"./elicitation\";\nimport {\n ConnectionInUseError,\n ConnectionNotFoundError,\n ConnectionProviderNotRegisteredError,\n ConnectionReauthRequiredError,\n ConnectionRefreshNotSupportedError,\n NoHandlerError,\n PluginNotLoadedError,\n SecretInUseError,\n SecretOwnedByConnectionError,\n SourceRemovalNotAllowedError,\n ToolBlockedError,\n ToolInvocationError,\n ToolNotFoundError,\n} from \"./errors\";\nimport { ConnectionId, ScopeId, SecretId, ToolId } from \"./ids\";\nimport { makeOAuth2Service } from \"./oauth-service\";\nimport type { OAuthService } from \"./oauth\";\nimport {\n comparePolicyRow,\n isValidPattern,\n resolveToolPolicy,\n rowToToolPolicy,\n type CreateToolPolicyInput,\n type PolicyMatch,\n type RemoveToolPolicyInput,\n type ToolPolicy,\n type UpdateToolPolicyInput,\n} from \"./policies\";\nimport type {\n AnyPlugin,\n Elicit,\n PluginCtx,\n PluginExtensions,\n SourceConfigureSchema,\n StaticSourceDecl,\n StaticToolDecl,\n StaticToolSchema,\n StorageDeps,\n} from \"./plugin\";\nimport {\n pluginStorageId,\n type PluginStorageEntry,\n type PluginStorageFacade,\n} from \"./plugin-storage\";\nimport type { Scope } from \"./scope\";\nimport { RemoveSecretInput, SecretRef, SetSecretInput, type SecretProvider } from \"./secrets\";\nimport { Usage } from \"./usages\";\nimport {\n ToolSchema,\n type RefreshSourceInput,\n type RemoveSourceInput,\n type Source,\n type SourceDetectionResult,\n type Tool,\n type ToolListFilter,\n} from \"./types\";\nimport { buildToolTypeScriptPreview, type ToolTypeScriptPreview } from \"./schema-types\";\nimport { collectReferencedDefinitions } from \"./schema-refs\";\nimport { assertExecutorScopePolicyTable, type ExecutorScopePolicyContext } from \"./scope-policy\";\nimport { validateHostedOutboundUrl } from \"./hosted-http-client\";\n\nconst MAX_ANNOTATION_GROUPS = 64;\nconst MAX_APPROVAL_ARGUMENT_PREVIEW_CHARS = 4_000;\n\n// ---------------------------------------------------------------------------\n// Elicitation handler — set once at `createExecutor({ onElicitation })`\n// and threaded into every tool invocation. A tool that requests user\n// input mid-execution suspends the fiber and the handler decides how to\n// respond. Tools that never elicit simply don't trigger the handler.\n//\n// The \"accept-all\" sentinel is convenient for tests and CLI automation —\n// every elicitation request gets auto-accepted with an empty content\n// payload. For real interactive hosts, pass a real handler.\n//\n// Required at the executor level rather than per-invoke, so the\n// \"what if a caller forgot to pass a handler\" branch is structurally\n// impossible. Higher layers that need per-invocation handler control\n// (an MCP server bridging different per-client handlers, the execution\n// engine threading agent-loop callbacks) can pass an override via\n// `tools.invoke(id, args, { onElicitation })` — the executor-level\n// handler is the fallback, never null.\n// ---------------------------------------------------------------------------\n\nexport type OnElicitation = ElicitationHandler | \"accept-all\";\n\nexport interface InvokeOptions {\n /** Override the executor-level handler for this single call. */\n readonly onElicitation?: OnElicitation;\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// Executor — public surface. Every list/invoke/schema call is a direct\n// core-table query (for dynamic rows) unioned with the in-memory static\n// pool. No ToolRegistry, no SourceRegistry, no SecretStore services.\n// ---------------------------------------------------------------------------\n\nexport type Executor<TPlugins extends readonly AnyPlugin[] = readonly []> = {\n /**\n * Precedence-ordered scope stack this executor was configured with.\n * Innermost first. Consumers that need \"the display scope\" typically\n * pick `scopes.at(-1)` (outermost, e.g. the organization) or\n * `scopes[0]` (innermost, e.g. the current user-in-org) depending on\n * what they're rendering.\n */\n readonly scopes: readonly Scope[];\n\n readonly tools: {\n readonly list: (filter?: ToolListFilter) => Effect.Effect<readonly Tool[], StorageFailure>;\n /** Fetch a tool's schema view: JSON schemas with `$defs`\n * attached from the core `definition` table, plus TypeScript\n * preview strings. Returns `null` for unknown tool ids. */\n readonly schema: (toolId: string) => Effect.Effect<ToolSchema | null, StorageFailure>;\n /** Every `$defs` entry across every source, grouped by source id.\n * Used for bulk schema export and downstream TypeScript rendering. */\n readonly definitions: () => Effect.Effect<\n Record<string, Record<string, unknown>>,\n StorageFailure\n >;\n readonly invoke: (\n toolId: string,\n args: unknown,\n options?: InvokeOptions,\n ) => Effect.Effect<\n unknown,\n | ToolNotFoundError\n | ToolBlockedError\n | PluginNotLoadedError\n | NoHandlerError\n | ToolInvocationError\n | ElicitationDeclinedError\n | StorageFailure\n >;\n };\n\n readonly sources: {\n readonly list: () => Effect.Effect<readonly Source[], StorageFailure>;\n readonly remove: (\n input: RemoveSourceInput,\n ) => Effect.Effect<void, SourceRemovalNotAllowedError | StorageFailure>;\n readonly refresh: (input: RefreshSourceInput) => Effect.Effect<void, StorageFailure>;\n /** URL autodetection — fans out to every plugin's `detect` hook\n * (if declared), returns every high/medium/low-confidence match.\n * UI picks a winner from the list. */\n readonly detect: (\n url: string,\n ) => Effect.Effect<readonly SourceDetectionResult[], StorageFailure>;\n /** All `$defs` registered for a single source, keyed by def name. */\n readonly definitions: (\n sourceId: string,\n ) => Effect.Effect<Record<string, unknown>, StorageFailure>;\n readonly configure: (input: {\n readonly source: {\n readonly id: string;\n readonly scope: ScopeId | string;\n };\n readonly scope: ScopeId | string;\n readonly type?: string;\n readonly config: unknown;\n }) => Effect.Effect<unknown, StorageFailure>;\n readonly listBindings: (\n input: SourceCredentialBindingSourceInput,\n ) => Effect.Effect<readonly CredentialBindingRef[], StorageFailure>;\n readonly resolveBinding: (\n input: SourceCredentialBindingSlotInput,\n ) => Effect.Effect<CredentialBindingRef | null, StorageFailure>;\n readonly setBinding: (\n input: SetSourceCredentialBindingInput,\n ) => Effect.Effect<CredentialBindingRef, StorageFailure>;\n readonly removeBinding: (\n input: RemoveSourceCredentialBindingInput,\n ) => Effect.Effect<void, StorageFailure>;\n readonly replaceBindings: (\n input: ReplaceSourceCredentialBindingsInput,\n ) => Effect.Effect<readonly CredentialBindingRef[], StorageFailure>;\n };\n\n readonly secrets: {\n readonly get: (\n id: string,\n ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>;\n readonly getAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>;\n /** Fast-path existence check — hits the core `secret` routing table\n * only, never calls the provider. Use this for UI state (\"secret\n * missing, prompt to add\") to avoid keychain permission prompts\n * or 1password IPC roundtrips on a pre-flight check. */\n readonly status: (id: string) => Effect.Effect<\"resolved\" | \"missing\", StorageFailure>;\n readonly set: (input: SetSecretInput) => Effect.Effect<SecretRef, StorageFailure>;\n /** Delete a bare (non-connection-owned) secret. Connection-owned\n * secrets are rejected with `SecretOwnedByConnectionError` — use\n * `connections.remove` instead. Refuses with `SecretInUseError`\n * if any plugin reports the secret as in use; the caller should\n * show the `usages(id)` list and ask the user to detach first. */\n readonly remove: (\n input: RemoveSecretInput,\n ) => Effect.Effect<void, SecretOwnedByConnectionError | SecretInUseError | StorageFailure>;\n readonly list: () => Effect.Effect<readonly SecretRef[], StorageFailure>;\n /** Management view of visible secret rows. Unlike `list`, this does\n * not collapse same-id rows across scopes, so UI that writes exact\n * credential targets can show both personal and shared rows. */\n readonly listAll: () => Effect.Effect<readonly SecretRef[], StorageFailure>;\n /** All places this secret is referenced — fans out across every\n * plugin's `usagesForSecret`. Used by the Secrets-tab \"Used by\"\n * list and by `remove` for its RESTRICT check. */\n readonly usages: (id: string) => Effect.Effect<readonly Usage[], StorageFailure>;\n readonly providers: () => Effect.Effect<readonly string[]>;\n };\n\n readonly connections: {\n readonly get: (id: string) => Effect.Effect<ConnectionRef | null, StorageFailure>;\n readonly getAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<ConnectionRef | null, StorageFailure>;\n readonly list: () => Effect.Effect<readonly ConnectionRef[], StorageFailure>;\n readonly create: (\n input: CreateConnectionInput,\n ) => Effect.Effect<ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure>;\n readonly updateTokens: (\n input: UpdateConnectionTokensInput,\n ) => Effect.Effect<ConnectionRef, ConnectionNotFoundError | StorageFailure>;\n readonly setIdentityLabel: (\n id: string,\n label: string | null,\n ) => Effect.Effect<void, ConnectionNotFoundError | StorageFailure>;\n readonly accessToken: (\n id: string,\n ) => Effect.Effect<\n string,\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure\n >;\n readonly accessTokenAtScope: (\n id: string,\n scope: string,\n ) => Effect.Effect<\n string,\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure\n >;\n /** Refuses with `ConnectionInUseError` if any plugin reports the\n * connection as in use. */\n readonly remove: (\n input: RemoveConnectionInput,\n ) => Effect.Effect<void, ConnectionInUseError | StorageFailure>;\n /** All places this connection is referenced — fans out across every\n * plugin's `usagesForConnection`. */\n readonly usages: (id: string) => Effect.Effect<readonly Usage[], StorageFailure>;\n readonly providers: () => Effect.Effect<readonly string[]>;\n };\n\n /** Shared credential slot bindings. Plugins decide what slot keys mean;\n * core owns scoped storage, resolution status, and usage visibility. */\n readonly credentialBindings: CredentialBindingsFacade;\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 policies: {\n /** All policies visible across the executor's scope stack, sorted\n * by (innermost-scope-first, position ascending) — i.e. the order\n * in which they're evaluated by first-match-wins. */\n readonly list: () => Effect.Effect<readonly ToolPolicy[], StorageFailure>;\n /** Create a new policy. Defaults to the top of the target scope's\n * list (highest precedence) when `position` is omitted. */\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 /** Resolve the effective policy for a tool id by walking the scope-\n * stacked policy list with first-match-wins semantics. Returns\n * `undefined` when no rule matches (caller falls back to the\n * plugin's `resolveAnnotations` output). */\n readonly resolve: (toolId: string) => Effect.Effect<PolicyMatch | undefined, StorageFailure>;\n };\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 /**\n * Precedence-ordered scope stack. Innermost first; typical shape is\n * `[userInOrgScope, orgScope]`. Reads on scoped tables walk the\n * stack (first hit wins for shadow-by-id consumers like secrets and\n * blobs); writes require callers to name an explicit target scope.\n * Must be non-empty.\n */\n readonly scopes: readonly Scope[];\n readonly db?: ExecutorDbInput | ExecutorDbFactory;\n readonly plugins?: TPlugins;\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 * `(ctx) => Effect<ElicitationResponse>` for interactive ones.\n * Required at construction so per-invoke calls don't have to thread\n * an options arg.\n */\n readonly onElicitation: OnElicitation;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n readonly oauthEndpointUrlPolicy?: OAuthEndpointUrlPolicy;\n readonly sourceDetection?: {\n readonly maxUrlLength?: number;\n readonly maxDetectors?: number;\n readonly maxResults?: number;\n readonly timeout?: Duration.Input;\n readonly hostedOutboundPolicy?: boolean;\n };\n /**\n * Enable the built-in `core-tools` plugin which contributes\n * agent-facing static tools (`scopes.list`, `secrets.list`,\n * `secrets.create`). The `webBaseUrl` is where the executor's web\n * UI lives; `secrets.create` builds a URL elicitation that points\n * the user at `${webBaseUrl}/secrets?...` so the plaintext value\n * never crosses the agent.\n *\n * Omit to skip registration (tests, MCP-only hosts that don't\n * surface a web UI, etc.).\n */\n readonly coreTools?: {\n readonly webBaseUrl: string;\n };\n}\n\n// ---------------------------------------------------------------------------\n// collectTables — merge core tables with every plugin's declared Fuma table.\n// Hosts pass the result to FumaDB when constructing the database client.\n// ---------------------------------------------------------------------------\n\nexport const collectTables = (plugins: readonly AnyPlugin[]): FumaTables => {\n const merged: FumaTables = { ...coreSchema };\n for (const plugin of plugins) {\n if (!plugin.schema) continue;\n for (const [tableKey, tableDef] of Object.entries(plugin.schema)) {\n if (merged[tableKey]) {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: collectTables is a synchronous configuration API\n throw new StorageError({\n message:\n `Duplicate storage table \"${tableKey}\" contributed by plugin \"${plugin.id}\"` +\n ` (reserved by core or another plugin)`,\n cause: undefined,\n });\n }\n merged[tableKey] = tableDef as FumaTables[string];\n }\n }\n\n validateExecutorScopePolicyTables(merged);\n\n return merged;\n};\n\nconst validateExecutorScopePolicyTables = (tables: FumaTables): void => {\n for (const [tableKey, tableDef] of Object.entries(tables)) {\n assertExecutorScopePolicyTable(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: dynamic plugin table map is known only after collectTables()\n const db = factory.client(memoryAdapter()).orm(version) as unknown as FumaDb;\n return {\n db,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Row → public projection conversions\n// ---------------------------------------------------------------------------\n\nconst rowToSource = (row: SourceRow): Source => ({\n id: row.id,\n scopeId: row.scope_id,\n kind: row.kind,\n name: row.name,\n url: row.url ?? undefined,\n pluginId: row.plugin_id,\n canRemove: Boolean(row.can_remove),\n canRefresh: Boolean(row.can_refresh),\n canEdit: Boolean(row.can_edit),\n runtime: false,\n});\n\nconst staticDeclToSource = (decl: StaticSourceDecl, pluginId: string): Source => ({\n id: decl.id,\n scopeId: undefined,\n kind: decl.kind,\n name: decl.name,\n url: decl.url,\n pluginId,\n canRemove: decl.canRemove ?? false,\n canRefresh: decl.canRefresh ?? false,\n canEdit: decl.canEdit ?? false,\n runtime: true,\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 decodeProviderState = Schema.decodeUnknownOption(ConnectionProviderState);\n\nconst rowToTool = (row: ToolRow, annotations?: ToolAnnotations): Tool => ({\n id: row.id,\n sourceId: row.source_id,\n pluginId: row.plugin_id,\n name: row.name,\n description: row.description,\n inputSchema: decodeJsonColumn(row.input_schema),\n outputSchema: decodeJsonColumn(row.output_schema),\n annotations,\n});\n\nconst staticDeclToTool = (\n source: StaticSourceDecl,\n tool: StaticToolDecl,\n pluginId: string,\n): Tool => ({\n id: `${source.id}.${tool.name}`,\n sourceId: source.id,\n pluginId,\n name: tool.name,\n description: tool.description,\n inputSchema: toToolJsonSchema(tool.inputSchema),\n outputSchema: toToolJsonSchema(tool.outputSchema, \"output\"),\n annotations: tool.annotations,\n});\n\nconst toToolJsonSchema = (\n schema: StaticToolSchema | undefined,\n direction: \"input\" | \"output\" = \"input\",\n): unknown => {\n if (schema == null) return undefined;\n return schema[\"~standard\"].jsonSchema[direction]({\n target: \"draft-2020-12\",\n });\n};\n\nconst toConfigureJsonSchema = (\n schema: StaticToolSchema | Schema.Decoder<unknown, never> | undefined,\n): unknown => {\n if (schema == null) return undefined;\n const standard = schema as {\n readonly \"~standard\"?: {\n readonly validate?: unknown;\n readonly jsonSchema?: StaticToolSchema[\"~standard\"][\"jsonSchema\"];\n };\n };\n if (typeof standard[\"~standard\"]?.validate !== \"function\") {\n const jsonSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(schema as Schema.Decoder<unknown, never>) as never,\n ) as StaticToolSchema;\n return toToolJsonSchema(jsonSchema);\n }\n return standard[\"~standard\"].jsonSchema?.input({\n target: \"draft-2020-12\",\n });\n};\n\nconst decodeConfigureInput = (\n schema: StaticToolSchema | Schema.Decoder<unknown, never> | undefined,\n input: unknown,\n): Effect.Effect<unknown, unknown> => {\n if (schema == null) return Effect.succeed(input);\n const standard = schema as {\n readonly \"~standard\"?: { readonly validate?: unknown };\n };\n if (standard[\"~standard\"] === undefined || typeof standard[\"~standard\"].validate !== \"function\") {\n return Schema.decodeUnknownEffect(schema as Schema.Decoder<unknown, never>)(input);\n }\n return Effect.promise(() =>\n Promise.resolve((standard[\"~standard\"]!.validate as (input: unknown) => unknown)(input)),\n ).pipe(\n Effect.flatMap((result) => {\n const validationResult = result as { readonly value?: unknown };\n return \"value\" in validationResult\n ? Effect.succeed(validationResult.value)\n : Effect.fail(result);\n }),\n );\n};\n\nconst sourceConfigureSchemaView = (\n pluginId: string,\n configure: NonNullable<AnyPlugin[\"sourceConfigure\"]>,\n): SourceConfigureSchema => ({\n pluginId,\n type: configure.type,\n schema: toConfigureJsonSchema(configure.schema),\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 scopeFilter =\n (scopes: readonly string[]) =>\n (b: ConditionBuilder<Record<string, AnyColumn>>): Condition =>\n scopes.length === 1 ? b(\"scope_id\", \"=\", scopes[0]!) : b(\"scope_id\", \"in\", [...scopes]);\n\nconst scopedWhere =\n (\n scopes: readonly string[],\n where?: (b: ConditionBuilder<Record<string, AnyColumn>>) => Condition | boolean,\n ) =>\n (b: ConditionBuilder<Record<string, AnyColumn>>): Condition | boolean =>\n b.and(scopeFilter(scopes)(b), where ? where(b) : true);\n\nconst byId =\n (id: string) =>\n (b: ConditionBuilder<Record<string, AnyColumn>>): Condition =>\n b(\"id\", \"=\", id);\n\nconst byScopedId =\n (scope: string, id: string) =>\n (b: ConditionBuilder<Record<string, AnyColumn>>): Condition =>\n b.and(b(\"scope_id\", \"=\", scope), b(\"id\", \"=\", id)) as Condition;\n\nconst toolSourceId = (toolId: string): string | null => {\n const dot = toolId.indexOf(\".\");\n return dot === -1 ? null : toolId.slice(0, dot);\n};\n\nconst levenshteinDistance = (left: string, right: string): number => {\n const previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n const current = Array.from({ length: right.length + 1 }, () => 0);\n for (let i = 0; i < left.length; i++) {\n current[0] = i + 1;\n for (let j = 0; j < right.length; j++) {\n current[j + 1] =\n left[i] === right[j]\n ? previous[j]!\n : Math.min(previous[j]!, previous[j + 1]!, current[j]!) + 1;\n }\n for (let j = 0; j < previous.length; j++) previous[j] = current[j]!;\n }\n return previous[right.length]!;\n};\n\nconst missingToolSuggestionScore = (query: string, candidate: string): number => {\n const normalizedQuery = query.toLowerCase();\n const normalizedCandidate = candidate.toLowerCase();\n if (normalizedCandidate === normalizedQuery) return 0;\n if (normalizedCandidate.startsWith(normalizedQuery)) return 1;\n if (normalizedQuery.startsWith(normalizedCandidate)) return 2;\n if (normalizedCandidate.includes(normalizedQuery)) return 3;\n const queryLeaf = normalizedQuery.split(\".\").at(-1) ?? normalizedQuery;\n const candidateLeaf = normalizedCandidate.split(\".\").at(-1) ?? normalizedCandidate;\n if (candidateLeaf.startsWith(queryLeaf) || queryLeaf.startsWith(candidateLeaf)) return 4;\n return 10 + levenshteinDistance(normalizedQuery, normalizedCandidate);\n};\n\nconst missingToolSuggestions = (\n toolId: string,\n rows: readonly { readonly id: string }[],\n): readonly ToolId[] =>\n rows\n .map((row) => ({ id: row.id, score: missingToolSuggestionScore(toolId, row.id) }))\n .sort((left, right) => left.score - right.score || left.id.localeCompare(right.id))\n .slice(0, 5)\n .map((item) => ToolId.make(item.id));\n\ntype CoreTableName = keyof CoreSchema & string;\ntype CoreRow<TName extends CoreTableName> = FumaRow<CoreSchema[TName]>;\ntype CoreWhere<_TName extends CoreTableName> = (\n b: ConditionBuilder<Record<string, AnyColumn>>,\n) => Condition | boolean;\ntype CoreFindManyOptions<TName extends CoreTableName> = {\n readonly where?: CoreWhere<TName>;\n readonly limit?: number;\n readonly offset?: number;\n readonly orderBy?:\n | readonly [string, \"asc\" | \"desc\"]\n | readonly (readonly [string, \"asc\" | \"desc\"])[];\n};\ntype CoreFindFirstOptions<TName extends CoreTableName> = Omit<\n CoreFindManyOptions<TName>,\n \"limit\" | \"offset\"\n>;\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<TName> },\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<TName> } = {},\n ): Effect.Effect<void, StorageFailure> =>\n fuma.use(`${tableName}.deleteMany`, (db) =>\n asLooseStorageDb(db).deleteMany(tableName, options),\n ),\n findFirst: <TName extends CoreTableName>(\n tableName: TName,\n options: CoreFindFirstOptions<TName>,\n ): Effect.Effect<CoreRow<TName> | null, StorageFailure> =>\n fuma.use(`${tableName}.findFirst`, (db) =>\n asLooseStorageDb(db).findFirst(tableName, options),\n ) as Effect.Effect<CoreRow<TName> | null, StorageFailure>,\n findMany: <TName extends CoreTableName>(\n tableName: TName,\n options: CoreFindManyOptions<TName> = {},\n ): Effect.Effect<readonly CoreRow<TName>[], StorageFailure> =>\n fuma.use(`${tableName}.findMany`, (db) =>\n asLooseStorageDb(db).findMany(tableName, options),\n ) as Effect.Effect<readonly CoreRow<TName>[], StorageFailure>,\n updateMany: <TName extends CoreTableName>(\n tableName: TName,\n options: {\n readonly where?: CoreWhere<TName>;\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\nconst pluginStorageEntryFromRow = <T>(row: CoreRow<\"plugin_storage\">): PluginStorageEntry<T> => ({\n id: row.id,\n scopeId: ScopeId.make(row.scope_id),\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 makePluginStorageFacade = (input: {\n readonly core: ReturnType<typeof makeCoreDb>;\n readonly pluginId: string;\n readonly scopeIds: readonly string[];\n}): PluginStorageFacade => {\n const whereFor = (collection: string, key?: string) =>\n scopedWhere(input.scopeIds, (b) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"collection\", \"=\", collection),\n key === undefined ? true : b(\"key\", \"=\", key),\n ),\n );\n\n const sortByScopePrecedence = (rows: readonly CoreRow<\"plugin_storage\">[]) =>\n [...rows].sort((left, right) => {\n const leftIndex = input.scopeIds.indexOf(left.scope_id);\n const rightIndex = input.scopeIds.indexOf(right.scope_id);\n return leftIndex - rightIndex || left.key.localeCompare(right.key);\n });\n\n const getVisible = <T>(collection: string, key: string) =>\n input.core\n .findMany(\"plugin_storage\", { where: whereFor(collection, key) })\n .pipe(Effect.map((rows) => sortByScopePrecedence(rows)[0] ?? null))\n .pipe(Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null)));\n\n return {\n get: (storageInput) => getVisible(storageInput.collection, storageInput.key),\n getAtScope: (storageInput) =>\n input.core\n .findFirst(\"plugin_storage\", {\n where: byScopedId(\n storageInput.scope,\n pluginStorageId({\n pluginId: input.pluginId,\n collection: storageInput.collection,\n key: storageInput.key,\n }),\n ),\n })\n .pipe(Effect.map((row) => (row ? pluginStorageEntryFromRow(row) : null))),\n list: (storageInput) =>\n input.core.findMany(\"plugin_storage\", { where: whereFor(storageInput.collection) }).pipe(\n Effect.map((rows) =>\n sortByScopePrecedence(rows)\n .filter((row) =>\n storageInput.keyPrefix === undefined\n ? true\n : row.key.startsWith(storageInput.keyPrefix),\n )\n .map((row) => pluginStorageEntryFromRow(row)),\n ),\n ),\n put: (storageInput) =>\n Effect.gen(function* () {\n if (!input.scopeIds.includes(storageInput.scope)) {\n return yield* new StorageError({\n message: `Unknown plugin storage target scope: ${storageInput.scope}`,\n cause: undefined,\n });\n }\n const id = pluginStorageId({\n pluginId: input.pluginId,\n collection: storageInput.collection,\n key: storageInput.key,\n });\n const existing = yield* input.core.findFirst(\"plugin_storage\", {\n where: byScopedId(storageInput.scope, id),\n });\n const now = new Date();\n if (existing) {\n yield* input.core.updateMany(\"plugin_storage\", {\n where: byScopedId(storageInput.scope, id),\n set: {\n data: storageInput.data,\n updated_at: now,\n },\n });\n return pluginStorageEntryFromRow({\n ...existing,\n data: storageInput.data,\n updated_at: now,\n });\n }\n const row = yield* input.core.create(\"plugin_storage\", {\n id,\n scope_id: storageInput.scope,\n plugin_id: input.pluginId,\n collection: storageInput.collection,\n key: storageInput.key,\n data: storageInput.data,\n created_at: now,\n updated_at: now,\n });\n return pluginStorageEntryFromRow(row);\n }),\n remove: (storageInput) =>\n input.core.deleteMany(\"plugin_storage\", {\n where: byScopedId(\n storageInput.scope,\n pluginStorageId({\n pluginId: input.pluginId,\n collection: storageInput.collection,\n key: storageInput.key,\n }),\n ),\n }),\n };\n};\n\n// ---------------------------------------------------------------------------\n// Dynamic-row writers — used by ctx.core.sources.register. Static sources\n// never touch these functions.\n// ---------------------------------------------------------------------------\n\n// Upsert shape: delete any existing source + tools + definitions for\n// `input.id` before creating fresh rows. Keeps replayable — boot-time\n// sync from executor.jsonc can call register() on rows that already\n// exist without tripping a UNIQUE constraint.\nconst writeSourceInput = (\n core: ReturnType<typeof makeCoreDb>,\n pluginId: string,\n input: SourceInput,\n): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n yield* deleteSourceById(core, input.id, input.scope);\n\n const now = new Date();\n yield* core.create(\"source\", {\n id: input.id,\n scope_id: input.scope,\n plugin_id: pluginId,\n kind: input.kind,\n name: input.name,\n url: input.url ?? null,\n can_remove: input.canRemove ?? true,\n can_refresh: input.canRefresh ?? false,\n can_edit: input.canEdit ?? false,\n created_at: now,\n updated_at: now,\n });\n\n const toolsById = new Map<string, (typeof input.tools)[number]>();\n for (const tool of input.tools) {\n toolsById.set(`${input.id}.${tool.name}`, tool);\n }\n const tools = [...toolsById.entries()];\n\n if (tools.length > 0) {\n yield* core.createMany(\n \"tool\",\n tools.map(([id, tool]) => ({\n id,\n scope_id: input.scope,\n source_id: input.id,\n plugin_id: pluginId,\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema ?? null,\n output_schema: tool.outputSchema ?? null,\n created_at: now,\n updated_at: now,\n })),\n );\n }\n });\n\n// Delete a source and its tools + definitions at ONE specific scope.\n// The helper pins `scope_id = scopeId` so it never widens into a stack-wide\n// wipe; a bystander scope's rows with a colliding `source_id` must survive.\nconst deleteSourceById = (\n core: ReturnType<typeof makeCoreDb>,\n sourceId: string,\n scopeId: string,\n): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n yield* core.deleteMany(\"tool\", {\n where: (b) => b.and(b(\"source_id\", \"=\", sourceId), b(\"scope_id\", \"=\", scopeId)),\n });\n yield* core.deleteMany(\"definition\", {\n where: (b) => b.and(b(\"source_id\", \"=\", sourceId), b(\"scope_id\", \"=\", scopeId)),\n });\n yield* core.deleteMany(\"source\", {\n where: byScopedId(scopeId, sourceId),\n });\n });\n\nconst writeDefinitions = (\n core: ReturnType<typeof makeCoreDb>,\n pluginId: string,\n input: DefinitionsInput,\n): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n // Pin the delete to `input.scope` so an inner-scope writer cannot remove\n // outer-scope definitions for the same source id.\n yield* core.deleteMany(\"definition\", {\n where: (b) => b.and(b(\"source_id\", \"=\", input.sourceId), b(\"scope_id\", \"=\", input.scope)),\n });\n const entries = Object.entries(input.definitions);\n if (entries.length === 0) return;\n const now = new Date();\n yield* core.createMany(\n \"definition\",\n entries.map(([name, schema]) => ({\n id: `${input.sourceId}.${name}`,\n scope_id: input.scope,\n source_id: input.sourceId,\n plugin_id: pluginId,\n name,\n schema: schema as Record<string, unknown>,\n created_at: now,\n })),\n );\n });\n\n// ---------------------------------------------------------------------------\n// Filtering — shared between dynamic (DB) and static (in-memory) pools\n// so `tools.list({ query, sourceId })` matches across both.\n// ---------------------------------------------------------------------------\n\nconst toolMatchesFilter = (tool: Tool, filter: ToolListFilter): boolean => {\n if (filter.sourceId && tool.sourceId !== filter.sourceId) return false;\n if (filter.query) {\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\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 StaticSources {\n readonly source: StaticSourceDecl;\n readonly pluginId: string;\n}\n\ninterface PluginRuntime {\n readonly plugin: AnyPlugin;\n readonly storage: unknown;\n readonly ctx: PluginCtx<unknown>;\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 { scopes, plugins: userPlugins = defaultPlugins() } = config;\n\n if (scopes.length === 0) {\n return yield* new StorageError({\n message: \"createExecutor requires a non-empty scopes array\",\n cause: undefined,\n });\n }\n\n // Built-in core-tools plugin: contributes scopes.list / secrets.list /\n // secrets.create static tools so agents can manage executor primitives\n // without the host wiring it explicitly. Opt-in via `coreTools` config.\n const plugins: readonly AnyPlugin[] = config.coreTools\n ? ([\n coreToolsPlugin({ webBaseUrl: config.coreTools.webBaseUrl }),\n ...userPlugins,\n ] as readonly AnyPlugin[])\n : (userPlugins as readonly AnyPlugin[]);\n\n const tables = yield* Effect.try({\n try: () => collectTables(plugins),\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 validateExecutorScopePolicyTables(rootDbUntyped.internal.tables);\n },\n catch: (cause) => storageFailureFromUnknown(\"Failed to validate executor tables\", cause),\n });\n const scopeIds = scopes.map((s) => String(s.id));\n const rootDb = withQueryContext(rootDbUntyped, {\n allowedScopeIds: new Set(scopeIds),\n } satisfies ExecutorScopePolicyContext);\n const fuma = makeFumaClient(rootDb);\n const core = makeCoreDb(fuma);\n const 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 staticSources = new Map<string, StaticSources>();\n\n // Per-plugin runtime state.\n const runtimes = new Map<string, PluginRuntime>();\n // Secret providers keyed by `provider.key`.\n const secretProviders = new Map<string, SecretProvider>();\n // Connection providers keyed by `provider.key` — drive the refresh\n // lifecycle for connection-owned tokens.\n const connectionProviders = new Map<string, ConnectionProvider>();\n const resolveConnectionProvider = (key: string): ConnectionProvider | undefined =>\n connectionProviders.get(key);\n // In-flight refresh dedup. `connectionsAccessToken` stamps a\n // `Deferred` here before calling the provider's `refresh`; parallel\n // callers that walk in while a refresh is still running observe\n // the same Deferred and await its resolution instead of hitting\n // the AS a second time. The map is mutated under a semaphore so\n // check-or-register is atomic under fiber interleavings.\n const refreshInFlight = new Map<\n string,\n Deferred.Deferred<\n string,\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure\n >\n >();\n const refreshInFlightLock = Semaphore.makeUnsafe(1);\n const extensions: Record<string, object> = {};\n\n // ------------------------------------------------------------------\n // Secrets facade — fast path is the core `secret` routing table\n // (explicit set()s, keychain entries, etc). Fallback is a walk\n // across providers that implement `list()`, because those are the\n // providers that own their own inventories (1password, file-secrets,\n // workos-vault, env) and enumerate-without-register. Providers\n // without a list() implementation (keychain) never hit the fallback\n // walk because their secrets must be registered through set() to\n // be known at all.\n //\n // Multi-scope behavior: the routing-table lookup pulls every row\n // for this id across the scope stack in a single `IN (...)` query,\n // then sorts innermost-first so a secret registered in a deeper\n // scope shadows one with the same id at a shallower scope (e.g. a\n // user's personal OAuth token wins over an org-wide one). Provider\n // calls stay sequential — scope-partitioning providers (workos-vault,\n // 1password-per-vault) have to be asked per scope because the object\n // name includes the scope — but they're bounded by the number of\n // registered rows for this id, not by scope-stack depth. The\n // provider-enumeration fallback is scope-agnostic: providers like\n // env or 1password don't partition their inventory by executor scope.\n const scopePrecedence = new Map<string, number>();\n scopeIds.forEach((s, i) => scopePrecedence.set(s, i));\n\n // Rank a row by how close its `scope_id` sits to the innermost scope.\n // Rows whose scope isn't in the stack get pushed to the end (they\n // should only arrive through explicit scope predicates, but guarding here\n // means a stray row can't silently win).\n const rowScopeId = (row: { readonly scope_id: unknown }) =>\n typeof row.scope_id === \"string\" ? row.scope_id : null;\n const scopeRank = (row: { readonly scope_id: unknown }) => {\n const scopeId = rowScopeId(row);\n return scopeId === null ? Infinity : (scopePrecedence.get(scopeId) ?? Infinity);\n };\n\n // Pick the innermost-scope row from a scoped Fuma query. Callers that\n // need one logical row query the whole visible scope stack and resolve\n // shadowing here.\n const findInnermost = <T extends { scope_id: unknown }>(rows: readonly T[]): T | null => {\n if (rows.length === 0) return null;\n let winner: T | undefined;\n let best = Infinity;\n for (const row of rows) {\n const rank = scopeRank(row);\n if (rank < best) {\n best = rank;\n winner = row;\n }\n }\n return winner ?? null;\n };\n\n const filterUsagesToScopeStack = (usages: readonly Usage[]): readonly Usage[] =>\n usages.filter((usage) => scopeIds.includes(usage.scopeId));\n\n const secretRowsForId = (id: string): Effect.Effect<readonly SecretRow[], StorageFailure> =>\n core.findMany(\"secret\", { where: scopedWhere(scopeIds, byId(id)) }) as Effect.Effect<\n readonly SecretRow[],\n StorageFailure\n >;\n\n const resolveSecretValueFromRows = (\n id: string,\n rows: readonly SecretRow[],\n ): Effect.Effect<string | null, StorageFailure> =>\n Effect.gen(function* () {\n const ordered = [...rows].sort((a, b) => scopeRank(a) - scopeRank(b));\n for (const row of ordered) {\n const provider = secretProviders.get(row.provider);\n if (!provider) continue;\n const value = yield* provider.get(id, row.scope_id);\n if (value !== null) return value;\n }\n\n // Fallback: ask enumerating providers in registration order. First\n // non-null wins. Providers that throw\n // are treated as \"don't have it\" so one flaky provider can't\n // block resolution via others. Scope-partitioning providers\n // get asked at the innermost scope as a display default — the\n // enumeration fallback doesn't know which scope the value\n // lives in; flat providers ignore the arg.\n const fallbackScope = scopeIds[0]!;\n const candidates = [...secretProviders.values()].filter(\n (p) => p.list && p.allowFallback !== false,\n );\n for (const provider of candidates) {\n const value = yield* provider\n .get(id, fallbackScope)\n .pipe(Effect.catch(() => Effect.succeed(null)));\n if (value !== null) return value;\n }\n return null;\n });\n\n const secretsGet = (\n id: string,\n ): Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure> =>\n Effect.gen(function* () {\n // Connection-owned token rows are internal plumbing; public secret\n // resolution must not expose them even if a token secret id is leaked.\n const rows = yield* secretRowsForId(id);\n const owned = rows.find((row) => row.owned_by_connection_id);\n const ownedByConnectionId = owned?.owned_by_connection_id;\n if (ownedByConnectionId) {\n return yield* new SecretOwnedByConnectionError({\n secretId: SecretId.make(id),\n connectionId: ConnectionId.make(ownedByConnectionId),\n });\n }\n return yield* resolveSecretValueFromRows(id, rows);\n });\n\n const secretsGetResolved = (\n id: string,\n ): Effect.Effect<\n { readonly value: string; readonly scopeId: string | null } | null,\n StorageFailure\n > =>\n Effect.gen(function* () {\n const rows = yield* secretRowsForId(id);\n const ordered = [...rows].sort((a, b) => scopeRank(a) - scopeRank(b));\n for (const row of ordered) {\n if (row.owned_by_connection_id) continue;\n const value = yield* resolveSecretValueAtScope(row, id);\n if (value !== null) return { value, scopeId: row.scope_id };\n }\n const value = yield* resolveSecretValueFromRows(id, []);\n return value === null ? null : { value, scopeId: null };\n });\n\n const resolveSecretValueAtScope = (\n row: SecretRow | null,\n id: string,\n ): Effect.Effect<string | null, StorageFailure> =>\n Effect.gen(function* () {\n if (!row) return null;\n const provider = secretProviders.get(row.provider);\n if (!provider) return null;\n return yield* provider.get(id, row.scope_id);\n });\n\n const secretsGetAtScope = (\n id: string,\n scope: string,\n ): Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure> =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"secret get scope\", scope);\n const row = yield* findSecretRowAtScope({\n secretId: id,\n scopeId: scope,\n });\n if (row?.owned_by_connection_id) {\n return yield* new SecretOwnedByConnectionError({\n secretId: SecretId.make(id),\n connectionId: ConnectionId.make(row.owned_by_connection_id),\n });\n }\n return yield* resolveSecretValueAtScope(row, id);\n });\n\n const connectionSecretGetAtScope = (\n id: string,\n scope: string,\n ): Effect.Effect<string | null, StorageFailure> =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"connection secret get scope\", scope);\n const row = yield* findSecretRowAtScope({\n secretId: id,\n scopeId: scope,\n });\n return yield* resolveSecretValueAtScope(row, id);\n });\n\n const secretRouteHasBackingValue = (row: SecretRow) => {\n const provider = secretProviders.get(row.provider);\n if (!provider?.has) return Effect.succeed(true);\n return provider.has(row.id, row.scope_id).pipe(Effect.catch(() => Effect.succeed(false)));\n };\n\n const secretsSet = (input: SetSecretInput): Effect.Effect<SecretRef, StorageFailure> =>\n Effect.gen(function* () {\n // Validate the write target before we touch the provider.\n if (!scopeIds.includes(input.scope)) {\n return yield* new StorageError({\n message:\n `secrets.set targets scope \"${input.scope}\" which is not ` +\n `in the executor's scope stack [${scopeIds.join(\", \")}].`,\n cause: undefined,\n });\n }\n\n // Pick provider: explicit or first-writable. Misconfiguration\n // (unknown provider, no writable provider, read-only provider)\n // is a host setup bug — surface as `StorageError` so it lands\n // as a captured InternalError(traceId) at the SDK boundary.\n let target: SecretProvider | undefined;\n if (input.provider) {\n target = secretProviders.get(input.provider);\n if (!target) {\n return yield* new StorageError({\n message: `Unknown secret provider: ${input.provider}`,\n cause: undefined,\n });\n }\n } else {\n for (const provider of secretProviders.values()) {\n if (provider.writable && provider.set) {\n target = provider;\n break;\n }\n }\n if (!target) {\n return yield* new StorageError({\n message: \"No writable secret providers registered\",\n cause: undefined,\n });\n }\n }\n if (!target.writable || !target.set) {\n return yield* new StorageError({\n message: `Secret provider \"${target.key}\" is read-only`,\n cause: undefined,\n });\n }\n\n yield* target.set(input.id, input.value, input.scope);\n\n // Upsert metadata row in the core `secret` table at the\n // caller-named scope. Pin the delete to `scope_id = input.scope`\n // so a personal override never deletes an org-wide secret with\n // the same id.\n const now = new Date();\n yield* core.deleteMany(\"secret\", {\n where: byScopedId(input.scope, input.id),\n });\n yield* core.create(\"secret\", {\n id: input.id,\n scope_id: input.scope,\n name: input.name,\n provider: target.key,\n owned_by_connection_id: null,\n created_at: now,\n });\n\n return SecretRef.make({\n id: input.id,\n scopeId: input.scope,\n name: input.name,\n provider: target.key,\n createdAt: now,\n });\n });\n\n // Fan out across every plugin that contributes `usagesForSecret`. Each\n // plugin queries its own normalized columns with explicit scope filters.\n //\n // The display path (`secretsUsages` / `connectionsUsages` from the API)\n // calls `*Lenient`: per-plugin errors become a logWarning so one buggy\n // plugin can't break the UI footer. The delete RESTRICT path\n // (`secretsRemove` / `connectionsRemove`) calls `*Strict`: per-plugin\n // errors fail the whole call so a transient plugin failure can't be\n // mistaken for \"no usages\" and let through a delete that creates\n // dangling refs.\n const secretsUsagesStrict = (id: string): Effect.Effect<readonly Usage[], StorageFailure> =>\n Effect.gen(function* () {\n const secretId = SecretId.make(id);\n const coreUsages = yield* credentialBindingUsagesForSecret(id);\n const perPlugin = yield* Effect.all(\n [...runtimes.values()]\n .filter((r) => r.plugin.usagesForSecret)\n .map((r) =>\n r.plugin.usagesForSecret!({\n ctx: r.ctx,\n args: { secretId },\n }).pipe(\n Effect.mapError(\n (cause): StorageFailure =>\n new StorageError({\n message: `usagesForSecret failed for plugin ${r.plugin.id}`,\n cause,\n }),\n ),\n ),\n ),\n { concurrency: \"unbounded\" },\n );\n return filterUsagesToScopeStack([...coreUsages, ...perPlugin.flat()]);\n });\n\n const secretsUsages = (id: string): Effect.Effect<readonly Usage[], StorageFailure> =>\n Effect.gen(function* () {\n const secretId = SecretId.make(id);\n const coreUsages = yield* credentialBindingUsagesForSecret(id);\n const perPlugin = yield* Effect.all(\n [...runtimes.values()]\n .filter((r) => r.plugin.usagesForSecret)\n .map((r) =>\n r.plugin.usagesForSecret!({\n ctx: r.ctx,\n args: { secretId },\n }).pipe(\n Effect.catchCause((cause: unknown) =>\n Effect.logWarning(`usagesForSecret failed for plugin ${r.plugin.id}`, cause).pipe(\n Effect.as([] as readonly Usage[]),\n ),\n ),\n ),\n ),\n { concurrency: \"unbounded\" },\n );\n return filterUsagesToScopeStack([...coreUsages, ...perPlugin.flat()]);\n });\n\n const connectionsUsagesStrict = (id: string): Effect.Effect<readonly Usage[], StorageFailure> =>\n Effect.gen(function* () {\n const connectionId = ConnectionId.make(id);\n const coreUsages = yield* credentialBindingUsagesForConnection(id);\n const perPlugin = yield* Effect.all(\n [...runtimes.values()]\n .filter((r) => r.plugin.usagesForConnection)\n .map((r) =>\n r.plugin.usagesForConnection!({\n ctx: r.ctx,\n args: { connectionId },\n }).pipe(\n Effect.mapError(\n (cause): StorageFailure =>\n new StorageError({\n message: `usagesForConnection failed for plugin ${r.plugin.id}`,\n cause,\n }),\n ),\n ),\n ),\n { concurrency: \"unbounded\" },\n );\n return filterUsagesToScopeStack([...coreUsages, ...perPlugin.flat()]);\n });\n\n const connectionsUsages = (id: string): Effect.Effect<readonly Usage[], StorageFailure> =>\n Effect.gen(function* () {\n const connectionId = ConnectionId.make(id);\n const coreUsages = yield* credentialBindingUsagesForConnection(id);\n const perPlugin = yield* Effect.all(\n [...runtimes.values()]\n .filter((r) => r.plugin.usagesForConnection)\n .map((r) =>\n r.plugin.usagesForConnection!({\n ctx: r.ctx,\n args: { connectionId },\n }).pipe(\n Effect.catchCause((cause: unknown) =>\n Effect.logWarning(\n `usagesForConnection failed for plugin ${r.plugin.id}`,\n cause,\n ).pipe(Effect.as([] as readonly Usage[])),\n ),\n ),\n ),\n { concurrency: \"unbounded\" },\n );\n return filterUsagesToScopeStack([...coreUsages, ...perPlugin.flat()]);\n });\n\n const secretsRemove = (\n input: RemoveSecretInput,\n ): Effect.Effect<void, SecretOwnedByConnectionError | SecretInUseError | StorageFailure> =>\n Effect.gen(function* () {\n const id = input.id;\n const targetScope = input.targetScope;\n if (!scopeIds.includes(targetScope)) {\n return yield* new StorageError({\n message:\n `secret remove targetScope \"${targetScope}\" is not in the executor's scope stack ` +\n `[${scopeIds.join(\", \")}].`,\n cause: undefined,\n });\n }\n\n // Remove is target-scope aware: drop only the explicitly named\n // scope row. Removing a user-scope override on a secret that also\n // has an org-scope default should reveal the org default, not wipe\n // it. If no core row exists at the target scope, provider cleanup\n // is still scoped to the explicit target for provider-enumerated\n // secrets, but core metadata never falls through to an outer row.\n const rows = yield* core.findMany(\"secret\", {\n where: scopedWhere(scopeIds, byId(id)),\n });\n const target = rows.find((row) => row.scope_id === targetScope);\n // Refuse to delete connection-owned secrets. The connection owns\n // the lifecycle — callers must go through connections.remove.\n if (target && target.owned_by_connection_id) {\n return yield* new SecretOwnedByConnectionError({\n secretId: SecretId.make(id),\n connectionId: ConnectionId.make(target.owned_by_connection_id),\n });\n }\n // RESTRICT: source/binding rows are pinned to the credential row's\n // scope. A same-id row in an outer scope does not satisfy a binding\n // written at the target scope, so the delete gate filters usages to\n // the exact row being removed.\n if (target) {\n const usages = (yield* secretsUsagesStrict(id)).filter(\n (usage) => usage.scopeId === targetScope,\n );\n if (usages.length > 0) {\n return yield* new SecretInUseError({\n secretId: SecretId.make(id),\n usageCount: usages.length,\n });\n }\n }\n\n const deleters = [...secretProviders.values()].filter(\n (p): p is typeof p & { delete: NonNullable<typeof p.delete> } =>\n !!(p.writable && p.delete),\n );\n yield* Effect.all(\n deleters.map((p) => p.delete(id, targetScope)),\n { concurrency: \"unbounded\" },\n );\n\n if (target) {\n yield* core.deleteMany(\"secret\", {\n where: byScopedId(targetScope, id),\n });\n }\n });\n\n // List is a union of two sources of truth:\n //\n // 1. Core `secret` rows — secrets explicitly registered via\n // executor.secrets.set(...). These carry their pinned provider\n // and are authoritative for routing (get() uses them).\n // 2. Each provider's own `list()` — for read-only or\n // already-populated providers (1password, file-secrets,\n // workos-vault, env), the provider enumerates what's actually\n // in its backend. These show up in the list even if the user\n // never called set() through the executor.\n //\n // Dedupe by secret id; core rows win over provider-enumerated ones\n // so that routing information in the core table is authoritative.\n // Providers without a list() method (e.g. keychain) contribute\n // only via the core table path.\n //\n // Multi-scope: core rows from any scope in the stack show up, each\n // tagged with its own `scope_id`. When the same id appears in multiple scopes, the\n // innermost wins — same rule as `secretsGet`. Provider-enumerated\n // entries don't know what scope they belong to and are attributed\n // to the innermost scope as a display default.\n const secretsList = (): Effect.Effect<readonly SecretRef[], StorageFailure> =>\n Effect.gen(function* () {\n const byId = new Map<string, SecretRef>();\n\n // Core routing rows first. Resolve collisions using the caller's\n // precedence order (innermost first). Rows owned by a connection\n // are filtered out — the user sees the Connection entry, not its\n // backing token secrets. Their ids go in a deny-set so provider\n // `list()` results for the same id can't leak them back in below.\n const allRows = yield* core.findMany(\"secret\", { where: scopedWhere(scopeIds) });\n const rows = allRows.filter((r) => !r.owned_by_connection_id);\n const pick = (row: (typeof rows)[number]) => {\n const existing = byId.get(row.id);\n const incomingScope = row.scope_id;\n const incomingRank = scopeRank(row);\n if (existing) {\n const existingRank = scopePrecedence.get(existing.scopeId) ?? Infinity;\n if (existingRank <= incomingRank) return;\n }\n byId.set(\n row.id,\n SecretRef.make({\n id: SecretId.make(row.id),\n scopeId: ScopeId.make(incomingScope),\n name: row.name,\n provider: row.provider,\n createdAt: row.created_at instanceof Date ? row.created_at : new Date(row.created_at),\n }),\n );\n };\n for (const row of rows) {\n const hasBackingValue = yield* secretRouteHasBackingValue(row);\n if (hasBackingValue) pick(row);\n }\n\n // Don't let provider-enumerated entries resurrect ids that\n // belong to a connection-owned core row.\n const connectionOwnedIds = new Set(\n allRows.filter((r) => r.owned_by_connection_id).map((r) => r.id),\n );\n // Attribute provider-listed entries to the innermost scope as\n // a display default — providers like 1password and env don't\n // partition their inventory by executor scope.\n const innermostScopeId = scopeIds[0];\n if (innermostScopeId !== undefined) {\n for (const [key, provider] of secretProviders) {\n if (!provider.list) continue;\n const entries = yield* provider\n .list()\n .pipe(Effect.catch(() => Effect.succeed([] as const)));\n for (const entry of entries) {\n if (byId.has(entry.id)) continue;\n if (connectionOwnedIds.has(entry.id)) continue;\n byId.set(\n entry.id,\n SecretRef.make({\n id: SecretId.make(entry.id),\n scopeId: ScopeId.make(innermostScopeId),\n name: entry.name,\n provider: key,\n createdAt: new Date(0),\n }),\n );\n }\n }\n }\n\n return Array.from(byId.values());\n });\n\n const secretsListAll = (): Effect.Effect<readonly SecretRef[], StorageFailure> =>\n Effect.gen(function* () {\n const allRows = yield* core.findMany(\"secret\", { where: scopedWhere(scopeIds) });\n const coreIds = new Set<string>();\n const refs: SecretRef[] = [];\n\n for (const row of allRows) {\n coreIds.add(row.id);\n if (row.owned_by_connection_id) continue;\n const hasBackingValue = yield* secretRouteHasBackingValue(row);\n if (!hasBackingValue) continue;\n refs.push(\n SecretRef.make({\n id: SecretId.make(row.id),\n scopeId: ScopeId.make(row.scope_id),\n name: row.name,\n provider: row.provider,\n createdAt: row.created_at instanceof Date ? row.created_at : new Date(row.created_at),\n }),\n );\n }\n\n return refs.sort((a, b) => {\n const rank =\n (scopePrecedence.get(a.scopeId) ?? Infinity) -\n (scopePrecedence.get(b.scopeId) ?? Infinity);\n if (rank !== 0) return rank;\n const name = a.name.localeCompare(b.name);\n return name === 0 ? String(a.id).localeCompare(String(b.id)) : name;\n });\n });\n\n // Same union shape as secretsList but projected to the leaner\n // SecretListEntry shape that plugins get via ctx.secrets.list().\n const secretsListForCtx = () =>\n Effect.gen(function* () {\n const list = yield* secretsList();\n return list.map((ref) => ({\n id: String(ref.id),\n scopeId: ref.scopeId,\n name: ref.name,\n provider: ref.provider,\n }));\n });\n\n // ------------------------------------------------------------------\n // Connections facade — sign-in state as a first-class primitive.\n // Connection rows own one or more backing `secret` rows via\n // `secret.owned_by_connection_id`; the SDK orchestrates refresh via\n // the registered provider keyed by `connection.provider`.\n // ------------------------------------------------------------------\n\n // Refresh skew: treat the access token as \"about to expire\" when\n // we're within this many ms of the expiry the AS declared.\n // Matches the value the old per-plugin refresh code used, so\n // behavior under the new SDK orchestration stays identical.\n const CONNECTION_REFRESH_SKEW_MS = 60_000;\n\n const rowToConnection = (row: ConnectionRow): ConnectionRef =>\n ConnectionRef.make({\n id: ConnectionId.make(row.id),\n scopeId: ScopeId.make(row.scope_id),\n provider: row.provider,\n identityLabel: row.identity_label ?? null,\n accessTokenSecretId: SecretId.make(row.access_token_secret_id),\n refreshTokenSecretId:\n row.refresh_token_secret_id != null ? SecretId.make(row.refresh_token_secret_id) : null,\n expiresAt: row.expires_at != null ? Number(row.expires_at) : null,\n oauthScope: row.scope ?? null,\n providerState: Option.getOrNull(decodeProviderState(decodeJsonColumn(row.provider_state))),\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\n const findInnermostConnectionRow = (\n id: string,\n ): Effect.Effect<ConnectionRow | null, StorageFailure> =>\n Effect.gen(function* () {\n const rows = yield* core.findMany(\"connection\", {\n where: scopedWhere(scopeIds, byId(id)),\n });\n return findInnermost(rows as readonly ConnectionRow[]);\n });\n\n const connectionsGet = (id: string): Effect.Effect<ConnectionRef | null, StorageFailure> =>\n Effect.gen(function* () {\n const row = yield* findInnermostConnectionRow(id);\n return row ? rowToConnection(row) : null;\n });\n\n const connectionsGetAtScope = (\n id: string,\n scope: string,\n ): Effect.Effect<ConnectionRef | null, StorageFailure> =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"connection get scope\", scope);\n const row = yield* findConnectionRowAtScope({\n connectionId: id,\n scopeId: scope,\n });\n return row ? rowToConnection(row) : null;\n });\n\n const connectionsList = (): Effect.Effect<readonly ConnectionRef[], StorageFailure> =>\n Effect.gen(function* () {\n const rows = yield* core.findMany(\"connection\", { where: scopedWhere(scopeIds) });\n // Dedup by id, innermost scope wins — same rule as sources/tools.\n const byId = new Map<string, ConnectionRow>();\n const byIdRank = new Map<string, number>();\n for (const row of rows as readonly ConnectionRow[]) {\n const rank = scopeRank(row);\n const existing = byIdRank.get(row.id);\n if (existing === undefined || rank < existing) {\n byId.set(row.id, row);\n byIdRank.set(row.id, rank);\n }\n }\n return [...byId.values()].map(rowToConnection);\n });\n\n // Write a secret value through a specific provider, bypassing the\n // bare-secrets ownership check so the SDK can stamp\n // `owned_by_connection_id` atomically alongside a connection row.\n const writeOwnedSecret = (params: {\n id: string;\n scope: string;\n name: string;\n value: string;\n provider: string;\n ownedByConnectionId: string;\n }): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n const target = secretProviders.get(params.provider);\n if (!target) {\n return yield* new StorageError({\n message: `Unknown secret provider: ${params.provider}`,\n cause: undefined,\n });\n }\n if (!target.writable || !target.set) {\n return yield* new StorageError({\n message: `Secret provider \"${target.key}\" is read-only`,\n cause: undefined,\n });\n }\n yield* target.set(params.id, params.value, params.scope);\n\n const now = new Date();\n yield* core.deleteMany(\"secret\", {\n where: byScopedId(params.scope, params.id),\n });\n yield* core.create(\"secret\", {\n id: params.id,\n scope_id: params.scope,\n name: params.name,\n provider: target.key,\n owned_by_connection_id: params.ownedByConnectionId,\n created_at: now,\n });\n });\n\n const pickWritableProvider = (\n requested?: string,\n ): Effect.Effect<SecretProvider, StorageFailure> =>\n Effect.gen(function* () {\n if (requested) {\n const p = secretProviders.get(requested);\n if (!p) {\n return yield* new StorageError({\n message: `Unknown secret provider: ${requested}`,\n cause: undefined,\n });\n }\n return p;\n }\n for (const p of secretProviders.values()) {\n if (p.writable && p.set) return p;\n }\n return yield* new StorageError({\n message: \"No writable secret providers registered\",\n cause: undefined,\n });\n });\n\n const connectionsCreate = (\n input: CreateConnectionInput,\n ): Effect.Effect<ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure> =>\n Effect.gen(function* () {\n if (!scopeIds.some((scopeId) => scopeId === input.scope)) {\n return yield* new StorageError({\n message:\n `connections.create targets scope \"${input.scope}\" which is not ` +\n `in the executor's scope stack [${scopeIds.join(\", \")}].`,\n cause: undefined,\n });\n }\n if (!resolveConnectionProvider(input.provider)) {\n return yield* new ConnectionProviderNotRegisteredError({\n provider: input.provider,\n connectionId: input.id,\n });\n }\n\n const writable = yield* pickWritableProvider();\n const now = new Date();\n\n return yield* transaction(\n Effect.gen(function* () {\n // Drop any existing connection row at this scope first so a\n // re-auth replaces cleanly. Owned-secret rows for the old\n // connection are removed by the cascade below (we delete\n // both old + new token secret ids explicitly).\n yield* core.deleteMany(\"connection\", {\n where: byScopedId(input.scope, input.id),\n });\n\n yield* writeOwnedSecret({\n id: input.accessToken.secretId,\n scope: input.scope,\n name: input.accessToken.name,\n value: input.accessToken.value,\n provider: writable.key,\n ownedByConnectionId: input.id,\n });\n if (input.refreshToken) {\n yield* writeOwnedSecret({\n id: input.refreshToken.secretId,\n scope: input.scope,\n name: input.refreshToken.name,\n value: input.refreshToken.value,\n provider: writable.key,\n ownedByConnectionId: input.id,\n });\n }\n\n yield* core.create(\"connection\", {\n id: input.id,\n scope_id: input.scope,\n provider: input.provider,\n identity_label: input.identityLabel ?? null,\n access_token_secret_id: input.accessToken.secretId,\n refresh_token_secret_id: input.refreshToken?.secretId ?? null,\n expires_at: input.expiresAt ?? null,\n scope: input.oauthScope ?? null,\n provider_state: input.providerState ?? null,\n created_at: now,\n updated_at: now,\n });\n\n return ConnectionRef.make({\n id: input.id,\n scopeId: input.scope,\n provider: input.provider,\n identityLabel: input.identityLabel,\n accessTokenSecretId: input.accessToken.secretId,\n refreshTokenSecretId: input.refreshToken?.secretId ?? null,\n expiresAt: input.expiresAt,\n oauthScope: input.oauthScope,\n providerState: input.providerState,\n createdAt: now,\n updatedAt: now,\n });\n }),\n );\n });\n\n // Write new token material into the existing secret rows and bump\n // the connection row's expiry / scope / providerState. Never\n // mutates `access_token_secret_id` or `refresh_token_secret_id` —\n // those stay pinned so consumers that stashed them in source\n // configs still resolve.\n const connectionsUpdateTokensForRow = (\n input: UpdateConnectionTokensInput,\n row: ConnectionRow,\n ): Effect.Effect<ConnectionRef, ConnectionNotFoundError | StorageFailure> =>\n Effect.gen(function* () {\n const writable = yield* pickWritableProvider();\n const accessName = `Connection ${input.id} access token`;\n const refreshName = `Connection ${input.id} refresh token`;\n\n return yield* transaction(\n Effect.gen(function* () {\n yield* writeOwnedSecret({\n id: row.access_token_secret_id,\n scope: row.scope_id,\n name: accessName,\n value: input.accessToken,\n provider: writable.key,\n ownedByConnectionId: row.id,\n });\n const rotatedRefresh = input.refreshToken ?? undefined;\n if (rotatedRefresh && row.refresh_token_secret_id) {\n yield* writeOwnedSecret({\n id: row.refresh_token_secret_id,\n scope: row.scope_id,\n name: refreshName,\n value: rotatedRefresh,\n provider: writable.key,\n ownedByConnectionId: row.id,\n });\n }\n const now = new Date();\n const patch: Record<string, unknown> = { updated_at: now };\n if (input.expiresAt !== undefined) patch.expires_at = input.expiresAt ?? null;\n if (input.oauthScope !== undefined) patch.scope = input.oauthScope ?? null;\n if (input.providerState !== undefined)\n patch.provider_state = input.providerState ?? null;\n if (input.identityLabel !== undefined)\n patch.identity_label = input.identityLabel ?? null;\n yield* core.updateMany(\"connection\", {\n where: byScopedId(row.scope_id, row.id),\n set: patch,\n });\n const updated = yield* findConnectionRowAtScope({\n connectionId: row.id,\n scopeId: row.scope_id,\n });\n if (!updated) {\n return yield* new ConnectionNotFoundError({\n connectionId: input.id,\n });\n }\n return rowToConnection(updated);\n }),\n );\n });\n\n const connectionsUpdateTokens = (\n input: UpdateConnectionTokensInput,\n ): Effect.Effect<ConnectionRef, ConnectionNotFoundError | StorageFailure> =>\n Effect.gen(function* () {\n const row = yield* findInnermostConnectionRow(input.id);\n if (!row) {\n return yield* new ConnectionNotFoundError({ connectionId: input.id });\n }\n return yield* connectionsUpdateTokensForRow(input, row);\n });\n\n const connectionsSetIdentityLabel = (\n id: string,\n label: string | null,\n ): Effect.Effect<void, ConnectionNotFoundError | StorageFailure> =>\n Effect.gen(function* () {\n const row = yield* findInnermostConnectionRow(id);\n if (!row) {\n return yield* new ConnectionNotFoundError({\n connectionId: ConnectionId.make(id),\n });\n }\n yield* core.updateMany(\"connection\", {\n where: byScopedId(row.scope_id, id),\n set: {\n identity_label: label ?? null,\n updated_at: new Date(),\n },\n });\n });\n\n const connectionsRemove = (\n input: RemoveConnectionInput,\n ): Effect.Effect<void, ConnectionInUseError | StorageFailure> =>\n Effect.gen(function* () {\n const id = input.id;\n const targetScope = input.targetScope;\n yield* assertScopeInStack(\"connection remove targetScope\", targetScope);\n const allRows = yield* core.findMany(\"connection\", {\n where: scopedWhere(scopeIds, byId(id)),\n });\n const row =\n (allRows as readonly ConnectionRow[]).find(\n (candidate) => candidate.scope_id === targetScope,\n ) ?? null;\n if (!row) return;\n const usages = (yield* connectionsUsagesStrict(id)).filter(\n (usage) => usage.scopeId === targetScope,\n );\n if (usages.length > 0) {\n return yield* new ConnectionInUseError({\n connectionId: ConnectionId.make(id),\n usageCount: usages.length,\n });\n }\n const scope = targetScope;\n yield* transaction(\n Effect.gen(function* () {\n // Find every owned secret at this scope and drop through\n // its provider + the core row. We look up by\n // `owned_by_connection_id` rather than just the two ids on\n // the connection row so any accidentally-orphaned siblings\n // get cleaned up too.\n const owned = yield* core.findMany(\"secret\", {\n where: (b) => b.and(b(\"owned_by_connection_id\", \"=\", id), b(\"scope_id\", \"=\", scope)),\n });\n const deleters = [...secretProviders.values()].filter(\n (p): p is typeof p & { delete: NonNullable<typeof p.delete> } =>\n !!(p.writable && p.delete),\n );\n for (const secret of owned) {\n yield* Effect.all(\n deleters.map((p) =>\n p\n .delete(secret.id, scope)\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(\n `Failed to delete connection-owned secret from provider ${p.key}`,\n cause,\n ).pipe(Effect.as(false)),\n ),\n ),\n ),\n { concurrency: \"unbounded\" },\n );\n }\n yield* core.deleteMany(\"secret\", {\n where: (b) => b.and(b(\"owned_by_connection_id\", \"=\", id), b(\"scope_id\", \"=\", scope)),\n });\n yield* core.deleteMany(\"connection\", {\n where: byScopedId(scope, id),\n });\n }),\n );\n });\n\n // Typed error union that `connectionsAccessToken` and every helper\n // that participates in a refresh returns. Pulled out into a type\n // alias because it has to match the Deferred's channel exactly —\n // otherwise concurrent waiters and the leader diverge on the error\n // type.\n type AccessTokenError =\n | ConnectionNotFoundError\n | ConnectionProviderNotRegisteredError\n | ConnectionRefreshNotSupportedError\n | ConnectionReauthRequiredError\n | ConnectionRefreshError\n | StorageFailure;\n\n // The actual work of a single refresh cycle, factored out so the\n // concurrency gate (`connectionsAccessToken`) stays readable. Runs\n // for the fiber that wins the `refreshInFlight` race.\n const performRefresh = (ref: ConnectionRef): Effect.Effect<string, AccessTokenError> =>\n Effect.gen(function* () {\n const provider = resolveConnectionProvider(ref.provider);\n if (!provider) {\n return yield* new ConnectionProviderNotRegisteredError({\n provider: ref.provider,\n connectionId: ref.id,\n });\n }\n if (!provider.refresh) {\n return yield* new ConnectionRefreshNotSupportedError({\n connectionId: ref.id,\n provider: ref.provider,\n });\n }\n\n const refreshTokenValue = ref.refreshTokenSecretId\n ? yield* connectionSecretGetAtScope(ref.refreshTokenSecretId, ref.scopeId)\n : null;\n\n // RFC 6749 §5.2 `invalid_grant` (and anything else the\n // provider tags with `reauthRequired`) is terminal — the\n // stored refresh token can't recover. Translate into the\n // caller-visible \"re-authenticate\" error so the UI can\n // prompt sign-in instead of silently retrying.\n const rawResult: Result.Result<ConnectionRefreshResult, ConnectionRefreshError> =\n yield* Effect.result(\n provider.refresh({\n connectionId: ref.id,\n scopeId: ref.scopeId,\n identityLabel: ref.identityLabel,\n refreshToken: refreshTokenValue,\n providerState: ref.providerState,\n oauthScope: ref.oauthScope,\n }),\n );\n if (Result.isFailure(rawResult)) {\n const err = rawResult.failure;\n if (err.reauthRequired) {\n return yield* new ConnectionReauthRequiredError({\n connectionId: err.connectionId,\n provider: ref.provider,\n // oxlint-disable-next-line executor/no-unknown-error-message -- typed: ConnectionRefreshError.message is provider-facing domain data, not an unknown caught error\n message: err[\"message\"],\n });\n }\n return yield* err;\n }\n const result = rawResult.success;\n\n const row = yield* findConnectionRowAtScope({\n connectionId: ref.id,\n scopeId: ref.scopeId,\n });\n if (!row) {\n return yield* new ConnectionNotFoundError({\n connectionId: ref.id,\n });\n }\n yield* connectionsUpdateTokensForRow(\n {\n id: ref.id,\n accessToken: result.accessToken,\n refreshToken: result.refreshToken,\n expiresAt: result.expiresAt,\n oauthScope: result.oauthScope,\n providerState: result.providerState,\n } as UpdateConnectionTokensInput,\n row,\n );\n\n return result.accessToken;\n });\n\n // accessToken(id) — the single surface plugins use at invoke time.\n // Resolves the backing secret, checks expiry, calls the provider's\n // refresh handler if we're inside the skew window. New tokens are\n // written back through the same provider and the connection row is\n // patched with the new expiry.\n //\n // Concurrent invokes on an expired token all share one refresh.\n // The fiber that wins the `refreshInFlightLock` race registers a\n // Deferred and performs the refresh; every other concurrent caller\n // observes the Deferred and awaits its completion. The Deferred is\n // pulled out of the map before the refresh result resolves so\n // later invokes don't reuse a completed slot.\n const connectionsAccessTokenForRow = (\n row: ConnectionRow,\n ): Effect.Effect<string, AccessTokenError> =>\n Effect.gen(function* () {\n const ref = rowToConnection(row);\n const now = Date.now();\n const needsRefresh =\n ref.expiresAt !== null && ref.expiresAt - CONNECTION_REFRESH_SKEW_MS <= now;\n\n if (!needsRefresh) {\n const current = yield* connectionSecretGetAtScope(ref.accessTokenSecretId, ref.scopeId);\n if (current !== null) return current;\n // Fall through to refresh if the stored token vanished — a\n // genuinely-missing secret with no way to refresh is a\n // hard-failure, same behavior as if `expires_at` had passed.\n }\n\n // Concurrency gate. `action` either returns the fresh access\n // token (this fiber did the refresh) or the already-running\n // Deferred that another fiber stamped into the map (this fiber\n // piggybacks on their refresh).\n const refreshKey = `${ref.scopeId}\\u0000${ref.id}`;\n const action = yield* refreshInFlightLock.withPermits(1)(\n Effect.gen(function* () {\n const existing = refreshInFlight.get(refreshKey);\n if (existing) {\n return {\n kind: \"await\" as const,\n deferred: existing,\n };\n }\n const deferred = yield* Deferred.make<string, AccessTokenError>();\n refreshInFlight.set(refreshKey, deferred);\n return { kind: \"lead\" as const, deferred };\n }),\n );\n\n if (action.kind === \"await\") {\n return yield* Deferred.await(action.deferred);\n }\n\n // Leader path: run the refresh, pipe the outcome into the\n // Deferred (so waiters wake up), and then clear the map slot\n // regardless of success or failure. Completing before delete\n // ensures a caller that arrives during cleanup can still observe\n // the settled leader result instead of starting a second refresh.\n return yield* performRefresh(ref).pipe(\n Effect.onExit((exit) =>\n refreshInFlightLock.withPermits(1)(\n Effect.gen(function* () {\n yield* Deferred.done(action.deferred, exit);\n refreshInFlight.delete(refreshKey);\n }),\n ),\n ),\n );\n });\n\n const connectionsAccessToken = (id: string): Effect.Effect<string, AccessTokenError> =>\n Effect.gen(function* () {\n const row = yield* findInnermostConnectionRow(id);\n if (!row) {\n return yield* new ConnectionNotFoundError({\n connectionId: ConnectionId.make(id),\n });\n }\n return yield* connectionsAccessTokenForRow(row);\n });\n\n const connectionsAccessTokenAtScope = (\n id: string,\n scope: string,\n ): Effect.Effect<string, AccessTokenError> =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"connection accessToken scope\", scope);\n const row = yield* findConnectionRowAtScope({\n connectionId: id,\n scopeId: scope,\n });\n if (!row) {\n return yield* new ConnectionNotFoundError({\n connectionId: ConnectionId.make(id),\n });\n }\n return yield* connectionsAccessTokenForRow(row);\n });\n\n const connectionsListForCtx = () => connectionsList();\n\n const scopeListLabel = () => `[${scopeIds.join(\", \")}]`;\n\n const assertScopeInStack = (\n label: string,\n scopeId: string,\n ): Effect.Effect<void, StorageError> =>\n scopeIds.includes(scopeId)\n ? Effect.void\n : Effect.fail(\n new StorageError({\n message: `${label} \"${scopeId}\" is not in the executor's scope stack ${scopeListLabel()}.`,\n cause: undefined,\n }),\n );\n\n const findSourceRowAtScope = (input: {\n readonly pluginId: string;\n readonly sourceId: string;\n readonly sourceScope: string;\n }): Effect.Effect<SourceRow | null, StorageFailure> =>\n Effect.gen(function* () {\n if (!scopeIds.includes(input.sourceScope)) return null;\n return yield* core.findFirst(\"source\", {\n where: (b) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"id\", \"=\", input.sourceId),\n b(\"scope_id\", \"=\", input.sourceScope),\n ),\n });\n });\n\n const findSourceOwnerRowAtScope = (input: {\n readonly sourceId: string;\n readonly sourceScope: string;\n }): Effect.Effect<SourceRow | null, StorageFailure> =>\n Effect.gen(function* () {\n if (!scopeIds.includes(input.sourceScope)) return null;\n return yield* core.findFirst(\"source\", {\n where: byScopedId(input.sourceScope, input.sourceId),\n });\n });\n\n const findSecretRowAtScope = (input: {\n readonly secretId: string;\n readonly scopeId: string;\n }): Effect.Effect<SecretRow | null, StorageFailure> =>\n Effect.gen(function* () {\n if (!scopeIds.includes(input.scopeId)) return null;\n return yield* core.findFirst(\"secret\", {\n where: byScopedId(input.scopeId, input.secretId),\n });\n });\n\n const findConnectionRowAtScope = (input: {\n readonly connectionId: string;\n readonly scopeId: string;\n }): Effect.Effect<ConnectionRow | null, StorageFailure> =>\n Effect.gen(function* () {\n if (!scopeIds.includes(input.scopeId)) return null;\n return yield* core.findFirst(\"connection\", {\n where: byScopedId(input.scopeId, input.connectionId),\n });\n });\n\n const credentialBindingRowsForSource = (\n input: CredentialBindingSourceInput,\n ): Effect.Effect<readonly CredentialBindingRow[], StorageFailure> =>\n scopeIds.includes(input.sourceScope)\n ? (core\n .findMany(\"credential_binding\", {\n where: scopedWhere(scopeIds, (b) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"source_id\", \"=\", input.sourceId),\n b(\"source_scope_id\", \"=\", input.sourceScope),\n ),\n ),\n })\n .pipe(\n Effect.map((rows) => {\n const sourceSourceRank = scopePrecedence.get(input.sourceScope) ?? Infinity;\n return (rows as readonly CredentialBindingRow[]).filter(\n (row) => scopeRank(row) <= sourceSourceRank,\n );\n }),\n ) as Effect.Effect<readonly CredentialBindingRow[], StorageFailure>)\n : Effect.succeed([]);\n\n const credentialBindingRowsForSlot = (\n input: CredentialBindingSlotInput,\n ): Effect.Effect<readonly CredentialBindingRow[], StorageFailure> =>\n scopeIds.includes(input.sourceScope)\n ? (core\n .findMany(\"credential_binding\", {\n where: scopedWhere(scopeIds, (b) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"source_id\", \"=\", input.sourceId),\n b(\"source_scope_id\", \"=\", input.sourceScope),\n b(\"slot_key\", \"=\", input.slotKey),\n ),\n ),\n })\n .pipe(\n Effect.map((rows) => {\n const sourceSourceRank = scopePrecedence.get(input.sourceScope) ?? Infinity;\n return (rows as readonly CredentialBindingRow[]).filter(\n (row) => scopeRank(row) <= sourceSourceRank,\n );\n }),\n ) as Effect.Effect<readonly CredentialBindingRow[], StorageFailure>)\n : Effect.succeed([]);\n\n const assertCredentialBindingTargetNotOuter = (input: {\n readonly label: string;\n readonly targetScope: string;\n readonly sourceScope: string;\n readonly sourceId: string;\n }): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n const sourceSourceRank = scopePrecedence.get(input.sourceScope) ?? Infinity;\n const targetRank = scopePrecedence.get(input.targetScope) ?? Infinity;\n if (targetRank > sourceSourceRank) {\n return yield* new StorageError({\n message:\n `${input.label} for source \"${input.sourceId}\" cannot target outer scope ` +\n `\"${input.targetScope}\" because the source lives at scope \"${input.sourceScope}\".`,\n cause: undefined,\n });\n }\n });\n\n const credentialBindingListForSource = (input: CredentialBindingSourceInput) =>\n Effect.gen(function* () {\n const rows = yield* credentialBindingRowsForSource(input);\n return rows\n .slice()\n .sort((a, b) => {\n const slot = a.slot_key.localeCompare(b.slot_key);\n return slot === 0 ? scopeRank(a) - scopeRank(b) : slot;\n })\n .map(credentialBindingRowToRef);\n });\n\n const credentialBindingSet = (input: SetPluginCredentialBindingInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"credential binding targetScope\", input.targetScope);\n yield* assertScopeInStack(\"credential binding sourceScope\", input.sourceScope);\n yield* assertCredentialBindingTargetNotOuter({\n label: \"credential binding\",\n targetScope: input.targetScope,\n sourceScope: input.sourceScope,\n sourceId: input.sourceId,\n });\n\n const source = yield* findSourceRowAtScope({\n pluginId: input.pluginId,\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n });\n if (!source) {\n return yield* new StorageError({\n message:\n `Cannot set credential binding for source \"${input.sourceId}\" ` +\n `at scope \"${input.sourceScope}\": source is not visible.`,\n cause: undefined,\n });\n }\n\n if (input.value.kind === \"secret\") {\n const secretId = input.value.secretId;\n const secretScope = input.value.secretScopeId ?? input.targetScope;\n yield* assertScopeInStack(\"credential binding secretScope\", secretScope);\n if (scopePrecedence.get(secretScope)! < scopePrecedence.get(input.targetScope)!) {\n return yield* new StorageError({\n message:\n `Cannot bind secret \"${secretId}\" from scope \"${secretScope}\" ` +\n `to target scope \"${input.targetScope}\": shared bindings cannot reference inner-scope secrets.`,\n cause: undefined,\n });\n }\n const secret = yield* findSecretRowAtScope({\n secretId,\n scopeId: secretScope,\n });\n if (!secret) {\n // No core routing row at this scope yet. Read-only providers\n // (1password, env, …) own items that never get a row via\n // `secrets.set()`, so a config-sync referencing one of those\n // ids by value otherwise fails here. Walk providers that can\n // enumerate, and if any owns the id, materialize a routing row\n // pointing at that provider so resolution finds it.\n let materialized = false;\n for (const [key, provider] of secretProviders) {\n let name: string | undefined;\n if (provider.list) {\n const entries = yield* provider\n .list()\n .pipe(Effect.catch(() => Effect.succeed([] as const)));\n const found = entries.find((e) => e.id === secretId);\n if (found) name = found.name;\n }\n if (name === undefined) {\n // Provider didn't enumerate the id (slow list(), failed list,\n // or no list() at all). Probe with get() — cheap for most\n // backends — and use the id as the display name.\n const value = yield* provider\n .get(secretId, secretScope)\n .pipe(Effect.catch(() => Effect.succeed(null as string | null)));\n if (value !== null) name = secretId;\n }\n if (name === undefined) continue;\n const now = new Date();\n yield* core.create(\"secret\", {\n id: secretId,\n scope_id: secretScope,\n name,\n provider: key,\n owned_by_connection_id: null,\n created_at: now,\n });\n materialized = true;\n break;\n }\n if (!materialized) {\n const providerKeys = [...secretProviders.keys()];\n return yield* new StorageError({\n message:\n `Cannot bind secret \"${secretId}\" at scope \"${secretScope}\": ` +\n `no registered secret provider has an item with this id ` +\n `(checked: ${providerKeys.join(\", \") || \"none\"}). ` +\n `If this id points to a 1Password item, the item may have been deleted, ` +\n `renamed, or live in a different vault than the one configured for this scope.`,\n cause: undefined,\n });\n }\n }\n }\n\n if (input.value.kind === \"connection\") {\n const connection = yield* findConnectionRowAtScope({\n connectionId: input.value.connectionId,\n scopeId: input.targetScope,\n });\n if (!connection) {\n return yield* new StorageError({\n message:\n `Cannot bind connection \"${input.value.connectionId}\" at scope \"${input.targetScope}\": ` +\n `the connection must be owned by the same scope as the binding.`,\n cause: undefined,\n });\n }\n }\n\n const id = credentialBindingId(input);\n const now = new Date();\n yield* core.deleteMany(\"credential_binding\", {\n where: (b) =>\n b.and(\n b(\"scope_id\", \"=\", input.targetScope),\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"source_id\", \"=\", input.sourceId),\n b(\"source_scope_id\", \"=\", input.sourceScope),\n b(\"slot_key\", \"=\", input.slotKey),\n ),\n });\n yield* core.create(\"credential_binding\", {\n id,\n scope_id: input.targetScope,\n plugin_id: input.pluginId,\n source_id: input.sourceId,\n source_scope_id: input.sourceScope,\n slot_key: input.slotKey,\n kind: input.value.kind,\n text_value: input.value.kind === \"text\" ? input.value.text : null,\n secret_id: input.value.kind === \"secret\" ? input.value.secretId : null,\n secret_scope_id:\n input.value.kind === \"secret\" ? (input.value.secretScopeId ?? input.targetScope) : null,\n connection_id: input.value.kind === \"connection\" ? input.value.connectionId : null,\n created_at: now,\n updated_at: now,\n });\n return credentialBindingRowToRef({\n id,\n scope_id: input.targetScope,\n plugin_id: input.pluginId,\n source_id: input.sourceId,\n source_scope_id: input.sourceScope,\n slot_key: input.slotKey,\n kind: input.value.kind,\n text_value: input.value.kind === \"text\" ? input.value.text : undefined,\n secret_id: input.value.kind === \"secret\" ? input.value.secretId : undefined,\n secret_scope_id:\n input.value.kind === \"secret\"\n ? (input.value.secretScopeId ?? input.targetScope)\n : undefined,\n connection_id: input.value.kind === \"connection\" ? input.value.connectionId : undefined,\n created_at: now,\n updated_at: now,\n } as CredentialBindingRow);\n });\n\n const credentialBindingRemove = (input: RemoveCredentialBindingInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"credential binding targetScope\", input.targetScope);\n yield* assertScopeInStack(\"credential binding sourceScope\", input.sourceScope);\n yield* assertCredentialBindingTargetNotOuter({\n label: \"credential binding removal\",\n targetScope: input.targetScope,\n sourceScope: input.sourceScope,\n sourceId: input.sourceId,\n });\n\n const source = yield* findSourceRowAtScope({\n pluginId: input.pluginId,\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n });\n if (!source) {\n return yield* new StorageError({\n message:\n `Cannot remove credential binding for source \"${input.sourceId}\" ` +\n `at scope \"${input.sourceScope}\": source is not visible.`,\n cause: undefined,\n });\n }\n\n yield* core.deleteMany(\"credential_binding\", {\n where: (b) =>\n b.and(\n b(\"scope_id\", \"=\", input.targetScope),\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"source_id\", \"=\", input.sourceId),\n b(\"source_scope_id\", \"=\", input.sourceScope),\n b(\"slot_key\", \"=\", input.slotKey),\n ),\n });\n });\n\n const credentialBindingReplaceForSource = (input: ReplaceCredentialBindingsInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"credential binding targetScope\", input.targetScope);\n yield* assertScopeInStack(\"credential binding sourceScope\", input.sourceScope);\n yield* assertCredentialBindingTargetNotOuter({\n label: \"credential binding replacement\",\n targetScope: input.targetScope,\n sourceScope: input.sourceScope,\n sourceId: input.sourceId,\n });\n\n const source = yield* findSourceRowAtScope({\n pluginId: input.pluginId,\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n });\n if (!source) {\n return yield* new StorageError({\n message:\n `Cannot replace credential bindings for source \"${input.sourceId}\" ` +\n `at scope \"${input.sourceScope}\": source is not visible.`,\n cause: undefined,\n });\n }\n\n const nextSlots = new Set(input.bindings.map((binding) => binding.slotKey));\n const existing = yield* core.findMany(\"credential_binding\", {\n where: (b) =>\n b.and(\n b(\"scope_id\", \"=\", input.targetScope),\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"source_id\", \"=\", input.sourceId),\n b(\"source_scope_id\", \"=\", input.sourceScope),\n ),\n });\n for (const row of existing as readonly CredentialBindingRow[]) {\n const shouldOwnSlot = input.slotPrefixes.some((prefix) =>\n row.slot_key.startsWith(prefix),\n );\n if (shouldOwnSlot && !nextSlots.has(row.slot_key)) {\n yield* credentialBindingRemove({\n targetScope: input.targetScope,\n pluginId: input.pluginId,\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n slotKey: row.slot_key,\n });\n }\n }\n\n const refs: CredentialBindingRef[] = [];\n for (const binding of input.bindings) {\n refs.push(\n yield* credentialBindingSet({\n targetScope: input.targetScope,\n pluginId: input.pluginId,\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n slotKey: binding.slotKey,\n value: binding.value,\n }),\n );\n }\n return refs;\n });\n\n const credentialBindingRemoveForSource = (input: CredentialBindingSourceInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"credential binding sourceScope\", input.sourceScope);\n const source = yield* findSourceRowAtScope(input);\n if (!source) return;\n\n // Source-owner cleanup is intentionally broader than a normal scoped\n // binding delete. Removing a shared source must detach all credential\n // rows for that source identity, including user-owned bindings that\n // are not in the source owner's current stack.\n yield* core.deleteMany(\"credential_binding\", {\n where: (b) =>\n b.and(\n b(\"plugin_id\", \"=\", input.pluginId),\n b(\"source_id\", \"=\", input.sourceId),\n b(\"source_scope_id\", \"=\", input.sourceScope),\n ),\n });\n });\n\n const credentialBindingResolutionStatus = (\n row: CredentialBindingRow,\n ): Effect.Effect<\"resolved\" | \"missing\", StorageFailure> =>\n Effect.gen(function* () {\n if (row.kind === \"text\") return typeof row.text_value === \"string\" ? \"resolved\" : \"missing\";\n if (row.kind === \"secret\") {\n if (!row.secret_id) return \"missing\";\n const secret = yield* findSecretRowAtScope({\n secretId: row.secret_id,\n scopeId: row.secret_scope_id ?? row.scope_id,\n });\n if (!secret) return \"missing\";\n return (yield* secretRouteHasBackingValue(secret)) ? \"resolved\" : \"missing\";\n }\n if (row.kind === \"connection\") {\n if (!row.connection_id) return \"missing\";\n const connection = yield* findConnectionRowAtScope({\n connectionId: row.connection_id,\n scopeId: row.scope_id,\n });\n return connection ? \"resolved\" : \"missing\";\n }\n return \"missing\";\n });\n\n const credentialBindingResolveBinding = (input: CredentialBindingSlotInput) =>\n Effect.gen(function* () {\n const rows = yield* credentialBindingRowsForSlot(input);\n const row = findInnermost(rows);\n return row ? credentialBindingRowToRef(row) : null;\n });\n\n const credentialBindingResolve = (input: CredentialBindingSlotInput) =>\n Effect.gen(function* () {\n const rows = yield* credentialBindingRowsForSlot(input);\n const row = findInnermost(rows);\n if (!row) {\n return ResolvedCredentialSlot.make({\n pluginId: input.pluginId,\n sourceId: input.sourceId,\n sourceScopeId: input.sourceScope,\n slotKey: input.slotKey,\n bindingScopeId: null,\n kind: null,\n status: \"missing\" as const,\n });\n }\n return ResolvedCredentialSlot.make({\n pluginId: input.pluginId,\n sourceId: input.sourceId,\n sourceScopeId: input.sourceScope,\n slotKey: input.slotKey,\n bindingScopeId: ScopeId.make(row.scope_id),\n kind:\n row.kind === \"text\" || row.kind === \"secret\" || row.kind === \"connection\"\n ? row.kind\n : null,\n status: yield* credentialBindingResolutionStatus(row),\n });\n });\n\n const sourceNamesForCredentialBindings = (\n rows: readonly CredentialBindingRow[],\n ): Effect.Effect<Map<string, string>, StorageFailure> =>\n Effect.gen(function* () {\n const sourceIds = [...new Set(rows.map((row) => row.source_id))];\n if (sourceIds.length === 0) return new Map<string, string>();\n const sourceRows = yield* core.findMany(\"source\", {\n where: scopedWhere(scopeIds, (b) => b(\"id\", \"in\", sourceIds)),\n });\n return new Map(\n sourceRows.map((row) => [`${row.scope_id}\\u0000${row.id}`, row.name] as const),\n );\n });\n\n const credentialBindingRowsToUsages = (\n rows: readonly CredentialBindingRow[],\n ): Effect.Effect<readonly Usage[], StorageFailure> =>\n Effect.gen(function* () {\n const names = yield* sourceNamesForCredentialBindings(rows);\n return rows.map((row) =>\n Usage.make({\n pluginId: row.plugin_id,\n scopeId: ScopeId.make(\n row.kind === \"secret\" ? (row.secret_scope_id ?? row.scope_id) : row.scope_id,\n ),\n ownerKind: \"credential-binding\",\n ownerId: row.source_id,\n ownerName: names.get(`${row.source_scope_id}\\u0000${row.source_id}`) ?? null,\n slot: row.slot_key,\n }),\n );\n });\n\n const credentialBindingUsagesForSecret = (\n id: string,\n ): Effect.Effect<readonly Usage[], StorageFailure> =>\n Effect.gen(function* () {\n const rows = yield* core.findMany(\"credential_binding\", {\n where: scopedWhere(scopeIds, (b) => b(\"secret_id\", \"=\", id)),\n });\n return yield* credentialBindingRowsToUsages(rows as readonly CredentialBindingRow[]);\n });\n\n const credentialBindingUsagesForConnection = (\n id: string,\n ): Effect.Effect<readonly Usage[], StorageFailure> =>\n Effect.gen(function* () {\n const rows = yield* core.findMany(\"credential_binding\", {\n where: scopedWhere(scopeIds, (b) => b(\"connection_id\", \"=\", id)),\n });\n return yield* credentialBindingRowsToUsages(rows as readonly CredentialBindingRow[]);\n });\n\n const credentialBindings: CredentialBindingsFacade = {\n listForSource: credentialBindingListForSource,\n resolveBinding: credentialBindingResolveBinding,\n resolve: credentialBindingResolve,\n set: credentialBindingSet,\n remove: credentialBindingRemove,\n replaceForSource: credentialBindingReplaceForSource,\n removeForSource: credentialBindingRemoveForSource,\n usagesForSecret: credentialBindingUsagesForSecret,\n usagesForConnection: credentialBindingUsagesForConnection,\n };\n\n const credentialBindingInputForSource = (input: SourceCredentialBindingSourceInput) =>\n Effect.gen(function* () {\n const source = yield* findSourceOwnerRowAtScope({\n sourceId: input.source.id,\n sourceScope: input.source.scope,\n });\n return source\n ? ({\n pluginId: source.plugin_id,\n sourceId: input.source.id,\n sourceScope: input.source.scope,\n } satisfies CredentialBindingSourceInput)\n : null;\n });\n\n const sourceBindingList = (input: SourceCredentialBindingSourceInput) =>\n Effect.gen(function* () {\n const bindingInput = yield* credentialBindingInputForSource(input);\n return bindingInput ? yield* credentialBindingListForSource(bindingInput) : [];\n });\n\n const sourceBindingResolve = (input: SourceCredentialBindingSlotInput) =>\n Effect.gen(function* () {\n const bindingInput = yield* credentialBindingInputForSource(input);\n return bindingInput\n ? yield* credentialBindingResolveBinding({\n ...bindingInput,\n slotKey: input.slotKey,\n })\n : null;\n });\n\n const sourceBindingSet = (input: SetSourceCredentialBindingInput) =>\n Effect.gen(function* () {\n const bindingInput = yield* credentialBindingInputForSource(input);\n if (!bindingInput) {\n return yield* new StorageError({\n message:\n `Cannot set credential binding for source \"${input.source.id}\" ` +\n `at scope \"${input.source.scope}\": source is not visible.`,\n cause: undefined,\n });\n }\n return yield* credentialBindingSet({\n ...bindingInput,\n targetScope: input.scope,\n slotKey: input.slotKey,\n value: input.value,\n });\n });\n\n const sourceBindingRemove = (input: RemoveSourceCredentialBindingInput) =>\n Effect.gen(function* () {\n const bindingInput = yield* credentialBindingInputForSource(input);\n if (!bindingInput) {\n return yield* new StorageError({\n message:\n `Cannot remove credential binding for source \"${input.source.id}\" ` +\n `at scope \"${input.source.scope}\": source is not visible.`,\n cause: undefined,\n });\n }\n yield* credentialBindingRemove({\n ...bindingInput,\n targetScope: input.scope,\n slotKey: input.slotKey,\n });\n });\n\n const sourceBindingReplace = (input: ReplaceSourceCredentialBindingsInput) =>\n Effect.gen(function* () {\n const bindingInput = yield* credentialBindingInputForSource(input);\n if (!bindingInput) {\n return yield* new StorageError({\n message:\n `Cannot replace credential bindings for source \"${input.source.id}\" ` +\n `at scope \"${input.source.scope}\": source is not visible.`,\n cause: undefined,\n });\n }\n return yield* credentialBindingReplaceForSource({\n ...bindingInput,\n targetScope: input.scope,\n slotPrefixes: input.slotPrefixes,\n bindings: input.bindings,\n });\n });\n\n const sourceConfigure = (input: {\n readonly source: {\n readonly id: string;\n readonly scope: ScopeId | string;\n };\n readonly scope: ScopeId | string;\n readonly type?: string;\n readonly config: unknown;\n }) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"source configure source scope\", input.source.scope);\n yield* assertScopeInStack(\"source configure target scope\", input.scope);\n\n const source = yield* core.findFirst(\"source\", {\n where: byScopedId(input.source.scope, input.source.id),\n });\n if (!source) {\n return yield* new StorageError({\n message:\n `Cannot configure source \"${input.source.id}\" at scope ` +\n `\"${input.source.scope}\": source is not visible.`,\n cause: undefined,\n });\n }\n\n const runtime = runtimes.get(source.plugin_id);\n const configure = runtime?.plugin.sourceConfigure;\n if (!runtime || !configure) {\n return yield* new StorageError({\n message: `Plugin \"${source.plugin_id}\" does not support source.configure.`,\n cause: undefined,\n });\n }\n if (input.type !== undefined && input.type !== configure.type) {\n return yield* new StorageError({\n message:\n `Source configure type mismatch for plugin \"${source.plugin_id}\": ` +\n `expected \"${configure.type}\", received \"${input.type}\".`,\n cause: undefined,\n });\n }\n\n const decoded = yield* decodeConfigureInput(configure.schema, input.config).pipe(\n Effect.mapError((cause) =>\n storageFailureFromUnknown(\n `Invalid source.configure payload for ${configure.type}`,\n cause,\n ),\n ),\n );\n\n return yield* configure\n .configure({\n ctx: runtime.ctx,\n sourceId: input.source.id,\n sourceScope: input.source.scope,\n targetScope: input.scope,\n config: decoded,\n })\n .pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(source.plugin_id, \"sourceConfigure\", cause),\n ),\n );\n });\n\n const oauthBundle = makeOAuth2Service({\n fuma,\n secretsGet: (id) =>\n secretsGet(id).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () => Effect.succeed(null)),\n ),\n secretsGetResolved: (id) => secretsGetResolved(id),\n secretsGetAtScope: (id, scope) =>\n secretsGetAtScope(id, scope).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () => Effect.succeed(null)),\n ),\n secretsSet: (input) => secretsSet(input),\n connectionsCreate: (input) => connectionsCreate(input),\n httpClientLayer: config.httpClientLayer,\n endpointUrlPolicy: config.oauthEndpointUrlPolicy,\n });\n connectionProviders.set(oauthBundle.connectionProvider.key, oauthBundle.connectionProvider);\n\n // ------------------------------------------------------------------\n // Plugin wiring — build ctx, run extension, populate static pools,\n // register secret providers. No adapter reads here.\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 pluginFuma = makeFumaClient(\n rootDb,\n plugin.schema ? { tables: new Set(Object.keys(plugin.schema)) } : { tables: new Set() },\n );\n const pluginStorage = makePluginStorageFacade({\n core,\n pluginId: plugin.id,\n scopeIds,\n });\n const storageDeps: StorageDeps = {\n scopes,\n fuma: pluginFuma,\n // Blob keys are namespaced by `<scope>/<plugin>` so two tenants\n // sharing a backing BlobStore can't collide or leak on the\n // same `(plugin, key)` pair. The store's `get`/`has` walk the\n // scope stack (innermost first); `put`/`delete` require the\n // plugin to name a target scope explicitly.\n blobs: pluginBlobStore(blobs, scopeIds, plugin.id),\n pluginStorage,\n };\n const storage = plugin.storage(storageDeps);\n\n const ctx: PluginCtx<unknown> = {\n scopes,\n storage,\n pluginStorage,\n httpClientLayer: config.httpClientLayer ?? FetchHttpClient.layer,\n core: {\n sources: {\n register: (input: SourceInput) =>\n Effect.gen(function* () {\n // Guard: reject a dynamic source whose id collides with\n // a static source id, or any of whose would-be tool ids\n // collide with a static tool id. Tool ids are\n // `${source_id}.${tool.name}` — static and dynamic\n // share the same string space. Fails as `StorageError`\n // so the HTTP edge surfaces it as `InternalError(traceId)`.\n if (staticSources.has(input.id)) {\n return yield* new StorageError({\n message: `Source id \"${input.id}\" collides with a static source`,\n cause: undefined,\n });\n }\n for (const tool of input.tools) {\n const fqid = `${input.id}.${tool.name}`;\n if (staticTools.has(fqid)) {\n return yield* new StorageError({\n message: `Tool id \"${fqid}\" collides with a static tool`,\n cause: undefined,\n });\n }\n }\n yield* transaction(writeSourceInput(core, plugin.id, input));\n }),\n unregister: (input: RemoveSourceInput) =>\n // `unregister` is scoped to a caller-named source row. The\n // plugin already knows which source owner it is updating,\n // so the core path must not infer an innermost target.\n transaction(\n Effect.gen(function* () {\n yield* assertScopeInStack(\"source unregister targetScope\", input.targetScope);\n const row = yield* core.findFirst(\"source\", {\n where: byScopedId(input.targetScope, input.id),\n });\n if (!row) return;\n yield* deleteSourceById(core, input.id, input.targetScope);\n }),\n ),\n update: (input) =>\n core\n .updateMany(\"source\", {\n where: byScopedId(input.scope, input.id),\n set: {\n ...(input.name !== undefined ? { name: input.name } : {}),\n ...(input.url !== undefined ? { url: input.url ?? null } : {}),\n updated_at: new Date(),\n },\n })\n .pipe(Effect.asVoid),\n list: () => listSources(),\n remove: (input) => removeSource(input),\n refresh: (input) => refreshSource(input),\n detect: (url) => detectSource(url),\n configure: (input) => sourceConfigure(input),\n listBindings: (input) => sourceBindingList(input),\n resolveBinding: (input) => sourceBindingResolve(input),\n setBinding: (input) => sourceBindingSet(input),\n removeBinding: (input) => sourceBindingRemove(input),\n configureSchemas: () =>\n Array.from(runtimes.values())\n .map(({ plugin }) =>\n plugin.sourceConfigure\n ? sourceConfigureSchemaView(plugin.id, plugin.sourceConfigure)\n : undefined,\n )\n .filter(Predicate.isNotUndefined),\n presets: () =>\n Array.from(runtimes.values()).flatMap(({ plugin }) =>\n (plugin.sourcePresets ?? []).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 definitions: {\n register: (input: DefinitionsInput) =>\n transaction(writeDefinitions(core, plugin.id, input)),\n },\n },\n secrets: {\n get: (id) => secretsGet(id),\n getAtScope: (id, scope) => secretsGetAtScope(id, scope),\n list: () => secretsListForCtx(),\n status: (id) => secretsStatus(id),\n usages: (id) => secretsUsages(id),\n providers: () =>\n Effect.sync(() => Array.from(secretProviders.keys()) as readonly string[]),\n set: (input) => secretsSet(input),\n remove: (input) => secretsRemove(input),\n },\n connections: {\n get: (id) => connectionsGet(id),\n getAtScope: (id, scope) => connectionsGetAtScope(id, scope),\n list: () => connectionsListForCtx(),\n usages: (id) => connectionsUsages(id),\n providers: () =>\n Effect.sync(() => Array.from(connectionProviders.keys()) as readonly string[]),\n create: (input) => connectionsCreate(input),\n updateTokens: (input) => connectionsUpdateTokens(input),\n setIdentityLabel: (id, label) => connectionsSetIdentityLabel(id, label),\n accessToken: (id) => connectionsAccessToken(id),\n accessTokenAtScope: (id, scope) => connectionsAccessTokenAtScope(id, scope),\n remove: (input) => connectionsRemove(input),\n },\n credentialBindings,\n oauth: oauthBundle.service,\n transaction: <A, E>(effect: Effect.Effect<A, E>) => transaction(effect),\n };\n\n // Build extension FIRST so it's available as `self` when resolving\n // staticSources. Field ordering in the plugin spec matters — TS\n // infers TExtension from `extension`'s return type, then NoInfer\n // locks `self` to that inferred type on `staticSources`.\n const extension: object = plugin.extension ? plugin.extension(ctx) : {};\n if (plugin.extension) {\n extensions[plugin.id] = extension;\n }\n\n // Resolve static declarations to the in-memory pools. NO DB WRITES.\n // Plugin-owned executor tools are intentionally mounted under the\n // single `executor` namespace so source inventory is about configured\n // integrations, not plugin management surfaces. The static source id\n // becomes the path segment, so plugins can expose TypeScript-friendly\n // management namespaces without changing their persisted plugin ids:\n // openapi.addSource -> executor.openapi.addSource\n // googleDiscovery.addSource -> executor.googleDiscovery.addSource\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\n if (mountUnderExecutor) {\n if (!staticSources.has(EXECUTOR_SOURCE_ID)) {\n staticSources.set(EXECUTOR_SOURCE_ID, {\n source: EXECUTOR_SOURCE,\n pluginId: EXECUTOR_SOURCE_ID,\n });\n }\n } else {\n if (staticSources.has(source.id)) {\n return yield* new StorageError({\n message: `Duplicate static source id: ${source.id} (plugin ${plugin.id})`,\n cause: undefined,\n });\n }\n staticSources.set(source.id, { source, pluginId: plugin.id });\n }\n\n for (const tool of source.tools) {\n const mountedTool = mountUnderExecutor\n ? {\n ...tool,\n name: `${source.id}.${tool.name}`,\n }\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.secretProviders) {\n const raw =\n typeof plugin.secretProviders === \"function\"\n ? plugin.secretProviders(ctx)\n : plugin.secretProviders;\n const providers = Effect.isEffect(raw)\n ? yield* raw.pipe(\n Effect.mapError((cause) => pluginStorageFailure(plugin.id, \"secretProviders\", cause)),\n )\n : raw;\n for (const provider of providers) {\n if (secretProviders.has(provider.key)) {\n return yield* new StorageError({\n message: `Duplicate secret provider key: ${provider.key} (from plugin ${plugin.id})`,\n cause: undefined,\n });\n }\n secretProviders.set(provider.key, provider);\n }\n }\n\n if (plugin.connectionProviders) {\n const raw =\n typeof plugin.connectionProviders === \"function\"\n ? plugin.connectionProviders(ctx)\n : plugin.connectionProviders;\n const providers = Effect.isEffect(raw)\n ? yield* raw.pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(plugin.id, \"connectionProviders\", cause),\n ),\n )\n : raw;\n for (const provider of providers) {\n if (connectionProviders.has(provider.key)) {\n return yield* new StorageError({\n message: `Duplicate connection provider key: ${provider.key} (from plugin ${plugin.id})`,\n cause: undefined,\n });\n }\n connectionProviders.set(provider.key, provider);\n }\n }\n }\n\n // ------------------------------------------------------------------\n // Executor surface\n // ------------------------------------------------------------------\n const listSources = () =>\n Effect.gen(function* () {\n const dynamic = yield* core.findMany(\"source\", { where: scopedWhere(scopeIds) });\n // Dedup by id with innermost scope winning. Without this, a user\n // who shadowed an org-wide source at their inner scope would see\n // two rows — their override and the outer default — which is\n // inconsistent with how `secrets.list` and every other list\n // surface dedup shadowed entries.\n const byId = new Map<string, (typeof dynamic)[number]>();\n const byIdRank = new Map<string, number>();\n for (const row of dynamic) {\n const rank = scopeRank(row);\n const existing = byIdRank.get(row.id);\n if (existing === undefined || rank < existing) {\n byId.set(row.id, row);\n byIdRank.set(row.id, rank);\n }\n }\n const dynamicDeduped = [...byId.values()];\n const staticList: Source[] = [];\n for (const { source, pluginId } of staticSources.values()) {\n staticList.push(staticDeclToSource(source, pluginId));\n }\n const merged = [...staticList, ...dynamicDeduped.map(rowToSource)];\n yield* Effect.annotateCurrentSpan({\n \"executor.sources.static_count\": staticList.length,\n \"executor.sources.dynamic_count\": dynamicDeduped.length,\n });\n return merged;\n }).pipe(Effect.withSpan(\"executor.sources.list\"));\n\n // Bulk-resolve annotations across a set of dynamic tool rows by\n // grouping them under their owning plugin's resolveAnnotations\n // callback. One plugin call per (plugin_id, source_id) pair, not\n // per row. Plugins without a resolver simply contribute no\n // annotations for their rows.\n const resolveAnnotationsFor = (rows: readonly ToolRow[]) =>\n Effect.gen(function* () {\n const result = new Map<string, ToolAnnotations>();\n if (rows.length === 0) return result;\n\n // Group by (plugin_id, source_id)\n const groups = new Map<string, ToolRow[]>();\n for (const row of rows) {\n const key = `${row.plugin_id}\\u0000${row.source_id}`;\n const bucket = groups.get(key);\n if (bucket) bucket.push(row);\n else groups.set(key, [row]);\n }\n\n // Each (plugin_id, source_id) group is an independent DB read,\n // so fan them out concurrently. Yielding them serially stacks\n // ~200-300ms storage round-trips end-to-end and dominates the\n // `executor.tools.list.annotations` span.\n const maps = yield* Effect.forEach(\n [...groups].slice(0, MAX_ANNOTATION_GROUPS),\n ([key, groupRows]) =>\n Effect.gen(function* () {\n const [pluginId, sourceId] = key.split(\"\\u0000\") as [string, string];\n const runtime = runtimes.get(pluginId);\n if (!runtime?.plugin.resolveAnnotations) return undefined;\n return yield* runtime.plugin\n .resolveAnnotations({\n ctx: runtime.ctx,\n sourceId,\n toolRows: groupRows,\n })\n .pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(pluginId, \"resolveAnnotations\", cause),\n ),\n );\n }),\n { concurrency: \"unbounded\" },\n );\n for (const map of maps) {\n if (!map) continue;\n for (const [toolId, annotations] of Object.entries(map)) {\n result.set(toolId, annotations);\n }\n }\n return result;\n });\n\n const listTools = (filter?: ToolListFilter) =>\n Effect.gen(function* () {\n const dynamic = yield* core.findMany(\"tool\", {\n where: scopedWhere(\n scopeIds,\n filter?.sourceId ? (b) => b(\"source_id\", \"=\", filter.sourceId!) : undefined,\n ),\n });\n // Dedup by tool id, innermost scope winning — same reason as\n // `listSources` above: a shadowed id must surface as one entry\n // (the inner one), not two.\n const byId = new Map<string, (typeof dynamic)[number]>();\n const byIdRank = new Map<string, number>();\n for (const row of dynamic) {\n const rank = scopeRank(row);\n const existing = byIdRank.get(row.id);\n if (existing === undefined || rank < existing) {\n byId.set(row.id, row);\n byIdRank.set(row.id, rank);\n }\n }\n const dynamicDeduped = [...byId.values()];\n const annotations =\n filter?.includeAnnotations === false\n ? new Map<string, ToolAnnotations>()\n : yield* resolveAnnotationsFor(dynamicDeduped).pipe(\n Effect.withSpan(\"executor.tools.list.annotations\"),\n );\n\n const out: Tool[] = [];\n // Static tools — annotations from the declaration, not a resolver.\n for (const entry of staticTools.values()) {\n out.push(staticDeclToTool(entry.source, entry.tool, entry.pluginId));\n }\n for (const row of dynamicDeduped) {\n out.push(rowToTool(row, annotations.get(row.id)));\n }\n const filtered = filter ? out.filter((t) => toolMatchesFilter(t, filter)) : out;\n\n // Drop tools blocked by user policy unless the caller explicitly\n // asked to see them (the settings UI does, agent surfaces don't).\n // One findMany covers the entire scope stack; resolution per\n // tool is in-memory.\n let result = filtered;\n let blockedCount = 0;\n if (filter?.includeBlocked !== true) {\n const policies = yield* loadAllPolicies();\n if (policies.length > 0) {\n const kept: Tool[] = [];\n for (const tool of filtered) {\n const match = resolveToolPolicy(tool.id, policies, scopeRank);\n if (match?.action === \"block\") {\n blockedCount++;\n continue;\n }\n kept.push(tool);\n }\n result = kept;\n }\n }\n\n yield* Effect.annotateCurrentSpan({\n \"executor.tools.static_count\": staticTools.size,\n \"executor.tools.dynamic_count\": dynamicDeduped.length,\n \"executor.tools.result_count\": result.length,\n \"executor.tools.blocked_count\": blockedCount,\n });\n return result;\n }).pipe(Effect.withSpan(\"executor.tools.list\"));\n\n // Load all definitions for a single source as a plain map. Defs\n // for the same name can exist at multiple scopes (an admin registers\n // a default, a user overrides one entry with a tighter schema) —\n // dedup by name keeping the innermost-scope row.\n const loadDefinitionsForSource = (sourceId: string) =>\n Effect.gen(function* () {\n const defRows = yield* core.findMany(\"definition\", {\n where: scopedWhere(scopeIds, (b) => b(\"source_id\", \"=\", sourceId)),\n });\n const winners = new Map<string, { row: (typeof defRows)[number]; rank: number }>();\n for (const row of defRows) {\n const rank = scopeRank(row);\n const existing = winners.get(row.name);\n if (!existing || rank < existing.rank) {\n winners.set(row.name, { row, rank });\n }\n }\n const out: Record<string, unknown> = {};\n for (const [name, { row }] of winners) out[name] = row.schema;\n return out;\n });\n\n // Render the ToolSchema view for a tool. Raw JSON schema roots stay small,\n // while source-level definitions are returned once for the UI schema\n // explorer and passed separately to the TypeScript preview compiler.\n const buildToolSchemaView = (opts: {\n toolId: string;\n name?: string;\n description?: string;\n sourceId: string | undefined;\n rawInput: unknown;\n rawOutput: unknown;\n }) =>\n Effect.gen(function* () {\n const defs: Record<string, unknown> = opts.sourceId\n ? yield* loadDefinitionsForSource(opts.sourceId).pipe(\n Effect.withSpan(\"executor.tool.schema.load_defs\"),\n )\n : {};\n\n const sourceDefsMap = new Map<string, unknown>(Object.entries(defs));\n const schemaDefinitions = collectReferencedDefinitions(\n [opts.rawInput, opts.rawOutput],\n sourceDefsMap,\n );\n const schemaDefsMap = new Map<string, unknown>(Object.entries(schemaDefinitions));\n const preview: ToolTypeScriptPreview = yield* Effect.promise(() =>\n buildToolTypeScriptPreview({\n inputSchema: opts.rawInput,\n outputSchema: opts.rawOutput,\n defs: schemaDefsMap,\n }),\n ).pipe(\n Effect.withSpan(\"schema.compile.preview\", {\n attributes: {\n \"schema.kind\": \"tool.preview\",\n \"schema.has_input\": opts.rawInput !== undefined,\n \"schema.has_output\": opts.rawOutput !== undefined,\n \"schema.def_count\": schemaDefsMap.size,\n \"schema.source_def_count\": sourceDefsMap.size,\n },\n }),\n );\n\n return ToolSchema.make({\n id: ToolId.make(opts.toolId),\n name: opts.name,\n description: opts.description,\n inputSchema: opts.rawInput,\n outputSchema: opts.rawOutput,\n schemaDefinitions:\n Object.keys(schemaDefinitions).length > 0 ? schemaDefinitions : undefined,\n inputTypeScript: preview.inputTypeScript ?? undefined,\n outputTypeScript: preview.outputTypeScript ?? undefined,\n typeScriptDefinitions: preview.typeScriptDefinitions ?? undefined,\n });\n });\n\n const toolSchema = (toolId: string) =>\n Effect.gen(function* () {\n // Static pool first — static tools have no source in the DB so\n // no `$defs` attach; just wrap the declared schemas.\n const staticEntry = staticTools.get(toolId);\n if (staticEntry) {\n yield* Effect.annotateCurrentSpan({\n \"executor.tool.dispatch_path\": \"static\",\n \"executor.source_id\": staticEntry.source.id,\n \"executor.source_kind\": staticEntry.source.kind,\n });\n return yield* buildToolSchemaView({\n toolId,\n name: staticEntry.tool.name,\n description: staticEntry.tool.description,\n sourceId: undefined,\n rawInput: toToolJsonSchema(staticEntry.tool.inputSchema),\n rawOutput: toToolJsonSchema(staticEntry.tool.outputSchema, \"output\"),\n });\n }\n // Innermost-wins lookup across every visible scope.\n const rows = yield* core\n .findMany(\"tool\", {\n where: scopedWhere(scopeIds, byId(toolId)),\n })\n .pipe(Effect.withSpan(\"executor.tool.resolve\"));\n const row = findInnermost(rows);\n if (!row) return null;\n yield* Effect.annotateCurrentSpan({\n \"executor.tool.dispatch_path\": \"dynamic\",\n \"executor.source_id\": row.source_id,\n \"executor.plugin_id\": row.plugin_id,\n });\n return yield* buildToolSchemaView({\n toolId,\n name: row.name,\n description: row.description,\n sourceId: row.source_id,\n rawInput: decodeJsonColumn(row.input_schema),\n rawOutput: decodeJsonColumn(row.output_schema),\n });\n }).pipe(\n Effect.withSpan(\"executor.tool.schema\", {\n attributes: { \"mcp.tool.name\": toolId },\n }),\n );\n\n // Bulk definitions accessor — every source's $defs, grouped by\n // source id. One query against the definition table, plus an\n // in-memory group-by with innermost-scope dedup: if the same\n // (source_id, name) pair exists at multiple scopes, the inner\n // scope's schema wins.\n const toolsDefinitions = () =>\n Effect.gen(function* () {\n const rows = yield* core.findMany(\"definition\", { where: scopedWhere(scopeIds) });\n const winners = new Map<string, { row: (typeof rows)[number]; rank: number }>();\n for (const row of rows) {\n const key = `${row.source_id}\\u0000${row.name}`;\n const rank = scopeRank(row);\n const existing = winners.get(key);\n if (!existing || rank < existing.rank) {\n winners.set(key, { row, rank });\n }\n }\n const out: Record<string, Record<string, unknown>> = {};\n for (const { row } of winners.values()) {\n let bucket = out[row.source_id];\n if (!bucket) {\n bucket = {};\n out[row.source_id] = bucket;\n }\n bucket[row.name] = row.schema;\n }\n return out;\n });\n\n const defaultElicitationHandler = resolveElicitationHandler(config.onElicitation);\n const pickHandler = (options: InvokeOptions | undefined): ElicitationHandler =>\n options?.onElicitation\n ? resolveElicitationHandler(options.onElicitation)\n : defaultElicitationHandler;\n\n const buildElicit = (toolId: string, args: unknown, handler: ElicitationHandler): Elicit => {\n return (request: ElicitationRequest) =>\n Effect.gen(function* () {\n const tid = ToolId.make(toolId);\n const response: ElicitationResponse = yield* handler({\n toolId: tid,\n args,\n request,\n });\n if (response.action !== \"accept\") {\n return yield* new ElicitationDeclinedError({\n toolId: tid,\n action: response.action,\n });\n }\n return response;\n });\n };\n\n // ------------------------------------------------------------------\n // Tool policies — user-authored overrides of the plugin-derived\n // approval annotations. Resolution walks the scope-stacked policy\n // table with first-match-wins ordering (innermost scope first, then\n // `position` ascending). The result either short-circuits invoke\n // (`block`), forces approval (`require_approval`), skips approval\n // (`approve`), or returns `undefined` so the plugin annotation is\n // used as today.\n // ------------------------------------------------------------------\n\n const loadAllPolicies = () => core.findMany(\"tool_policy\", { where: scopedWhere(scopeIds) });\n\n const resolveToolPolicyForId = (toolId: string) =>\n Effect.gen(function* () {\n const policies = yield* loadAllPolicies();\n return resolveToolPolicy(toolId, policies, scopeRank);\n });\n\n const enforceApproval = (\n annotations: ToolAnnotations | undefined,\n toolId: string,\n args: unknown,\n policy: PolicyMatch | undefined,\n handler: ElicitationHandler,\n ) =>\n Effect.gen(function* () {\n // approve → never prompt regardless of plugin annotation.\n if (policy?.action === \"approve\") return;\n\n // require_approval → always prompt. If the plugin already had a\n // description, prefer it; otherwise show the matched pattern so\n // the user can see *why* the prompt fired.\n const policyForcesApproval = policy?.action === \"require_approval\";\n if (!policyForcesApproval && !annotations?.requiresApproval) return;\n\n const tid = ToolId.make(toolId);\n const message = annotations?.approvalDescription\n ? annotations.approvalDescription\n : policyForcesApproval && policy\n ? `Approve ${toolId}? (matched policy: ${policy.pattern})`\n : `Approve ${toolId}?`;\n const request = FormElicitation.make({\n message: `${message}\\n\\nArguments:\\n${approvalArgumentPreview(args)}`,\n requestedSchema: {\n type: \"object\",\n properties: {},\n },\n });\n const response = yield* handler({ toolId: tid, args, request });\n if (response.action !== \"accept\") {\n return yield* new ElicitationDeclinedError({\n toolId: tid,\n action: response.action,\n });\n }\n });\n\n const invokeTool = (toolId: string, args: unknown, options?: InvokeOptions) => {\n const handler = pickHandler(options);\n return Effect.gen(function* () {\n const formatInvocationCauseMessage = (cause: unknown): string => {\n // oxlint-disable-next-line executor/no-instanceof-error, executor/no-unknown-error-message -- boundary: preserve public invoke error message wrapping for unknown plugin failures\n return cause instanceof Error ? cause.message : String(cause);\n };\n const wrapInvocationError =\n (resolvedToolId: string) =>\n <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, ToolInvocationError> =>\n effect.pipe(\n Effect.mapError(\n (cause) =>\n new ToolInvocationError({\n toolId: ToolId.make(resolvedToolId),\n message: formatInvocationCauseMessage(cause),\n cause,\n }),\n ),\n );\n\n // Static path — O(1) map lookup, no DB hit.\n const staticEntry = staticTools.get(toolId);\n if (staticEntry) {\n // Resolve the user-authored policy before static plugin code\n // runs. Dynamic tools resolve policy after canonicalizing the\n // stored tool id so casing aliases cannot bypass rules.\n const policy = yield* resolveToolPolicyForId(toolId).pipe(\n Effect.withSpan(\"executor.tool.resolve_policy\"),\n );\n if (policy?.action === \"block\") {\n return yield* new ToolBlockedError({\n toolId: ToolId.make(toolId),\n pattern: policy.pattern,\n });\n }\n yield* Effect.annotateCurrentSpan({\n \"executor.tool.dispatch_path\": \"static\",\n \"executor.source_id\": staticEntry.source.id,\n \"executor.source_kind\": staticEntry.source.kind,\n \"executor.plugin_id\": staticEntry.pluginId,\n });\n yield* enforceApproval(staticEntry.tool.annotations, toolId, args, policy, handler).pipe(\n Effect.withSpan(\"executor.tool.enforce_approval\"),\n );\n return yield* wrapInvocationError(toolId)(\n staticEntry.tool.handler({\n ctx: staticEntry.ctx,\n args,\n elicit: buildElicit(toolId, args, handler),\n }),\n ).pipe(Effect.withSpan(\"executor.tool.handler\"));\n }\n\n // Dynamic path — DB lookup + delegate to owning plugin. Walk the\n // whole scope stack and pick the innermost-scope row so a user's\n // shadow of an outer tool actually wins on invoke.\n let toolRows = yield* core\n .findMany(\"tool\", {\n where: scopedWhere(scopeIds, byId(toolId)),\n })\n .pipe(Effect.withSpan(\"executor.tool.resolve\"));\n let row = findInnermost(toolRows);\n let resolvedToolId = toolId;\n let suggestionRows: readonly CoreRow<\"tool\">[] = toolRows;\n if (!row) {\n suggestionRows = yield* core\n .findMany(\"tool\", {\n where: scopedWhere(scopeIds),\n })\n .pipe(Effect.withSpan(\"executor.tool.resolve_suggestions\"));\n const sourceId = toolSourceId(toolId);\n if (sourceId) {\n const normalizedToolId = toolId.toLowerCase();\n row = findInnermost(\n suggestionRows.filter(\n (toolRow) =>\n toolRow.source_id === sourceId && toolRow.id.toLowerCase() === normalizedToolId,\n ),\n );\n if (row) resolvedToolId = row.id;\n }\n }\n if (!row) {\n return yield* new ToolNotFoundError({\n toolId: ToolId.make(toolId),\n suggestions: missingToolSuggestions(toolId, suggestionRows),\n });\n }\n yield* Effect.annotateCurrentSpan({\n \"executor.tool.dispatch_path\": \"dynamic\",\n \"executor.source_id\": row.source_id,\n \"executor.plugin_id\": row.plugin_id,\n \"executor.tool.resolved_id\": resolvedToolId,\n });\n const policy = yield* resolveToolPolicyForId(resolvedToolId).pipe(\n Effect.withSpan(\"executor.tool.resolve_policy\"),\n );\n if (policy?.action === \"block\") {\n return yield* new ToolBlockedError({\n toolId: ToolId.make(resolvedToolId),\n pattern: policy.pattern,\n });\n }\n const runtime = runtimes.get(row.plugin_id);\n if (!runtime) {\n return yield* new PluginNotLoadedError({\n pluginId: row.plugin_id,\n toolId: ToolId.make(toolId),\n });\n }\n if (!runtime.plugin.invokeTool) {\n return yield* new NoHandlerError({\n toolId: ToolId.make(toolId),\n pluginId: row.plugin_id,\n });\n }\n\n // Ask the plugin to derive annotations for this one row, if it\n // has a resolver. Cheap because the plugin typically already\n // needs to load its enrichment data to invoke the tool —\n // implementations should structure their resolver + invokeTool\n // around a single storage read. Skipped entirely when the user\n // policy is `approve` — the prompt is going to be skipped no\n // matter what the plugin says, so don't pay for the lookup.\n let annotations: ToolAnnotations | undefined;\n if (policy?.action !== \"approve\" && runtime.plugin.resolveAnnotations) {\n const map = yield* runtime.plugin\n .resolveAnnotations({\n ctx: runtime.ctx,\n sourceId: row.source_id,\n toolRows: [row],\n })\n .pipe(wrapInvocationError(resolvedToolId))\n .pipe(Effect.withSpan(\"executor.tool.resolve_annotations\"));\n annotations = map[resolvedToolId];\n }\n yield* enforceApproval(annotations, resolvedToolId, args, policy, handler).pipe(\n Effect.withSpan(\"executor.tool.enforce_approval\"),\n );\n\n return yield* wrapInvocationError(resolvedToolId)(\n runtime.plugin.invokeTool({\n ctx: runtime.ctx,\n toolRow: row,\n args,\n elicit: buildElicit(resolvedToolId, args, handler),\n }),\n ).pipe(Effect.withSpan(\"executor.tool.handler\"));\n }).pipe(\n Effect.withSpan(\"executor.tool.invoke\", {\n attributes: {\n \"mcp.tool.name\": toolId,\n },\n }),\n );\n };\n\n const removeSource = (input: RemoveSourceInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"source remove targetScope\", input.targetScope);\n const sourceId = input.id;\n // Block removal of static sources structurally.\n if (staticSources.has(sourceId)) {\n return yield* new SourceRemovalNotAllowedError({ sourceId });\n }\n const sourceRow = yield* core.findFirst(\"source\", {\n where: byScopedId(input.targetScope, sourceId),\n });\n if (!sourceRow) return;\n if (!sourceRow.can_remove) {\n return yield* new SourceRemovalNotAllowedError({ sourceId });\n }\n const runtime = runtimes.get(sourceRow.plugin_id);\n // Group the plugin's own cleanup + the core row delete into one\n // Fuma transaction so removeSource never leaves orphan rows on failure.\n yield* transaction(\n Effect.gen(function* () {\n if (runtime?.plugin.removeSource) {\n yield* runtime.plugin\n .removeSource({\n ctx: runtime.ctx,\n sourceId,\n scope: input.targetScope,\n })\n .pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(runtime.plugin.id, \"removeSource\", cause),\n ),\n );\n }\n yield* deleteSourceById(core, sourceId, input.targetScope);\n }),\n );\n });\n\n const refreshSource = (input: RefreshSourceInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"source refresh targetScope\", input.targetScope);\n const sourceId = input.id;\n if (staticSources.has(sourceId)) return;\n const sourceRow = yield* core.findFirst(\"source\", {\n where: byScopedId(input.targetScope, sourceId),\n });\n if (!sourceRow) return;\n const runtime = runtimes.get(sourceRow.plugin_id);\n if (runtime?.plugin.refreshSource) {\n yield* runtime.plugin\n .refreshSource({\n ctx: runtime.ctx,\n sourceId,\n scope: input.targetScope,\n })\n .pipe(\n Effect.mapError((cause) =>\n pluginStorageFailure(runtime.plugin.id, \"refreshSource\", cause),\n ),\n );\n }\n });\n\n const sourceDetectionMaxUrlLength = config.sourceDetection?.maxUrlLength ?? 2_048;\n const sourceDetectionMaxDetectors = config.sourceDetection?.maxDetectors ?? 6;\n const sourceDetectionMaxResults = config.sourceDetection?.maxResults ?? 4;\n const sourceDetectionTimeout = config.sourceDetection?.timeout ?? \"60 seconds\";\n const sourceDetectionHostedOutboundPolicy =\n config.sourceDetection?.hostedOutboundPolicy ?? config.httpClientLayer !== undefined;\n\n // URL autodetection — fan out across a bounded set of plugins that\n // declared a `detect` hook. Collect non-null results up to the\n // configured cap. Plugin-level detect implementations should\n // swallow fetch errors and return null, so one flaky plugin doesn't\n // block the whole dispatch.\n const detectionConfidenceScore = (confidence: SourceDetectionResult[\"confidence\"]) =>\n Match.value(confidence).pipe(\n Match.when(\"high\", () => 3),\n Match.when(\"medium\", () => 2),\n Match.when(\"low\", () => 1),\n Match.exhaustive,\n );\n\n const detectSource = (url: string) =>\n Effect.gen(function* () {\n const trimmed = url.trim();\n if (trimmed.length === 0 || trimmed.length > sourceDetectionMaxUrlLength) return [];\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (error) => error,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return [];\n if (parsed.value.protocol !== \"http:\" && parsed.value.protocol !== \"https:\") return [];\n if (sourceDetectionHostedOutboundPolicy) {\n const allowed = yield* validateHostedOutboundUrl(trimmed).pipe(\n Effect.as(true),\n Effect.catch(() => Effect.succeed(false)),\n );\n if (!allowed) return [];\n }\n\n const results: SourceDetectionResult[] = [];\n let detectorCount = 0;\n for (const runtime of runtimes.values()) {\n if (!runtime.plugin.detect) continue;\n if (detectorCount >= sourceDetectionMaxDetectors) break;\n detectorCount++;\n const result = yield* runtime.plugin\n .detect({ ctx: runtime.ctx, url: trimmed })\n .pipe(Effect.timeout(sourceDetectionTimeout))\n .pipe(Effect.catch(() => Effect.succeed(null)));\n if (result) results.push(result);\n }\n return results\n .sort(\n (a, b) =>\n detectionConfidenceScore(b.confidence) - detectionConfidenceScore(a.confidence),\n )\n .slice(0, sourceDetectionMaxResults);\n });\n\n // Per-source definitions accessor — one query, one mapping pass.\n const sourceDefinitions = (sourceId: string) => loadDefinitionsForSource(sourceId);\n\n // Existence check for user-facing secret pickers. Core `secret`\n // rows are routing metadata; when a provider can answer `has()`,\n // confirm the backing value still exists. Providers without `has()`\n // remain conservative so keychain/1password don't need to return\n // the value or prompt just to populate picker/status UI.\n const secretsStatus = (id: string): Effect.Effect<\"resolved\" | \"missing\", StorageFailure> =>\n Effect.gen(function* () {\n const rows = yield* secretRowsForId(id);\n if (rows.some((row) => row.owned_by_connection_id)) return \"missing\";\n for (const row of rows) {\n if (yield* secretRouteHasBackingValue(row)) return \"resolved\";\n }\n\n return \"missing\";\n });\n\n // ------------------------------------------------------------------\n // Policies — CRUD surface backed by the `tool_policy` core table.\n // The cloud settings UI is one consumer; plugins call the same API\n // when they programmatically manage policies.\n //\n // `list` orders rows innermost scope first, then position ascending.\n // Resolution then takes the first local match per scope and applies\n // the most restrictive action across scopes.\n // ------------------------------------------------------------------\n const policiesList = () =>\n Effect.gen(function* () {\n const rows = yield* loadAllPolicies();\n const sorted = [...rows].sort((a, b) => {\n const sa = scopeRank(a);\n const sb = scopeRank(b);\n if (sa !== sb) return sa - sb;\n return comparePolicyRow(a, b);\n });\n return sorted.map((row) => rowToToolPolicy(row));\n }).pipe(Effect.withSpan(\"executor.policies.list\"));\n\n const policiesCreate = (input: CreateToolPolicyInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"tool policy targetScope\", input.targetScope);\n if (!isValidPattern(input.pattern)) {\n return yield* new StorageError({\n message:\n `Invalid tool policy pattern \"${input.pattern}\". ` +\n `Patterns must be \"*\" (every tool), an exact tool id (\"a.b.c\"), ` +\n `or a trailing wildcard (\"a.b.*\"). Leading \"*\" prefixes ` +\n `(\"*foo\", \"*.foo\") and \"**\" are not supported.`,\n cause: undefined,\n });\n }\n if (!isToolPolicyAction(input.action)) {\n return yield* new StorageError({\n message:\n `Invalid tool policy action \"${String(input.action)}\". ` +\n `Expected \"approve\" | \"require_approval\" | \"block\".`,\n cause: undefined,\n });\n }\n\n // Default position: a fractional-indexing key above the\n // current minimum. Lets newly-created rules win against\n // existing ones, which matches the v1 design — users typically\n // add a rule to override behavior they're seeing right now,\n // not as a background fallback.\n let position = input.position;\n if (position === undefined) {\n const existing = yield* core.findMany(\"tool_policy\", {\n where: (b) => b(\"scope_id\", \"=\", input.targetScope),\n });\n let min: string | null = null;\n for (const row of existing) {\n const p = row.position;\n if (min === null || p < min) min = p;\n }\n position = generateKeyBetween(null, min);\n }\n\n const id = `pol_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;\n const now = new Date();\n yield* core.create(\"tool_policy\", {\n id,\n scope_id: input.targetScope,\n pattern: input.pattern,\n action: input.action,\n position,\n created_at: now,\n updated_at: now,\n });\n return rowToToolPolicy({\n id,\n scope_id: input.targetScope,\n pattern: input.pattern,\n action: input.action,\n position,\n created_at: now,\n updated_at: now,\n } as ToolPolicyRow);\n }).pipe(Effect.withSpan(\"executor.policies.create\"));\n\n const policiesUpdate = (input: UpdateToolPolicyInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"tool policy targetScope\", input.targetScope);\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 if (input.action !== undefined && !isToolPolicyAction(input.action)) {\n return yield* new StorageError({\n message: `Invalid tool policy action \"${String(input.action)}\".`,\n cause: undefined,\n });\n }\n\n const rows = yield* core.findMany(\"tool_policy\", {\n where: byScopedId(input.targetScope, input.id),\n });\n const row = rows[0] ?? null;\n if (!row) {\n return yield* new StorageError({\n message: `Tool policy \"${input.id}\" not found in scope \"${input.targetScope}\".`,\n cause: undefined,\n });\n }\n\n const updated: ToolPolicyRow = {\n ...row,\n pattern: input.pattern ?? row.pattern,\n action: input.action ?? row.action,\n position: input.position ?? row.position,\n updated_at: new Date(),\n };\n yield* core.updateMany(\"tool_policy\", {\n where: byScopedId(input.targetScope, input.id),\n set: {\n pattern: updated.pattern,\n action: updated.action,\n position: updated.position,\n updated_at: updated.updated_at,\n },\n });\n return rowToToolPolicy(updated);\n }).pipe(Effect.withSpan(\"executor.policies.update\"));\n\n const policiesRemove = (input: RemoveToolPolicyInput) =>\n Effect.gen(function* () {\n yield* assertScopeInStack(\"tool policy targetScope\", input.targetScope);\n yield* core.deleteMany(\"tool_policy\", {\n where: byScopedId(input.targetScope, input.id),\n });\n }).pipe(Effect.withSpan(\"executor.policies.remove\"));\n\n const policiesResolve = (toolId: string) =>\n resolveToolPolicyForId(toolId).pipe(Effect.withSpan(\"executor.policies.resolve\"));\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 // Public Executor surface — storage-backed methods surface\n // `StorageFailure` (StorageError | UniqueViolationError) raw. The\n // HTTP edge wraps this surface with `withCapture` to\n // translate `StorageError` → `InternalError({ traceId })`; non-HTTP\n // consumers (CLI, Promise SDK, tests) see the raw typed channel.\n const base = {\n scopes,\n tools: {\n list: listTools,\n schema: toolSchema,\n definitions: toolsDefinitions,\n invoke: invokeTool,\n },\n sources: {\n list: listSources,\n remove: removeSource,\n refresh: refreshSource,\n detect: detectSource,\n definitions: sourceDefinitions,\n configure: sourceConfigure,\n listBindings: sourceBindingList,\n resolveBinding: sourceBindingResolve,\n setBinding: sourceBindingSet,\n removeBinding: sourceBindingRemove,\n replaceBindings: sourceBindingReplace,\n },\n secrets: {\n get: secretsGet,\n getAtScope: secretsGetAtScope,\n status: secretsStatus,\n set: secretsSet,\n remove: secretsRemove,\n list: secretsList,\n listAll: secretsListAll,\n usages: secretsUsages,\n providers: () => Effect.sync(() => Array.from(secretProviders.keys()) as readonly string[]),\n },\n connections: {\n get: connectionsGet,\n getAtScope: connectionsGetAtScope,\n list: connectionsList,\n create: connectionsCreate,\n updateTokens: connectionsUpdateTokens,\n setIdentityLabel: connectionsSetIdentityLabel,\n accessToken: connectionsAccessToken,\n accessTokenAtScope: connectionsAccessTokenAtScope,\n remove: connectionsRemove,\n usages: connectionsUsages,\n providers: () =>\n Effect.sync(() => Array.from(connectionProviders.keys()) as readonly string[]),\n },\n credentialBindings,\n oauth: oauthBundle.service,\n policies: {\n list: policiesList,\n create: policiesCreate,\n update: policiesUpdate,\n remove: policiesRemove,\n resolve: policiesResolve,\n },\n close,\n };\n\n // Plugin extension keys are known from the generic plugin tuple,\n // while runtime registration builds the same shape dynamically.\n const toExecutor = (value: unknown): Executor<TPlugins> => value as Executor<TPlugins>;\n return toExecutor(Object.assign(base, extensions));\n });\n","import { Schema } from \"effect\";\n\nimport { ScopeId } from \"./ids\";\n\nexport const Scope = Schema.Struct({\n id: ScopeId,\n name: Schema.String,\n createdAt: Schema.Date,\n});\nexport type Scope = typeof Scope.Type;\n\n/**\n * Source-add flows that do not expose a user-facing placement choice install\n * sources at the outermost visible scope. Local executors have one scope, while\n * cloud executors use an innermost personal scope plus an outer organization\n * scope where shared sources live.\n */\nexport const defaultSourceInstallScopeId = (\n scopes: readonly { readonly id: ScopeId | string }[],\n): string | null => {\n const scope = scopes[scopes.length - 1];\n return scope ? String(scope.id) : null;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAS,cAAc;AA4CvB,IAAM,cAAc,CAAC,OAAe,WAClC,OAAO,SAAS,KAAK,IACjB,OAAO,OACP,OAAO;AAAA,EACL,IAAI,aAAa;AAAA,IACf,SACE,6BAA6B,KAAK,iDACP,OAAO,KAAK,IAAI,CAAC;AAAA,IAC9C,OAAO;AAAA,EACT,CAAC;AACH;AAEN,IAAM,QAAQ,CAAC,OAAe,aAAqB,GAAG,KAAK,IAAI,QAAQ;AAQhE,IAAM,kBAAkB,CAC7B,OACA,QACA,cACqB;AAAA,EACrB,KAAK,CAAC,QACJ,OAAO,IAAI,aAAa;AACtB,UAAM,aAAa,OAAO,IAAI,CAAC,MAAM,MAAM,GAAG,QAAQ,CAAC;AACvD,UAAM,OAAO,OAAO,MAAM,QAAQ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AAAA,MACR,MAAM;AAAA,MACN,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,WAAW,MAAMA,SAAO,KAAK,MAAM,MAAM,KAAK,gBAAgB,KAAK,CAAC,CAAsB;AAAA,IAC5F;AAAA,IACA,aAAa;AAAA,MACX,KAAK;AAAA,MACL,YAAY;AAAA,MACZ,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,cAAc;AAAA,MACd,kBAAkB;AAAA,MAClB,aAAa;AAAA,MACb,oBAAoB;AAAA,MACpB,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,WAAW,MACTA,SAAO,KAAK,MAAM,MAAM,KAAK,oBAAoB,KAAK,CAAC,CAAsB;AAAA,IACjF;AAAA,IACA;AAAA,IACA,OAAO,YAAY;AAAA,IACnB,UAAU;AAAA,MACR,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,IACA;AAAA,EACF;AAIA,QAAM,aAAa,CAAC,UAAuC;AAC3D,SAAO,WAAW,OAAO,OAAO,MAAM,UAAU,CAAC;AACnD,CAAC;;;AC5nIH,SAAS,UAAAe,gBAAc;AAIhB,IAAM,QAAQC,SAAO,OAAO;AAAA,EACjC,IAAI;AAAA,EACJ,MAAMA,SAAO;AAAA,EACb,WAAWA,SAAO;AACpB,CAAC;AASM,IAAM,8BAA8B,CACzC,WACkB;AAClB,QAAM,QAAQ,OAAO,OAAO,SAAS,CAAC;AACtC,SAAO,QAAQ,OAAO,MAAM,EAAE,IAAI;AACpC;","names":["Effect","Schema","Data","Effect","Schema","Schema","Data","Effect","Schema","Schema","Schema","Schema","Data","Effect","Data","Effect","Predicate","Schema","Data","Schema","Effect","Predicate","response","Duration","Effect","Option","Schema","FetchHttpClient","HttpClient","HttpClientRequest","Schema","Effect","Option","crypto","HttpClient","HttpClientRequest","Duration","FetchHttpClient","changed","key","ast","minItems","maxItems","type","rules","schema","Effect","Layer","Schema","FetchHttpClient","Effect","Match","Option","Predicate","Result","Schema","FetchHttpClient","Effect","Schema","Option","decodeProviderState","tool","value","byId","Result","now","FetchHttpClient","plugin","Predicate","resolvedToolId","policy","Match","Schema","Schema"]}