@rafads/plugin-openapi 1.5.38

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 (122) hide show
  1. package/README.md +83 -0
  2. package/dist/AddOpenApiIntegration-JPAEXE56.js +512 -0
  3. package/dist/AddOpenApiIntegration-JPAEXE56.js.map +1 -0
  4. package/dist/OpenApiAccountsPanel-GZFDSTAU.js +106 -0
  5. package/dist/OpenApiAccountsPanel-GZFDSTAU.js.map +1 -0
  6. package/dist/UpdateSpecSection-KUSNI44Q.js +106 -0
  7. package/dist/UpdateSpecSection-KUSNI44Q.js.map +1 -0
  8. package/dist/api/group.d.ts +239 -0
  9. package/dist/api/handlers.d.ts +7 -0
  10. package/dist/api/index.d.ts +237 -0
  11. package/dist/chunk-6V45G2XQ.js +199 -0
  12. package/dist/chunk-6V45G2XQ.js.map +1 -0
  13. package/dist/chunk-CURJJXB3.js +132 -0
  14. package/dist/chunk-CURJJXB3.js.map +1 -0
  15. package/dist/chunk-CXFO6TLJ.js +39 -0
  16. package/dist/chunk-CXFO6TLJ.js.map +1 -0
  17. package/dist/chunk-HTHEUUJA.js +2873 -0
  18. package/dist/chunk-HTHEUUJA.js.map +1 -0
  19. package/dist/chunk-IG6QTTZB.js +79 -0
  20. package/dist/chunk-IG6QTTZB.js.map +1 -0
  21. package/dist/chunk-O2LMSZ2Z.js +120 -0
  22. package/dist/chunk-O2LMSZ2Z.js.map +1 -0
  23. package/dist/chunk-OR27BCXQ.js +956 -0
  24. package/dist/chunk-OR27BCXQ.js.map +1 -0
  25. package/dist/chunk-R7TVM3XD.js +275 -0
  26. package/dist/chunk-R7TVM3XD.js.map +1 -0
  27. package/dist/client.js +38 -0
  28. package/dist/client.js.map +1 -0
  29. package/dist/core.js +331 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/index.js +19 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/providers/google/config.d.ts +34 -0
  34. package/dist/providers/google/discovery.d.ts +49 -0
  35. package/dist/providers/google/discovery.test.d.ts +1 -0
  36. package/dist/providers/google/index.d.ts +5 -0
  37. package/dist/providers/google/oauth-scopes.d.ts +3 -0
  38. package/dist/providers/google/oauth-scopes.test.d.ts +1 -0
  39. package/dist/providers/google/openapi-ownership-migration.d.ts +7 -0
  40. package/dist/providers/google/openapi-ownership-migration.test.d.ts +1 -0
  41. package/dist/providers/google/presets.d.ts +31 -0
  42. package/dist/providers/google/presets.test.d.ts +1 -0
  43. package/dist/providers/google/spec-format-adapter.d.ts +3 -0
  44. package/dist/providers/google/spec-format-adapter.test.d.ts +1 -0
  45. package/dist/providers/google.js +1446 -0
  46. package/dist/providers/google.js.map +1 -0
  47. package/dist/providers/microsoft/graph.d.ts +76 -0
  48. package/dist/providers/microsoft/graph.test.d.ts +1 -0
  49. package/dist/providers/microsoft/index.d.ts +3 -0
  50. package/dist/providers/microsoft/presets.d.ts +46 -0
  51. package/dist/providers/microsoft/presets.test.d.ts +1 -0
  52. package/dist/providers/microsoft/spec-format-adapter.d.ts +2 -0
  53. package/dist/providers/microsoft/spec-format-adapter.test.d.ts +1 -0
  54. package/dist/providers/microsoft.js +1056 -0
  55. package/dist/providers/microsoft.js.map +1 -0
  56. package/dist/react/AddOpenApiIntegration.d.ts +22 -0
  57. package/dist/react/AddOpenApiIntegration.test.d.ts +1 -0
  58. package/dist/react/OpenApiAccountsPanel.d.ts +6 -0
  59. package/dist/react/OpenApiIntegrationDetailsFields.d.ts +25 -0
  60. package/dist/react/UpdateSpecSection.d.ts +2 -0
  61. package/dist/react/atoms.d.ts +317 -0
  62. package/dist/react/auth-method-config.d.ts +18 -0
  63. package/dist/react/auth-method-config.test.d.ts +1 -0
  64. package/dist/react/client.d.ts +233 -0
  65. package/dist/react/index.d.ts +5 -0
  66. package/dist/react/integration-plugin.d.ts +6 -0
  67. package/dist/react/plugin-client.d.ts +2 -0
  68. package/dist/sdk/backing.d.ts +188 -0
  69. package/dist/sdk/client-credentials-oauth.test.d.ts +1 -0
  70. package/dist/sdk/compiled-spec-cache.test.d.ts +1 -0
  71. package/dist/sdk/config.d.ts +81 -0
  72. package/dist/sdk/configure.test.d.ts +1 -0
  73. package/dist/sdk/definitions.d.ts +57 -0
  74. package/dist/sdk/derive-auth.d.ts +11 -0
  75. package/dist/sdk/describe-auth-methods.test.d.ts +1 -0
  76. package/dist/sdk/errors.d.ts +45 -0
  77. package/dist/sdk/extract.d.ts +157 -0
  78. package/dist/sdk/extract.test.d.ts +1 -0
  79. package/dist/sdk/form-urlencoded-body.test.d.ts +1 -0
  80. package/dist/sdk/index.d.ts +19 -0
  81. package/dist/sdk/index.test.d.ts +1 -0
  82. package/dist/sdk/invoke.d.ts +150 -0
  83. package/dist/sdk/migrate-config.d.ts +4 -0
  84. package/dist/sdk/migrate-config.test.d.ts +1 -0
  85. package/dist/sdk/multi-scope-bearer.test.d.ts +1 -0
  86. package/dist/sdk/multi-scope-oauth.test.d.ts +1 -0
  87. package/dist/sdk/ndjson-output-migration.d.ts +13 -0
  88. package/dist/sdk/ndjson-output-migration.test.d.ts +1 -0
  89. package/dist/sdk/non-json-body.test.d.ts +1 -0
  90. package/dist/sdk/oauth-refresh.test.d.ts +1 -0
  91. package/dist/sdk/openapi-utils.d.ts +65 -0
  92. package/dist/sdk/output-schema-migration.d.ts +21 -0
  93. package/dist/sdk/output-schema-migration.test.d.ts +1 -0
  94. package/dist/sdk/parse.d.ts +33 -0
  95. package/dist/sdk/parse.test.d.ts +1 -0
  96. package/dist/sdk/plugin.d.ts +109 -0
  97. package/dist/sdk/plugin.test.d.ts +1 -0
  98. package/dist/sdk/presets.d.ts +15 -0
  99. package/dist/sdk/preview-oauth2.test.d.ts +1 -0
  100. package/dist/sdk/preview.d.ts +514 -0
  101. package/dist/sdk/query-serialization.test.d.ts +1 -0
  102. package/dist/sdk/real-specs.test.d.ts +1 -0
  103. package/dist/sdk/request-user-agent.test.d.ts +1 -0
  104. package/dist/sdk/response-headers-timeout.test.d.ts +1 -0
  105. package/dist/sdk/server-url-resolution.test.d.ts +1 -0
  106. package/dist/sdk/spec-blob-migration.d.ts +7 -0
  107. package/dist/sdk/spec-blob.test.d.ts +1 -0
  108. package/dist/sdk/spec-format.d.ts +36 -0
  109. package/dist/sdk/spec-format.test.d.ts +1 -0
  110. package/dist/sdk/split.d.ts +84 -0
  111. package/dist/sdk/store.d.ts +49 -0
  112. package/dist/sdk/store.test.d.ts +1 -0
  113. package/dist/sdk/streaming-response.test.d.ts +1 -0
  114. package/dist/sdk/tool-row-projection.test.d.ts +1 -0
  115. package/dist/sdk/types.d.ts +352 -0
  116. package/dist/sdk/upstream-failures.test.d.ts +1 -0
  117. package/dist/sdk/usage-scope-isolation.test.d.ts +1 -0
  118. package/dist/testing/index.d.ts +177 -0
  119. package/dist/testing.js +454 -0
  120. package/dist/testing.js.map +1 -0
  121. package/dist/testing.test.d.ts +1 -0
  122. package/package.json +103 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/parse.ts","../src/sdk/openapi-utils.ts","../src/sdk/types.ts","../src/sdk/extract.ts","../src/sdk/definitions.ts","../src/sdk/invoke.ts","../src/sdk/backing.ts","../src/sdk/preview.ts"],"sourcesContent":["import type { OpenAPI, OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport { Duration, Effect, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport { JSON_SCHEMA, load as parseYamlDocument } from \"js-yaml\";\n\nimport { OpenApiExtractionError, OpenApiParseError } from \"./errors\";\n\nexport type ParsedDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\nexport interface SpecFetchCredentials {\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\n// ExtractionError subclass raised from parse() for non-3.x specs\nclass OpenApiExtractionErrorFromParse extends OpenApiExtractionError {}\n\n/**\n * Fetch an OpenAPI spec URL and return its body text. Uses the Effect\n * HttpClient so the caller chooses the transport via layer — in Cloudflare\n * Workers, `FetchHttpClient.layer` binds to the Workers-native `fetch`.\n * Bounded by a 60s timeout.\n */\nexport const fetchSpecText = Effect.fn(\"OpenApi.fetchSpecText\")(function* (\n url: string,\n credentials?: SpecFetchCredentials,\n) {\n const client = yield* HttpClient.HttpClient;\n const requestUrl = new URL(url);\n for (const [name, value] of Object.entries(credentials?.queryParams ?? {})) {\n requestUrl.searchParams.set(name, value);\n }\n let request = HttpClientRequest.get(requestUrl.toString()).pipe(\n HttpClientRequest.setHeader(\"Accept\", \"application/json, application/yaml, text/yaml, */*\"),\n );\n for (const [name, value] of Object.entries(credentials?.headers ?? {})) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n const response = yield* client.execute(request).pipe(\n Effect.timeout(Duration.seconds(60)),\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to fetch OpenAPI document\",\n }),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* new OpenApiParseError({\n message: `Failed to fetch OpenAPI document: HTTP ${response.status}`,\n });\n }\n const specText = yield* response.text.pipe(\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to read OpenAPI document body\",\n }),\n ),\n );\n return specText;\n});\n\n/**\n * Resolve an input string to spec text — if it's a URL, fetch it via\n * HttpClient; otherwise return it as-is.\n */\nexport const resolveSpecText = (input: string, credentials?: SpecFetchCredentials) =>\n input.startsWith(\"http://\") || input.startsWith(\"https://\")\n ? fetchSpecText(input, credentials)\n : Effect.succeed(input);\n\n/**\n * Parse an OpenAPI document from spec text and validate it's OpenAPI 3.x.\n *\n * NOTE: does NOT resolve `$ref`s. `DocResolver` + `normalizeOpenApiRefs`\n * downstream work on refs lazily, so inlining them here would just waste\n * memory — and for big specs (e.g. Cloudflare's API) that blows through\n * the 128MB Cloudflare Workers memory cap.\n */\nexport const parse = Effect.fn(\"OpenApi.parse\")(function* (text: string) {\n const api = yield* parseTextToObject(text);\n\n if (!isOpenApi3(api)) {\n return yield* new OpenApiExtractionErrorFromParse({\n message:\n \"Only OpenAPI 3.x documents are supported. Swagger 2.x documents should be converted first.\",\n });\n }\n\n return api as ParsedDocument;\n});\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nconst isOpenApi3 = (doc: OpenAPI.Document): doc is OpenAPIV3.Document | OpenAPIV3_1.Document =>\n \"openapi\" in doc && typeof doc.openapi === \"string\" && doc.openapi.startsWith(\"3.\");\n\nconst parseTextToObject = (text: string): Effect.Effect<OpenAPI.Document, OpenApiParseError> =>\n Effect.gen(function* () {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document is empty\",\n });\n }\n\n const parsed = yield* parseJsonLike(trimmed).pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to parse OpenAPI document\",\n }),\n ),\n );\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document must parse to an object\",\n });\n }\n\n return parsed as OpenAPI.Document;\n });\n\nconst parseJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst parseJsonLike = (text: string): Effect.Effect<unknown, unknown> => {\n const parseYaml = Effect.try({\n try: () => parseYamlDocument(text, { json: true, schema: JSON_SCHEMA }) as unknown,\n catch: () => \"YamlParseFailed\" as const,\n });\n if (!text.startsWith(\"{\") && !text.startsWith(\"[\")) return parseYaml;\n return parseJsonText(text).pipe(Effect.catch(() => parseYaml));\n};\n","// ---------------------------------------------------------------------------\n// OpenAPI type aliases and $ref resolution\n//\n// Wraps the openapi-types V3/V3_1 union mess and provides clean ref resolution.\n// ---------------------------------------------------------------------------\n\nimport type { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport type { ParsedDocument } from \"./parse\";\nimport type { ServerVariable } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Type aliases — collapse V3 / V3_1 unions into single names\n// ---------------------------------------------------------------------------\n\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\n\n// ---------------------------------------------------------------------------\n// DocResolver — wraps a parsed document for clean $ref resolution\n// ---------------------------------------------------------------------------\n\nexport class DocResolver {\n constructor(readonly doc: ParsedDocument) {}\n\n /** Resolve a value that might be a $ref, returning the resolved object */\n resolve<T>(value: T | OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject): T | null {\n if (isRef(value)) {\n const resolved = this.resolvePointer(value.$ref);\n return resolved as T | null;\n }\n return value as T;\n }\n\n private resolvePointer(ref: string): unknown {\n if (!ref.startsWith(\"#/\")) return null;\n const segments = ref.slice(2).split(\"/\");\n let current: unknown = this.doc;\n for (const segment of segments) {\n if (typeof current !== \"object\" || current === null) return null;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n }\n}\n\nconst isRef = (value: unknown): value is { $ref: string } =>\n typeof value === \"object\" && value !== null && \"$ref\" in value;\n\n// ---------------------------------------------------------------------------\n// Server URL resolution\n// ---------------------------------------------------------------------------\n\n/** Substitute `{var}` placeholders in a templated URL using a plain map. */\nexport const substituteUrlVariables = (url: string, values: Record<string, string>): string => {\n let out = url;\n for (const [name, value] of Object.entries(values)) {\n out = out.replaceAll(`{${name}}`, value);\n }\n return out;\n};\n\n/** Resolve a templated server URL, filling each `{var}` from `overrides` when\n * non-empty, otherwise the variable's spec default. URLs without placeholders\n * pass through unchanged. */\nexport const resolveServerUrl = (\n templateUrl: string,\n variables: Record<string, ServerVariable> | undefined,\n overrides: Record<string, string>,\n): string => {\n const values: Record<string, string> = {};\n for (const [name, v] of Object.entries(variables ?? {})) values[name] = v.default;\n for (const [name, value] of Object.entries(overrides)) {\n if (value) values[name] = value;\n }\n return substituteUrlVariables(templateUrl, values);\n};\n\n// ---------------------------------------------------------------------------\n// Content negotiation\n// ---------------------------------------------------------------------------\n\n/**\n * Return all declared media entries in spec order. `Object.entries` on a\n * plain object preserves insertion order in modern engines, which matches\n * spec declaration order as the parser produced it.\n */\nexport const declaredContents = (\n content: Record<string, MediaTypeObject> | undefined,\n): ReadonlyArray<{ mediaType: string; media: MediaTypeObject }> => {\n if (!content) return [];\n return Object.entries(content).map(([mediaType, media]) => ({ mediaType, media }));\n};\n\n/**\n * Pick the default media type for a requestBody or response. Matches\n * swagger-client behaviour: **first declared wins** (not JSON-first). Spec\n * authors order content entries to signal intent (upload-heavy endpoints\n * declare multipart first, JSON second); respecting that order avoids\n * silently downgrading a multipart endpoint to JSON.\n *\n * For response bodies we still want a JSON preference because the server\n * picks the response content type, not the client — the old `application/\n * json` preference is preserved via `preferredResponseContent` below.\n */\nexport const preferredContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n const first = declaredContents(content)[0];\n return first ? first : undefined;\n};\n\n/** Response-side content picker — still JSON-first because the server\n * picks the response media type, so we want to advertise a preference. */\nexport const preferredResponseContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n if (!content) return undefined;\n const entries = Object.entries(content);\n const pick =\n entries.find(([mt]) => mt === \"application/json\") ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"+json\")) ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"json\")) ??\n entries[0];\n return pick ? { mediaType: pick[0], media: pick[1] } : undefined;\n};\n\n// ---------------------------------------------------------------------------\n// NDJSON responses\n// ---------------------------------------------------------------------------\n\nexport const normalizeMediaType = (mediaType: string | null | undefined): string =>\n mediaType?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\n/** Media types whose bodies are newline-delimited JSON documents. The invoke\n * path collects these streams and returns an ARRAY of parsed lines, so every\n * schema surface must describe that array: the spec convention is to declare\n * the schema of ONE line (e.g. Vercel's runtime-logs endpoint). */\nexport const NDJSON_MEDIA_TYPES: ReadonlySet<string> = new Set([\n \"application/stream+json\",\n \"application/x-ndjson\",\n \"application/jsonl\",\n]);\n\nexport const isNdjsonMediaType = (mediaType: string | null | undefined): boolean =>\n NDJSON_MEDIA_TYPES.has(normalizeMediaType(mediaType));\n\n/** Wrap a per-line NDJSON response schema into the array the runtime actually\n * returns. The description rides into the compiled TypeScript preview as a\n * JSDoc comment, so agents learn the truncation and raw-text caveats where\n * they read the type. */\nexport const ndjsonArrayOutputSchema = (lineSchema: unknown): Record<string, unknown> => ({\n type: \"array\",\n items: lineSchema,\n description:\n \"Parsed NDJSON stream: one array item per line. The stream may be truncated \" +\n \"(`x-executor-stream: truncated` response header); a body that is not valid \" +\n \"NDJSON is returned as the raw string instead.\",\n});\n","import { Schema } from \"effect\";\nimport { AuthTemplateSlug, type OAuthAuthentication } from \"@rafads/sdk/shared\";\nimport {\n apiKeyMethodFromAuthTemplate,\n isApiKeyAuthTemplate,\n type ApiKeyAuthMethod,\n type ApiKeyAuthTemplate,\n} from \"@rafads/sdk/http-auth\";\n\n// ---------------------------------------------------------------------------\n// Auth-template model.\n//\n// The apiKey method is the SHARED placements model (`@rafads/sdk/http-auth`,\n// the same shape the graphql/mcp plugins store): N header/query placements,\n// each rendered from its own credential input. The oauth template is\n// mechanism-intrinsic and comes from core (`OAuthAuthentication`, keyed\n// `kind: \"oauth2\"` with stored endpoints+scopes); an integration's\n// `Authentication` union composes the two. Client credentials\n// (clientId/secret) live on the core `OAuthClient`, not here.\n//\n// Pre-canonical stored templates (`type: \"apiKey\"` with `variable()`-templated\n// header/query records) are rewritten by the one-off config migration\n// (`migrate-config.ts`) — runtime code knows only this model.\n// ---------------------------------------------------------------------------\n\nexport { TOKEN_VARIABLE } from \"@rafads/sdk/http-auth\";\n\nexport type APIKeyAuthentication = ApiKeyAuthMethod;\n\n/** Every method is keyed by `kind` — `kind: \"oauth2\"` | `kind: \"apikey\"`. */\nexport type Authentication = OAuthAuthentication | APIKeyAuthentication;\n\n/** What auth inputs accept: oauth templates (wire-typed: plain slug) plus the\n * request-shaped apikey dialect (`type: \"apiKey\"`, headers/queryParams\n * records) — the ONE apikey authoring shape. Stored configs and the catalog\n * read as canonical placements; `apiKeyAuthTemplateFromMethod` serializes\n * them back for read-modify-write flows. */\nexport type OAuthAuthenticationInput = Omit<OAuthAuthentication, \"slug\"> & {\n readonly slug: string;\n};\nexport type AuthenticationInput = OAuthAuthenticationInput | ApiKeyAuthTemplate;\n\n/** Expand the request-shaped dialect into canonical placements and brand the\n * oauth slugs. A dialect entry without a slug gets a blank one —\n * `mergeAuthTemplates` backfills `custom_<id>`. */\nexport const normalizeOpenApiAuthInputs = (\n inputs: readonly AuthenticationInput[],\n): readonly Authentication[] =>\n inputs.map((input): Authentication => {\n if (!isApiKeyAuthTemplate(input)) {\n return { ...input, slug: AuthTemplateSlug.make(input.slug) };\n }\n const method = apiKeyMethodFromAuthTemplate(input);\n return { ...method, slug: method.slug ?? \"\" };\n });\n\n// ---------------------------------------------------------------------------\n// Branded IDs\n// ---------------------------------------------------------------------------\n\nexport const OperationId = Schema.String.pipe(Schema.brand(\"OperationId\"));\nexport type OperationId = typeof OperationId.Type;\n\n// ---------------------------------------------------------------------------\n// HTTP\n// ---------------------------------------------------------------------------\n\nexport const HttpMethod = Schema.Literals([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\nexport type HttpMethod = typeof HttpMethod.Type;\n\nexport const ParameterLocation = Schema.Literals([\"path\", \"query\", \"header\", \"cookie\"]);\nexport type ParameterLocation = typeof ParameterLocation.Type;\n\n// ---------------------------------------------------------------------------\n// Extracted operation\n// ---------------------------------------------------------------------------\n\nexport const OperationParameter = Schema.Struct({\n name: Schema.String,\n location: ParameterLocation,\n required: Schema.Boolean,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type OperationParameter = typeof OperationParameter.Type;\n\n/**\n * OpenAPI 3.x `Encoding Object` (§4.8.15). Declared per-property inside a\n * multipart/form-data or application/x-www-form-urlencoded request body.\n *\n * - `contentType` — for multipart, overrides the per-part `Content-Type`\n * header (e.g. `application/json` for a JSON-encoded metadata part).\n * - `style` / `explode` / `allowReserved` — for form-urlencoded, control\n * array / object serialization the same way parameter-level style does.\n */\nexport const EncodingObject = Schema.Struct({\n contentType: Schema.OptionFromOptional(Schema.String),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n});\nexport type EncodingObject = typeof EncodingObject.Type;\n\nexport const MediaBinding = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n encoding: Schema.OptionFromOptional(Schema.Record(Schema.String, EncodingObject)),\n});\nexport type MediaBinding = typeof MediaBinding.Type;\n\nexport const OperationRequestBody = Schema.Struct({\n required: Schema.Boolean,\n /** Default media type — first declared in spec order (not JSON-first).\n * Used when the caller does not override via the tool's `contentType` arg. */\n contentType: Schema.String,\n /** Schema of the default media type. Kept for backward compat with stored\n * bindings from before `contents` was added. */\n schema: Schema.OptionFromOptional(Schema.Unknown),\n /** All declared media types in spec order. Populated by `extract.ts`\n * going forward; older persisted bindings may have this unset and will\n * fall back to `{contentType, schema}`. */\n contents: Schema.OptionFromOptional(Schema.Array(MediaBinding)),\n});\nexport type OperationRequestBody = typeof OperationRequestBody.Type;\n\nexport const OperationFileHint = Schema.Struct({\n kind: Schema.Literals([\"binaryResponse\", \"byteField\"]),\n mimeType: Schema.OptionFromOptional(Schema.String),\n dataField: Schema.OptionFromOptional(Schema.String),\n sizeField: Schema.OptionFromOptional(Schema.String),\n encoding: Schema.OptionFromOptional(Schema.Literals([\"base64\", \"base64url\"])),\n});\nexport type OperationFileHint = typeof OperationFileHint.Type;\n\nexport const OperationResponseBody = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n fileHint: Schema.OptionFromOptional(OperationFileHint),\n});\nexport type OperationResponseBody = typeof OperationResponseBody.Type;\n\nexport const ServerVariable = Schema.Struct({\n default: Schema.String,\n enum: Schema.OptionFromOptional(Schema.Array(Schema.String)),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type ServerVariable = typeof ServerVariable.Type;\n\nexport const ServerInfo = Schema.Struct({\n url: Schema.String,\n description: Schema.OptionFromOptional(Schema.String),\n variables: Schema.OptionFromOptional(Schema.Record(Schema.String, ServerVariable)),\n});\nexport type ServerInfo = typeof ServerInfo.Type;\n\nexport const ExtractedOperation = Schema.Struct({\n operationId: OperationId,\n toolPath: Schema.OptionFromOptional(Schema.String),\n method: HttpMethod,\n servers: Schema.Array(ServerInfo),\n pathTemplate: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n responseBody: Schema.OptionFromOptional(OperationResponseBody),\n inputSchema: Schema.OptionFromOptional(Schema.Unknown),\n outputSchema: Schema.OptionFromOptional(Schema.Unknown),\n deprecated: Schema.Boolean,\n /** OAuth scope requirements from `security`, alternatives preserved: each\n * inner array is one acceptable Security Requirement Object's scope set\n * (sorted, deduped); the outer array is an OR across alternatives. An\n * absent operation `security` inherits the document default; an explicit\n * `security: []` (auth disabled) and a scope-less declaration both omit\n * the field. */\n requiredScopeAlternatives: Schema.optional(Schema.Array(Schema.Array(Schema.String))),\n});\nexport type ExtractedOperation = typeof ExtractedOperation.Type;\n\nexport const ExtractionResult = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n /** The spec's `info.description` — the author's own summary of the API. */\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operations: Schema.Array(ExtractedOperation),\n});\nexport type ExtractionResult = typeof ExtractionResult.Type;\n\n// ---------------------------------------------------------------------------\n// Operation binding — minimal invocation data (no schemas/metadata)\n// ---------------------------------------------------------------------------\n\nexport const OperationBinding = Schema.Struct({\n method: HttpMethod,\n servers: Schema.optional(Schema.Array(ServerInfo)),\n pathTemplate: Schema.String,\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n responseBody: Schema.OptionFromOptional(OperationResponseBody),\n /** Declared OAuth scope alternatives (see\n * ExtractedOperation.requiredScopeAlternatives), persisted with the\n * binding so the invoke path can annotate a scope-insufficient rejection\n * with exactly what the operation needs. Optional so bindings stored\n * before this field existed keep decoding. */\n requiredScopeAlternatives: Schema.optional(Schema.Array(Schema.Array(Schema.String))),\n});\nexport type OperationBinding = typeof OperationBinding.Type;\n\n// ---------------------------------------------------------------------------\n// Invocation\n// ---------------------------------------------------------------------------\n\nexport const InvocationResult = Schema.Struct({\n status: Schema.Number,\n headers: Schema.Record(Schema.String, Schema.String),\n data: Schema.NullOr(Schema.Unknown),\n error: Schema.NullOr(Schema.Unknown),\n});\nexport type InvocationResult = typeof InvocationResult.Type;\n","import { Effect, Option } from \"effect\";\n\nimport { planToolPaths, type OperationPathInput, type PlannedToolPath } from \"./definitions\";\nimport { OpenApiExtractionError } from \"./errors\";\nimport type { ParsedDocument } from \"./parse\";\nimport {\n parseEntry,\n parseHead,\n parseSmallComponents,\n type ByteRange,\n type KeepPathItem,\n type SpecStructure,\n} from \"./split\";\nimport {\n declaredContents,\n DocResolver,\n isNdjsonMediaType,\n ndjsonArrayOutputSchema,\n preferredResponseContent,\n type OperationObject,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n type ServerObject,\n} from \"./openapi-utils\";\nimport {\n EncodingObject,\n ExtractedOperation,\n ExtractionResult,\n type HttpMethod,\n MediaBinding,\n OperationBinding,\n OperationFileHint,\n OperationId,\n OperationParameter,\n OperationRequestBody,\n OperationResponseBody,\n type ParameterLocation,\n ServerInfo,\n ServerVariable,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst HTTP_METHODS: readonly HttpMethod[] = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n];\n\nconst VALID_PARAM_LOCATIONS = new Set<string>([\"path\", \"query\", \"header\", \"cookie\"]);\n\n// ---------------------------------------------------------------------------\n// Parameter extraction\n// ---------------------------------------------------------------------------\n\nconst extractParameters = (\n pathItem: PathItemObject,\n operation: OperationObject,\n r: DocResolver,\n): OperationParameter[] => {\n const merged = new Map<string, ParameterObject>();\n\n for (const raw of pathItem.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n for (const raw of operation.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n\n return [...merged.values()]\n .filter((p) => VALID_PARAM_LOCATIONS.has(p.in))\n .map((p) =>\n OperationParameter.make({\n name: p.name,\n location: p.in as ParameterLocation,\n required: p.in === \"path\" ? true : p.required === true,\n schema: Option.fromNullishOr(p.schema),\n style: Option.fromNullishOr(p.style),\n explode: Option.fromNullishOr(p.explode),\n allowReserved: Option.fromNullishOr(\"allowReserved\" in p ? p.allowReserved : undefined),\n description: Option.fromNullishOr(p.description),\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Request body extraction\n// ---------------------------------------------------------------------------\n\nconst buildEncodingRecord = (\n encoding: Record<string, unknown> | undefined,\n): Record<string, EncodingObject> | undefined => {\n if (!encoding) return undefined;\n const out: Record<string, EncodingObject> = {};\n for (const [prop, raw] of Object.entries(encoding)) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const e = raw as {\n contentType?: string;\n style?: string;\n explode?: boolean;\n allowReserved?: boolean;\n };\n out[prop] = EncodingObject.make({\n contentType: Option.fromNullishOr(e.contentType),\n style: Option.fromNullishOr(e.style),\n explode: Option.fromNullishOr(e.explode),\n allowReserved: Option.fromNullishOr(e.allowReserved),\n });\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst extractRequestBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationRequestBody | undefined => {\n if (!operation.requestBody) return undefined;\n\n const body = r.resolve<RequestBodyObject>(operation.requestBody);\n if (!body) return undefined;\n\n const contents = declaredContents(body.content).map(({ mediaType, media }) =>\n MediaBinding.make({\n contentType: mediaType,\n schema: Option.fromNullishOr(media.schema),\n encoding: Option.fromNullishOr(\n buildEncodingRecord((media as { encoding?: Record<string, unknown> }).encoding),\n ),\n }),\n );\n if (contents.length === 0) return undefined;\n\n // Default = first declared (spec author's preferred order). Callers can\n // override at invoke time with a `contentType` arg.\n const defaultContent = contents[0]!;\n\n return OperationRequestBody.make({\n required: body.required === true,\n contentType: defaultContent.contentType,\n schema: defaultContent.schema,\n contents: Option.some(contents),\n });\n};\n\n// ---------------------------------------------------------------------------\n// Response schema extraction\n// ---------------------------------------------------------------------------\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst stringType = (schema: Record<string, unknown>): boolean =>\n schema.type === \"string\" || (Array.isArray(schema.type) && schema.type.includes(\"string\"));\n\nconst numericType = (schema: Record<string, unknown>): boolean =>\n schema.type === \"integer\" ||\n schema.type === \"number\" ||\n (Array.isArray(schema.type) &&\n (schema.type.includes(\"integer\") || schema.type.includes(\"number\")));\n\nconst normalizedMediaType = (mediaType: string): string =>\n mediaType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\nconst isJsonMediaType = (mediaType: string): boolean => {\n const normalized = normalizedMediaType(mediaType);\n return (\n normalized === \"application/json\" || normalized.includes(\"+json\") || normalized.includes(\"json\")\n );\n};\n\nconst binaryStringSchema = (schema: Record<string, unknown>): boolean =>\n stringType(schema) && (schema.format === \"binary\" || schema.format === \"byte\");\n\nconst base64EncodingFromDescription = (schema: Record<string, unknown>): \"base64\" | \"base64url\" =>\n typeof schema.description === \"string\" &&\n /base64url|base64-url|url[- ]safe/i.test(schema.description)\n ? \"base64url\"\n : \"base64\";\n\nconst detectFileHint = (\n schema: unknown,\n mediaType: string,\n r: DocResolver,\n): OperationFileHint | undefined => {\n const resolved = isRecord(schema) ? r.resolve<Record<string, unknown>>(schema) : null;\n if (!resolved) return undefined;\n\n if (!isJsonMediaType(mediaType) && binaryStringSchema(resolved)) {\n return OperationFileHint.make({\n kind: \"binaryResponse\",\n mimeType: Option.some(mediaType),\n dataField: Option.none(),\n sizeField: Option.none(),\n encoding: Option.none(),\n });\n }\n\n if (!isJsonMediaType(mediaType)) return undefined;\n\n const properties = resolved.properties;\n if (!isRecord(properties)) return undefined;\n const data = properties.data;\n const dataSchema = isRecord(data) ? r.resolve<Record<string, unknown>>(data) : null;\n if (!dataSchema || !binaryStringSchema(dataSchema)) return undefined;\n\n const size = properties.size;\n const sizeSchema = isRecord(size) ? r.resolve<Record<string, unknown>>(size) : null;\n const sizeField = sizeSchema && numericType(sizeSchema) ? \"size\" : undefined;\n\n return OperationFileHint.make({\n kind: \"byteField\",\n mimeType: Option.some(\"application/octet-stream\"),\n dataField: Option.some(\"data\"),\n sizeField: sizeField ? Option.some(sizeField) : Option.none(),\n encoding: Option.some(base64EncodingFromDescription(dataSchema)),\n });\n};\n\nconst extractResponseBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationResponseBody | undefined => {\n if (!operation.responses) return undefined;\n\n // Success responses may use exact codes (\"200\"), the OpenAPI wildcard status\n // key (\"2XX\" — Microsoft Graph declares every success response this way), or\n // fall through to \"default\". Prefer exact codes, then the wildcard, then default.\n const entries = Object.entries(operation.responses);\n const preferred = [\n ...entries.filter(([s]) => /^2\\d\\d$/.test(s)).sort(([a], [b]) => a.localeCompare(b)),\n ...entries.filter(([s]) => /^2xx$/i.test(s)),\n ...entries.filter(([s]) => s === \"default\"),\n ];\n\n for (const [, ref] of preferred) {\n const resp = r.resolve<ResponseObject>(ref);\n if (!resp) continue;\n const content = preferredResponseContent(resp.content);\n if (content?.media.schema) {\n return OperationResponseBody.make({\n contentType: content.mediaType,\n schema: Option.some(content.media.schema),\n fileHint: Option.fromNullishOr(detectFileHint(content.media.schema, content.mediaType, r)),\n });\n }\n }\n\n return undefined;\n};\n\n/**\n * Derive an operation's output schema from its response body. NDJSON bodies\n * (`application/stream+json` and friends) are spec'd per LINE but returned by\n * the invoke path as an array of parsed lines, so the advertised schema wraps\n * the line schema in an array; otherwise describe previews promise a single\n * object that invocations never return. Used by both the whole-tree extract\n * and the serve path's stored-binding rebuild so the two stay in lockstep.\n */\nexport const outputSchemaFromResponseBody = (\n responseBody: OperationResponseBody,\n): unknown | undefined => {\n const schema = Option.getOrUndefined(responseBody.schema);\n if (schema === undefined) return undefined;\n return isNdjsonMediaType(responseBody.contentType) ? ndjsonArrayOutputSchema(schema) : schema;\n};\n\n// ---------------------------------------------------------------------------\n// Input schema builder\n// ---------------------------------------------------------------------------\n\n// Optional `server` input — host selection + server-URL variables. Undefined\n// when there's nothing to configure (a single server with no variables).\nconst buildServerInputProperty = (\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const variableDefs: Record<string, ServerVariable> = {};\n for (const server of servers) {\n for (const [name, v] of Object.entries(Option.getOrUndefined(server.variables) ?? {})) {\n if (!(name in variableDefs)) variableDefs[name] = v;\n }\n }\n const hasMultiple = servers.length > 1;\n const variableNames = Object.keys(variableDefs);\n if (!hasMultiple && variableNames.length === 0) return undefined;\n\n const properties: Record<string, unknown> = {};\n if (hasMultiple) {\n properties.url = {\n type: \"string\",\n enum: servers.map((server) => server.url),\n default: servers[0]!.url,\n description: \"Which of the spec's servers to send the request to.\",\n };\n }\n if (variableNames.length > 0) {\n properties.variables = {\n type: \"object\",\n additionalProperties: false,\n properties: Object.fromEntries(\n Object.entries(variableDefs).map(([name, v]) => [\n name,\n {\n type: \"string\",\n default: v.default,\n ...(Option.isSome(v.enum) ? { enum: v.enum.value } : {}),\n ...(Option.isSome(v.description) ? { description: v.description.value } : {}),\n },\n ]),\n ),\n description: \"Values for the server URL `{variables}`; spec defaults apply when omitted.\",\n };\n }\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n description: \"Optional host selection and server-URL variables for this request.\",\n };\n};\n\nexport const buildInputSchema = (\n parameters: readonly OperationParameter[],\n requestBody: OperationRequestBody | undefined,\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n let requiredBodyAlternatives: readonly { readonly required: readonly string[] }[] | undefined;\n\n for (const param of parameters) {\n properties[param.name] = Option.getOrElse(param.schema, () => ({ type: \"string\" }));\n if (param.required) required.push(param.name);\n }\n\n // A path/query parameter named `server` takes precedence over the host input.\n const serverProperty = buildServerInputProperty(servers);\n if (serverProperty && !(\"server\" in properties)) properties.server = serverProperty;\n\n if (requestBody) {\n // When the spec declares multiple media types for this requestBody,\n // expose `contentType` so the model can pick. Default = first declared.\n // For mixed bodies, `body` schema tracks the default; the model is\n // responsible for supplying a body shape that matches whichever\n // contentType it picks. Octet-only operations use `bodyBase64` instead.\n const contents = Option.getOrUndefined(requestBody.contents);\n const defaultIsOctetStream =\n requestBody.contentType.split(\";\")[0]?.trim().toLowerCase() === \"application/octet-stream\";\n const acceptsOctetStream =\n defaultIsOctetStream ||\n contents?.some(\n (content) =>\n content.contentType.split(\";\")[0]?.trim().toLowerCase() === \"application/octet-stream\",\n ) === true;\n const acceptsBody =\n !defaultIsOctetStream ||\n contents?.some(\n (content) =>\n content.contentType.split(\";\")[0]?.trim().toLowerCase() !== \"application/octet-stream\",\n ) === true;\n if (acceptsBody) {\n properties.body = Option.getOrElse(requestBody.schema, () => ({ type: \"object\" }));\n }\n if (acceptsOctetStream) {\n properties.bodyBase64 = {\n type: \"string\",\n contentEncoding: \"base64\",\n contentMediaType: \"application/octet-stream\",\n description:\n \"Base64-encoded bytes for application/octet-stream request bodies. When contentType is omitted, this selects application/octet-stream.\",\n };\n }\n if (requestBody.required) {\n if (acceptsOctetStream && acceptsBody) {\n requiredBodyAlternatives = [{ required: [\"body\"] }, { required: [\"bodyBase64\"] }];\n } else {\n required.push(acceptsOctetStream ? \"bodyBase64\" : \"body\");\n }\n }\n if (contents && contents.length > 1) {\n properties.contentType = {\n type: \"string\",\n enum: contents.map((c) => c.contentType),\n default: requestBody.contentType,\n description:\n \"Content-Type for the request body. Declared media types for this operation, in spec order.\",\n };\n }\n }\n\n if (Object.keys(properties).length === 0) return undefined;\n\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n ...(requiredBodyAlternatives ? { anyOf: requiredBodyAlternatives } : {}),\n additionalProperties: false,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Operation ID derivation\n// ---------------------------------------------------------------------------\n\nconst deriveOperationId = (\n method: HttpMethod,\n pathTemplate: string,\n operation: OperationObject,\n): string =>\n operation.operationId ??\n (`${method}_${pathTemplate.replace(/[^a-zA-Z0-9]+/g, \"_\")}`.replace(/^_+|_+$/g, \"\") ||\n `${method}_operation`);\n\nconst explicitToolPath = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-toolPath\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\nconst explicitPathTemplate = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-pathTemplate\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Server extraction\n// ---------------------------------------------------------------------------\n\nconst extractServerList = (servers: readonly ServerObject[] | undefined): ServerInfo[] =>\n (servers ?? []).flatMap((server) => {\n if (!server.url) return [];\n const serverVariables = server.variables as\n | Record<\n string,\n {\n readonly default?: string;\n readonly enum?: readonly string[];\n readonly description?: string;\n }\n >\n | undefined;\n const vars = serverVariables\n ? Object.fromEntries(\n Object.entries(serverVariables).flatMap(([name, v]) => {\n if (v.default === undefined || v.default === null) return [];\n const enumValues = Array.isArray(v.enum)\n ? v.enum.filter((x): x is string => typeof x === \"string\")\n : undefined;\n return [\n [\n name,\n ServerVariable.make({\n default: String(v.default),\n enum:\n enumValues && enumValues.length > 0 ? Option.some(enumValues) : Option.none(),\n description: Option.fromNullishOr(v.description),\n }),\n ],\n ];\n }),\n )\n : undefined;\n return [\n ServerInfo.make({\n url: server.url,\n description: Option.fromNullishOr(server.description),\n variables: vars && Object.keys(vars).length > 0 ? Option.some(vars) : Option.none(),\n }),\n ];\n });\n\nconst extractServers = (doc: ParsedDocument): ServerInfo[] => extractServerList(doc.servers);\n\nconst operationServers = (\n pathItem: PathItemObject,\n operation: OperationObject,\n docServers: readonly ServerInfo[],\n): readonly ServerInfo[] => {\n const operationLevel = extractServerList(operation.servers);\n if (operationLevel.length > 0) return operationLevel;\n const pathLevel = extractServerList(pathItem.servers);\n if (pathLevel.length > 0) return pathLevel;\n return docServers;\n};\n\n/** OAuth scope requirements an operation declares via `security`, with the\n * spec's semantics preserved (OpenAPI 3.x Security Requirement Objects):\n *\n * - Each requirement object is one acceptable ALTERNATIVE; the array is an\n * OR. Alternatives stay separate — unioning them would tell a user to\n * grant scopes from mutually alternative schemes at once.\n * - Within one requirement object the schemes are ANDed, so their scopes\n * union into that alternative's set (sorted, deduped).\n * - An ABSENT operation `security` inherits the document-level default;\n * an explicit `security: []` disables auth. Both yield `undefined` only\n * when nothing (or nothing scoped) is genuinely declared. */\nconst securityScopeAlternatives = (\n operation: OperationObject,\n documentSecurity: unknown,\n): readonly (readonly string[])[] | undefined => {\n const security = operation.security !== undefined ? operation.security : documentSecurity;\n if (!Array.isArray(security) || security.length === 0) return undefined;\n const alternatives: (readonly string[])[] = [];\n const seen = new Set<string>();\n for (const requirement of security) {\n if (requirement === null || typeof requirement !== \"object\") continue;\n const scopes = new Set<string>();\n for (const schemeScopes of Object.values(requirement)) {\n if (!Array.isArray(schemeScopes)) continue;\n for (const scope of schemeScopes) {\n if (typeof scope === \"string\" && scope.trim().length > 0) scopes.add(scope);\n }\n }\n if (scopes.size === 0) continue;\n const alternative = [...scopes].sort();\n const key = alternative.join(\" \");\n if (seen.has(key)) continue;\n seen.add(key);\n alternatives.push(alternative);\n }\n return alternatives.length > 0 ? alternatives : undefined;\n};\n\nconst documentSecurityOf = (doc: unknown): unknown =>\n doc !== null && typeof doc === \"object\" && !Array.isArray(doc)\n ? (doc as Record<string, unknown>).security\n : undefined;\n\n// ---------------------------------------------------------------------------\n// Main extraction\n// ---------------------------------------------------------------------------\n\n/** Extract all operations from a bundled OpenAPI 3.x document */\nexport const extract = Effect.fn(\"OpenApi.extract\")(function* (doc: ParsedDocument) {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const docServers = extractServers(doc);\n const operations: ExtractedOperation[] = [];\n\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const responseBody = extractResponseBody(operation, r);\n const servers = operationServers(pathItem, operation, docServers);\n const inputSchema = buildInputSchema(parameters, requestBody, servers);\n const outputSchema = responseBody ? outputSchemaFromResponseBody(responseBody) : undefined;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n const operationPathTemplate = explicitPathTemplate(operation) ?? pathTemplate;\n\n const requiredScopeAlternatives = securityScopeAlternatives(\n operation,\n documentSecurityOf(doc),\n );\n operations.push(\n ExtractedOperation.make({\n operationId: OperationId.make(deriveOperationId(method, pathTemplate, operation)),\n toolPath: Option.fromNullishOr(explicitToolPath(operation)),\n method,\n servers,\n pathTemplate: operationPathTemplate,\n summary: Option.fromNullishOr(operation.summary),\n description: Option.fromNullishOr(operation.description),\n tags,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n inputSchema: Option.fromNullishOr(inputSchema),\n outputSchema: Option.fromNullishOr(outputSchema),\n deprecated: operation.deprecated === true,\n ...(requiredScopeAlternatives ? { requiredScopeAlternatives } : {}),\n }),\n );\n }\n }\n\n return ExtractionResult.make({\n title: Option.fromNullishOr(doc.info?.title),\n description: Option.fromNullishOr(doc.info?.description),\n version: Option.fromNullishOr(doc.info?.version),\n servers: docServers,\n operations,\n });\n});\n\n// ---------------------------------------------------------------------------\n// Streaming binding extraction\n// ---------------------------------------------------------------------------\n\n/** One persisted invocation binding plus the tool name and description it\n * backs. The description is the resolved operation description / summary /\n * method+path fallback, persisted so the serve path needs no re-parse. */\nexport interface OperationBindingChunk {\n readonly toolName: string;\n readonly description: string;\n readonly binding: OperationBinding;\n}\n\ninterface OperationRef {\n readonly pathItem: PathItemObject;\n readonly operation: OperationObject;\n readonly method: HttpMethod;\n /** Resolved path template (`x-executor-pathTemplate` override or the key). */\n readonly pathTemplate: string;\n}\n\n/**\n * Stream invocation bindings out of a parsed document in bounded chunks,\n * persisting each chunk via `onChunk` before building the next.\n *\n * This is the memory-safe compile path for huge specs (e.g. Microsoft Graph,\n * 16.5k operations / 37MB). It differs from `extract` + `compileToolDefinitions`\n * in two ways that keep peak memory at parse level rather than ~doubling it:\n *\n * 1. It never builds `hoistedDefs` or per-operation `inputSchema`/`outputSchema`\n * (the add path only needs invocation bindings, which carry `$ref`s, not\n * inlined schemas).\n * 2. It never holds all bindings at once. Tool-path planning needs a global\n * view, but only of lightweight metadata (`planToolPaths`, schema-free);\n * the heavy per-operation bindings are built, flushed, and dropped one\n * chunk at a time.\n *\n * Bindings reference subtrees of the parsed document rather than copying them,\n * so `onChunk` must sever those references (its storage layer JSON-serializes\n * the binding) before the chunk is dropped. Returns the resolved tool names in\n * sorted order, matching `compileToolDefinitions`.\n */\nexport const streamOperationBindings = <E, R>(\n doc: ParsedDocument,\n chunkSize: number,\n onChunk: (chunk: readonly OperationBindingChunk[]) => Effect.Effect<void, E, R>,\n): Effect.Effect<\n { readonly toolCount: number; readonly toolNames: readonly string[] },\n OpenApiExtractionError | E,\n R\n> =>\n Effect.gen(function* () {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const docServers = extractServers(doc);\n\n // Pass 1 (light): collect schema-free path metadata + a parallel array of\n // references back into the tree. Both are small (no schemas copied).\n const inputs: OperationPathInput[] = [];\n const opRefs: OperationRef[] = [];\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? pathTemplate;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n inputs.push({\n operationId: deriveOperationId(method, pathTemplate, operation),\n explicitToolPath: explicitToolPath(operation),\n method,\n pathTemplate: resolvedPathTemplate,\n tag0: tags[0],\n });\n opRefs.push({ pathItem, operation, method, pathTemplate: resolvedPathTemplate });\n }\n }\n\n // Global, schema-free collision resolution + sort. Cheap relative to the\n // parsed tree; returns plans sorted by toolPath with an index back into\n // `opRefs`.\n const plans = planToolPaths(inputs);\n\n // Pass 2 (heavy, streamed): build a binding per operation, flush a chunk\n // once it fills, then drop it. Bindings reference tree subtrees; `onChunk`\n // serializes them, so peak stays at parse level.\n let chunk: OperationBindingChunk[] = [];\n for (const plan of plans) {\n const ref = opRefs[plan.operationIndex]!;\n const parameters = extractParameters(ref.pathItem, ref.operation, r);\n const requestBody = extractRequestBody(ref.operation, r);\n const responseBody = extractResponseBody(ref.operation, r);\n const servers = operationServers(ref.pathItem, ref.operation, docServers);\n const requiredScopeAlternatives = securityScopeAlternatives(\n ref.operation,\n documentSecurityOf(doc),\n );\n chunk.push({\n toolName: plan.toolPath,\n description:\n ref.operation.description ??\n ref.operation.summary ??\n `${ref.method.toUpperCase()} ${ref.pathTemplate}`,\n binding: OperationBinding.make({\n method: ref.method,\n servers,\n pathTemplate: ref.pathTemplate,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n ...(requiredScopeAlternatives ? { requiredScopeAlternatives } : {}),\n }),\n });\n if (chunk.length >= chunkSize) {\n yield* onChunk(chunk);\n chunk = [];\n }\n }\n if (chunk.length > 0) yield* onChunk(chunk);\n\n return { toolCount: plans.length, toolNames: plans.map((plan) => plan.toolPath) };\n }).pipe(Effect.withSpan(\"OpenApi.streamOperationBindings\"));\n\nconst isPathItemValue = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Stream invocation bindings straight from a `SpecStructure` (the structural\n * split of a large spec) without ever materializing the whole-document tree.\n *\n * This is the fully-streaming compile path: it never parses the spec whole.\n * Each path-item is parsed in isolation twice (pass 1 for light tool-path\n * planning metadata, pass 2 to build the heavy binding) and discarded, so peak\n * memory stays near the size of a single path-item plus the raw text, even for\n * the 37MB / 16.5k-operation Microsoft Graph spec that OOMs a whole-tree parse.\n * Re-parsing in pass 2 (rather than holding pass-1 tree references) is the\n * deliberate CPU-for-memory trade that keeps peak at one-path-item level.\n *\n * `keepPathItem`, when given, filters (and may trim) each path-item, so the same\n * primitive serves both a full-spec compile (no filter) and a selection (e.g.\n * the Microsoft Graph scope filter) with identical streaming guarantees. It is\n * applied identically in both passes so the per-operation index stays aligned.\n *\n * Schemas are never resolved here: parameter / requestBody / response component\n * `$ref`s resolve against the small (schema-free) components built from the\n * structure; `#/components/schemas/X` refs stay as strings in the binding and\n * are normalized + served from the content-addressed defs blob. Returns the\n * resolved tool names in sorted order, matching `compileToolDefinitions`.\n */\nexport const streamOperationBindingsFromStructure = <E, R>(\n structure: SpecStructure,\n options: { readonly chunkSize: number; readonly keepPathItem?: KeepPathItem },\n onChunk: (chunk: readonly OperationBindingChunk[]) => Effect.Effect<void, E, R>,\n): Effect.Effect<{ readonly toolCount: number; readonly toolNames: readonly string[] }, E, R> =>\n Effect.gen(function* () {\n const { chunkSize, keepPathItem } = options;\n\n // Parse one path-item range to its kept (optionally trimmed) value, applying\n // `keepPathItem` identically in both passes so the operation index aligns.\n const keptPathItem = (range: ByteRange): readonly [string, PathItemObject] | null => {\n const entry = parseEntry(structure.text, range, 2);\n if (!entry) return null;\n const [path, rawValue] = entry;\n if (!isPathItemValue(rawValue)) return null;\n if (!keepPathItem) return [path, rawValue as PathItemObject];\n const kept = keepPathItem(path, rawValue);\n return kept ? [path, kept as PathItemObject] : null;\n };\n\n // Pass 1 (light): collect schema-free tool-path planning metadata in\n // document order. No bindings, no schemas; one path-item resident at a time.\n const inputs: OperationPathInput[] = [];\n for (const range of structure.pathItems) {\n const kept = keptPathItem(range);\n if (!kept) continue;\n const [path, pathItem] = kept;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? path;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n inputs.push({\n operationId: deriveOperationId(method, path, operation),\n explicitToolPath: explicitToolPath(operation),\n method,\n pathTemplate: resolvedPathTemplate,\n tag0: tags[0],\n });\n }\n }\n\n // Global, schema-free collision resolution + sort. `plan.operationIndex`\n // indexes back into `inputs` (document order), so a flat array recovers each\n // operation's assigned tool path during the document-order pass 2.\n const plans = planToolPaths(inputs);\n const planByOpIndex: (PlannedToolPath | undefined)[] = new Array(inputs.length);\n for (const plan of plans) planByOpIndex[plan.operationIndex] = plan;\n\n // Pass 2 (heavy, streamed): re-parse each path-item in the same document\n // order, build a binding per operation, flush a chunk once it fills, then\n // drop it. The resolver is schema-free (small components only); schema refs\n // stay as `$ref` strings in the bindings.\n // oxlint-disable-next-line executor/no-double-cast -- boundary: parseHead/parseSmallComponents return Record<string, unknown>, which does not structurally match the OpenAPIV3 Document union; the schema-free resolver doc (head + small components, empty paths) is only read for .servers (extractServers) and .components ($ref resolution).\n const resolverDoc = {\n ...parseHead(structure),\n paths: {},\n components: parseSmallComponents(structure),\n } as unknown as ParsedDocument;\n const r = new DocResolver(resolverDoc);\n const docServers = extractServers(resolverDoc);\n\n let opIndex = 0;\n let chunk: OperationBindingChunk[] = [];\n for (const range of structure.pathItems) {\n const kept = keptPathItem(range);\n if (!kept) continue;\n const [path, pathItem] = kept;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const plan = planByOpIndex[opIndex];\n opIndex += 1;\n if (!plan) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? path;\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const responseBody = extractResponseBody(operation, r);\n const servers = operationServers(pathItem, operation, docServers);\n const requiredScopeAlternatives = securityScopeAlternatives(\n operation,\n documentSecurityOf(resolverDoc),\n );\n chunk.push({\n toolName: plan.toolPath,\n description:\n operation.description ??\n operation.summary ??\n `${method.toUpperCase()} ${resolvedPathTemplate}`,\n binding: OperationBinding.make({\n method,\n servers,\n pathTemplate: resolvedPathTemplate,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n ...(requiredScopeAlternatives ? { requiredScopeAlternatives } : {}),\n }),\n });\n if (chunk.length >= chunkSize) {\n yield* onChunk(chunk);\n chunk = [];\n }\n }\n }\n if (chunk.length > 0) yield* onChunk(chunk);\n\n return { toolCount: plans.length, toolNames: plans.map((plan) => plan.toolPath) };\n }).pipe(Effect.withSpan(\"OpenApi.streamOperationBindingsFromStructure\"));\n","/**\n * Derives structured `group.leaf` tool paths from extracted OpenAPI operations.\n *\n * Ported from the v3 executor's `definitions.ts`. Turns flat operation IDs like\n * `zones_listZones` into nested paths like `zones.listZones` that the tree UI\n * can render with proper nesting.\n */\n\nimport { Option } from \"effect\";\n\nimport type { ExtractedOperation } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Word / case utilities\n// ---------------------------------------------------------------------------\n\nconst splitWords = (value: string): string[] =>\n value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, \"$1 $2\")\n .replace(/[^a-zA-Z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n\nconst normalizeWord = (value: string): string => value.toLowerCase();\n\nconst toCamelCase = (value: string): string => {\n const words = splitWords(value).map(normalizeWord);\n if (words.length === 0) return \"tool\";\n const [first, ...rest] = words;\n return `${first}${rest.map((p) => `${p[0]?.toUpperCase() ?? \"\"}${p.slice(1)}`).join(\"\")}`;\n};\n\nconst toPascalCase = (value: string): string => {\n const camel = toCamelCase(value);\n return `${camel[0]?.toUpperCase() ?? \"\"}${camel.slice(1)}`;\n};\n\n// ---------------------------------------------------------------------------\n// Path utilities\n// ---------------------------------------------------------------------------\n\nconst VERSION_SEGMENT_REGEX = /^v\\d+(?:[._-]\\d+)?$/i;\nconst IGNORED_PATH_SEGMENTS = new Set([\"api\"]);\n\nconst pathSegmentsFromTemplate = (pathTemplate: string): string[] =>\n pathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst isPathParameterSegment = (segment: string): boolean =>\n segment.startsWith(\"{\") && segment.endsWith(\"}\");\n\nconst normalizeGroupSegment = (value: string | undefined): string | null => {\n const candidate = value?.trim();\n if (!candidate) return null;\n return toCamelCase(candidate);\n};\n\n// ---------------------------------------------------------------------------\n// Derivation\n// ---------------------------------------------------------------------------\n\nconst deriveVersionSegment = (pathTemplate: string): string | undefined =>\n pathSegmentsFromTemplate(pathTemplate)\n .map((s) => s.toLowerCase())\n .find((s) => VERSION_SEGMENT_REGEX.test(s));\n\nconst derivePathGroup = (pathTemplate: string): string => {\n for (const segment of pathSegmentsFromTemplate(pathTemplate)) {\n const lower = segment.toLowerCase();\n if (VERSION_SEGMENT_REGEX.test(lower)) continue;\n if (IGNORED_PATH_SEGMENTS.has(lower)) continue;\n if (isPathParameterSegment(segment)) continue;\n return normalizeGroupSegment(segment) ?? \"root\";\n }\n return \"root\";\n};\n\nconst splitOperationIdSegments = (value: string): string[] =>\n value\n .split(/[/.]+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst deriveLeafSeed = (operationId: string, group: string): string => {\n const segments = splitOperationIdSegments(operationId);\n if (segments.length > 1) {\n const [first, ...rest] = segments;\n if ((normalizeGroupSegment(first) ?? first) === group && rest.length > 0) {\n return rest.join(\" \");\n }\n }\n return operationId;\n};\n\nconst fallbackLeafSeed = (method: string, pathTemplate: string, group: string): string => {\n const relevantSegments = pathSegmentsFromTemplate(pathTemplate)\n .filter((s) => !VERSION_SEGMENT_REGEX.test(s.toLowerCase()))\n .filter((s) => !IGNORED_PATH_SEGMENTS.has(s.toLowerCase()))\n .filter((s) => !isPathParameterSegment(s))\n .map((s) => normalizeGroupSegment(s) ?? s)\n .filter((s) => s !== group);\n\n const segmentSuffix = relevantSegments.map((s) => toPascalCase(s)).join(\"\");\n return `${method}${segmentSuffix || \"Operation\"}`;\n};\n\nconst deriveLeaf = (\n operationId: string,\n method: string,\n pathTemplate: string,\n group: string,\n): string => {\n const preferred = toCamelCase(deriveLeafSeed(operationId, group));\n if (preferred.length > 0 && preferred !== group) return preferred;\n return toCamelCase(fallbackLeafSeed(method, pathTemplate, group));\n};\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface ToolDefinition {\n /** Dot-separated path like `zones.listZones` */\n readonly toolPath: string;\n /** The group segment */\n readonly group: string;\n /** The leaf segment */\n readonly leaf: string;\n /** Index into the original operations array */\n readonly operationIndex: number;\n /** The original operation */\n readonly operation: ExtractedOperation;\n}\n\n/**\n * The minimal per-operation metadata the tool-path planner needs. Kept\n * deliberately light (no schemas) so the streaming compile path can plan paths\n * for tens of thousands of operations without holding the full extracted\n * operations in memory.\n */\nexport interface OperationPathInput {\n readonly operationId: string;\n readonly explicitToolPath: string | undefined;\n readonly method: string;\n readonly pathTemplate: string;\n /** The first non-empty tag, used to seed the group segment. */\n readonly tag0: string | undefined;\n}\n\n/** A resolved tool path plus its index back into the input operations array. */\nexport interface PlannedToolPath {\n readonly toolPath: string;\n readonly group: string;\n readonly leaf: string;\n readonly operationIndex: number;\n}\n\n// ---------------------------------------------------------------------------\n// Collision resolution\n// ---------------------------------------------------------------------------\n\ninterface RawToolPath {\n toolPath: string;\n group: string;\n leaf: string;\n versionSegment: string | undefined;\n method: string;\n operationHash: string;\n operationIndex: number;\n}\n\nconst resolveCollisions = (definitions: RawToolPath[]): PlannedToolPath[] => {\n // Mutable — we progressively refine toolPath on collision\n const staged = definitions.map((d) => ({ ...d }));\n\n const applyFactory = (items: typeof staged, factory: (d: (typeof staged)[number]) => string) => {\n const byPath = new Map<string, typeof staged>();\n for (const item of items) {\n const bucket = byPath.get(item.toolPath) ?? [];\n bucket.push(item);\n byPath.set(item.toolPath, bucket);\n }\n for (const bucket of byPath.values()) {\n if (bucket.length < 2) continue;\n for (const d of bucket) {\n d.toolPath = factory(d);\n }\n }\n };\n\n // Round 1: add version segment\n applyFactory(staged, (d) =>\n d.versionSegment ? `${d.group}.${d.versionSegment}.${d.leaf}` : d.toolPath,\n );\n\n // Round 2: add method suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}`;\n });\n\n // Round 3: add hash suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}${d.operationHash.slice(0, 8)}`;\n });\n\n return staged.map((d) => ({\n toolPath: d.toolPath,\n group: d.group,\n leaf: d.leaf,\n operationIndex: d.operationIndex,\n }));\n};\n\n// ---------------------------------------------------------------------------\n// Stable hash (simple, deterministic)\n// ---------------------------------------------------------------------------\n\nconst stableHash = (value: unknown): string => {\n const str = JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort());\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;\n }\n return Math.abs(hash).toString(36).padStart(8, \"0\");\n};\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Plan structured `group.leaf` tool paths from lightweight per-operation\n * metadata. Path derivation + collision resolution need a global view of every\n * operation, but only its name/method/path/tag, never its schemas. Keeping this\n * pass schema-free lets the streaming compile path plan paths for a 16k-op spec\n * without materializing the full extracted operations.\n *\n * The returned `operationIndex` points back into the `inputs` array.\n */\nexport const planToolPaths = (inputs: readonly OperationPathInput[]): PlannedToolPath[] => {\n const raw: RawToolPath[] = inputs.map((op, index) => {\n const operationId = op.operationId;\n const operationHash = stableHash({\n method: op.method,\n path: op.pathTemplate,\n operationId,\n });\n const versionSegment = deriveVersionSegment(op.pathTemplate);\n\n if (op.explicitToolPath) {\n const [group = \"root\", ...leafParts] = op.explicitToolPath.split(\".\").filter(Boolean);\n const leaf = leafParts.join(\".\") || group;\n return {\n toolPath: op.explicitToolPath,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n };\n }\n\n const group = normalizeGroupSegment(op.tag0) ?? derivePathGroup(op.pathTemplate);\n const leaf = deriveLeaf(operationId, op.method, op.pathTemplate, group);\n return {\n toolPath: `${group}.${leaf}`,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n };\n });\n\n return resolveCollisions(raw).sort((a, b) => a.toolPath.localeCompare(b.toolPath));\n};\n\n/**\n * Compile extracted operations into tool definitions with structured\n * `group.leaf` paths suitable for tree rendering. Thin wrapper over\n * `planToolPaths` that re-attaches each operation by index.\n */\nexport const compileToolDefinitions = (\n operations: readonly ExtractedOperation[],\n): ToolDefinition[] => {\n const plans = planToolPaths(\n operations.map((op) => ({\n operationId: op.operationId,\n explicitToolPath: Option.getOrUndefined(op.toolPath),\n method: op.method,\n pathTemplate: op.pathTemplate,\n tag0: op.tags[0],\n })),\n );\n\n return plans.map((plan) => ({\n toolPath: plan.toolPath,\n group: plan.group,\n leaf: plan.leaf,\n operationIndex: plan.operationIndex,\n operation: operations[plan.operationIndex]!,\n }));\n};\n","import { Effect, Exit, Fiber, Layer, Option, Schema, Stream } from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\";\nimport type { ToolFileValue } from \"@rafads/sdk/core\";\n\nimport { OpenApiInvocationError } from \"./errors\";\nimport { isNdjsonMediaType, NDJSON_MEDIA_TYPES, resolveServerUrl } from \"./openapi-utils\";\nimport {\n type EncodingObject,\n type OperationFileHint,\n type OperationBinding,\n InvocationResult,\n type MediaBinding,\n type OperationParameter,\n type ServerInfo,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Parameter reading\n// ---------------------------------------------------------------------------\n\nconst CONTAINER_KEYS: Record<string, readonly string[]> = {\n path: [\"path\", \"pathParams\", \"params\"],\n query: [\"query\", \"queryParams\", \"params\"],\n header: [\"headers\", \"header\"],\n cookie: [\"cookies\", \"cookie\"],\n};\n\nconst readParamValue = (args: Record<string, unknown>, param: OperationParameter): unknown => {\n const direct = args[param.name];\n if (direct !== undefined) return direct;\n\n for (const key of CONTAINER_KEYS[param.location] ?? []) {\n const container = args[key];\n if (typeof container === \"object\" && container !== null && !Array.isArray(container)) {\n const nested = (container as Record<string, unknown>)[param.name];\n if (nested !== undefined) return nested;\n }\n }\n\n return undefined;\n};\n\nconst primitiveToString = (value: unknown): string =>\n typeof value === \"object\" && value !== null ? JSON.stringify(value) : String(value);\n\n// RFC 3986 §2.2 reserved chars. `allowReserved: true` leaves these\n// unencoded; default OAS behavior encodes everything non-unreserved.\nconst RESERVED_UNENCODED_RE = /[A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]/;\n\nconst encodeReservedAware = (raw: string, allowReserved: boolean): string => {\n if (!allowReserved) return encodeURIComponent(raw);\n // Walk char-by-char so the reserved set passes through as-is.\n let out = \"\";\n for (const ch of raw) {\n out += RESERVED_UNENCODED_RE.test(ch) ? ch : encodeURIComponent(ch);\n }\n return out;\n};\n\nconst queryParamValues = (value: unknown, param: OperationParameter): string[] => {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) return [primitiveToString(value)];\n\n const style = Option.getOrUndefined(param.style) ?? \"form\";\n const explode = Option.getOrElse(param.explode, () => true);\n\n if (explode) return value.map(primitiveToString);\n\n const separator = style === \"spaceDelimited\" ? \" \" : style === \"pipeDelimited\" ? \"|\" : \",\";\n return [value.map(primitiveToString).join(separator)];\n};\n\n// ---------------------------------------------------------------------------\n// Path resolution\n// ---------------------------------------------------------------------------\n\nconst resolvePath = Effect.fn(\"OpenApi.resolvePath\")(function* (\n pathTemplate: string,\n args: Record<string, unknown>,\n parameters: readonly OperationParameter[],\n) {\n let resolved = pathTemplate;\n\n for (const param of parameters) {\n if (param.location !== \"path\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) {\n if (param.required) {\n return yield* new OpenApiInvocationError({\n message: `Missing required path parameter: ${param.name}`,\n statusCode: Option.none(),\n });\n }\n continue;\n }\n const encoded = encodeReservedAware(\n String(value),\n Option.getOrElse(param.allowReserved, () => false),\n );\n resolved = resolved.replaceAll(`{${param.name}}`, encoded);\n resolved = resolved.replaceAll(`{+${param.name}}`, encoded);\n }\n\n const remaining = [...resolved.matchAll(/\\{([^{}]+)\\}/g)]\n .map((m) => m[1])\n .filter((v): v is string => typeof v === \"string\");\n\n for (const name of remaining) {\n const value = args[name];\n if (value !== undefined && value !== null) {\n resolved = resolved.replaceAll(`{${name}}`, encodeURIComponent(String(value)));\n }\n }\n\n const unresolved = [...resolved.matchAll(/\\{([^{}]+)\\}/g)]\n .map((m) => m[1])\n .filter((v): v is string => typeof v === \"string\");\n\n if (unresolved.length > 0) {\n return yield* new OpenApiInvocationError({\n message: `Unresolved path parameters: ${[...new Set(unresolved)].join(\", \")}`,\n statusCode: Option.none(),\n });\n }\n\n return resolved;\n});\n\n// GitHub (and some other upstreams) reject requests that lack a User-Agent\n// header with a 403 (\"Request forbidden by administrative rules\"), which is\n// indistinguishable from a credential rejection downstream. Send a default so\n// those calls succeed. It is applied before operation header params and\n// resolved auth headers, so a spec- or connection-provided User-Agent wins.\nconst DEFAULT_USER_AGENT = \"executor\";\n\nconst applyHeaders = (\n request: HttpClientRequest.HttpClientRequest,\n headers: Record<string, string>,\n): HttpClientRequest.HttpClientRequest => {\n let req = request;\n for (const [name, value] of Object.entries(headers)) {\n req = HttpClientRequest.setHeader(req, name, value);\n }\n return req;\n};\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nconst normalizeContentType = (ct: string | null | undefined): string =>\n ct?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\nexport const STREAM_MAX_BYTES = 1_000_000;\nexport const STREAM_MAX_MS = 10_000;\n// Below Cloudflare's ~125s subrequest limit so cloud fails first with an\n// actionable error, but above the slowest legitimate buffered upstreams\n// observed in production (30d telemetry: successful calls cluster under\n// 110s; a 60s cap would have broken ~40 real calls).\nexport const RESPONSE_HEADERS_TIMEOUT_MS = 110_000;\n\nclass StreamCapReached extends Error {\n readonly _tag = \"StreamCapReached\";\n}\n\nexport interface StreamingResponseCaps {\n readonly maxBytes?: number;\n readonly maxMs?: number;\n}\n\nexport interface InvokeOptions {\n readonly responseHeadersTimeoutMs?: number;\n}\n\nconst formatTimeout = (timeoutMs: number): string =>\n timeoutMs % 1_000 === 0 ? `${timeoutMs / 1_000}s` : `${timeoutMs}ms`;\n\nconst responseHeadersTimeoutMessage = (timeoutMs: number): string =>\n `Upstream returned no response headers within ${formatTimeout(timeoutMs)}. The endpoint may be a live stream with no data to send (for example, runtime logs of an idle deployment); the request was aborted. Retry when the resource has activity, or use a non-streaming endpoint.`;\n\nconst STREAMING_RESPONSE_CONTENT_TYPES = new Set([...NDJSON_MEDIA_TYPES, \"text/event-stream\"]);\n\nconst isStreamingResponseContentType = (ct: string | null | undefined): boolean =>\n STREAMING_RESPONSE_CONTENT_TYPES.has(normalizeContentType(ct));\n\nconst isJsonContentType = (ct: string | null | undefined): boolean => {\n const normalized = normalizeContentType(ct);\n if (!normalized) return false;\n return (\n normalized === \"application/json\" || normalized.includes(\"+json\") || normalized.includes(\"json\")\n );\n};\n\nconst isFormUrlEncoded = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct) === \"application/x-www-form-urlencoded\";\n\nconst isMultipartFormData = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct).startsWith(\"multipart/form-data\");\n\nconst isXmlContentType = (ct: string | null | undefined): boolean => {\n const normalized = normalizeContentType(ct);\n if (!normalized) return false;\n return (\n normalized === \"application/xml\" || normalized === \"text/xml\" || normalized.endsWith(\"+xml\")\n );\n};\n\nconst isTextContentType = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct).startsWith(\"text/\");\n\nconst isOctetStream = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct) === \"application/octet-stream\";\n\nconst decodeJsonLine = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\n\nconst parseStreamingJsonLines = (text: string, truncated: boolean): unknown => {\n const lines = text.split(/\\r?\\n/);\n let lastNonEmptyIndex = -1;\n for (let index = lines.length - 1; index >= 0; index--) {\n const line = lines[index];\n if (line !== undefined && line.trim() !== \"\") {\n lastNonEmptyIndex = index;\n break;\n }\n }\n const rows: unknown[] = [];\n\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index];\n if (line === undefined || line.trim() === \"\") continue;\n const parsed = decodeJsonLine(line);\n if (Exit.isSuccess(parsed)) {\n rows.push(parsed.value);\n continue;\n }\n // A trailing fragment cut mid-line by the byte/time cap is expected; any\n // other unparseable line means the body is not NDJSON after all.\n if (truncated && index === lastNonEmptyIndex) continue;\n return text;\n }\n\n return rows;\n};\n\nconst decodeStreamingResponseBody = (\n contentType: string | null,\n text: string,\n truncated: boolean,\n): unknown => (isNdjsonMediaType(contentType) ? parseStreamingJsonLines(text, truncated) : text);\n\nexport const collectStreamingBody = (\n stream: Stream.Stream<Uint8Array, unknown, never>,\n contentType: string | null,\n caps: StreamingResponseCaps = {},\n) =>\n Effect.gen(function* () {\n const maxBytes = caps.maxBytes ?? STREAM_MAX_BYTES;\n const maxMs = caps.maxMs ?? STREAM_MAX_MS;\n const chunks: Uint8Array[] = [];\n let bytes = 0;\n let truncated = false;\n const startedAt = Date.now();\n\n const runFork = Effect.runForkWith(yield* Effect.context<never>());\n const completedExitOption = yield* Effect.callback<Option.Option<Exit.Exit<void, unknown>>>(\n (resume, signal) => {\n let settled = false;\n const collectEffect = stream.pipe(\n Stream.timeout(maxMs),\n Stream.runForEach((chunk) =>\n Effect.gen(function* () {\n const remaining = maxBytes - bytes;\n if (remaining <= 0) {\n truncated = true;\n return yield* Effect.fail(new StreamCapReached());\n }\n\n if (chunk.byteLength > remaining) {\n chunks.push(chunk.subarray(0, remaining));\n bytes += remaining;\n truncated = true;\n return yield* Effect.fail(new StreamCapReached());\n }\n\n chunks.push(chunk);\n bytes += chunk.byteLength;\n if (bytes >= maxBytes) {\n truncated = true;\n return yield* Effect.fail(new StreamCapReached());\n }\n }),\n ),\n Effect.catch((error: unknown) =>\n error instanceof StreamCapReached ? Effect.void : Effect.fail(error),\n ),\n Effect.exit,\n Effect.tap((exit) =>\n Effect.sync(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resume(Effect.succeed(Option.some(exit)));\n }),\n ),\n );\n const fiber = runFork(collectEffect);\n const interrupt = () => {\n runFork(Fiber.interrupt(fiber));\n };\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n truncated = true;\n interrupt();\n resume(Effect.succeed(Option.none()));\n }, maxMs + 1_000);\n signal.addEventListener(\"abort\", interrupt, { once: true });\n return Effect.sync(() => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", interrupt);\n if (!settled) interrupt();\n });\n },\n );\n if (Option.isSome(completedExitOption) && Exit.isFailure(completedExitOption.value)) {\n return yield* Effect.failCause(completedExitOption.value.cause);\n }\n if (Option.isNone(completedExitOption)) truncated = true;\n\n const durationMs = Date.now() - startedAt;\n if (durationMs >= maxMs) truncated = true;\n const collected = new Uint8Array(bytes);\n let offset = 0;\n for (const chunk of chunks) {\n collected.set(chunk, offset);\n offset += chunk.byteLength;\n }\n const text = new TextDecoder(\"utf-8\").decode(collected);\n\n return {\n data: decodeStreamingResponseBody(contentType, text, truncated),\n headers: {\n \"x-executor-stream\": truncated ? \"truncated\" : \"complete\",\n \"x-executor-stream-bytes\": String(bytes),\n \"x-executor-stream-duration-ms\": String(durationMs),\n },\n };\n });\n\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n};\n\nconst normalizeBase64 = (value: string, encoding: \"base64\" | \"base64url\"): string => {\n const compact = value.replace(/\\s/g, \"\");\n const alphabet =\n encoding === \"base64url\" ? compact.replace(/-/g, \"+\").replace(/_/g, \"/\") : compact;\n const remainder = alphabet.length % 4;\n return remainder === 0 ? alphabet : `${alphabet}${\"=\".repeat(4 - remainder)}`;\n};\n\nconst byteLengthFromBase64 = (base64: string): number => {\n const compact = base64.replace(/\\s/g, \"\");\n const padding = compact.endsWith(\"==\") ? 2 : compact.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, Math.floor((compact.length * 3) / 4) - padding);\n};\n\nconst isGenericMimeType = (mimeType: string): boolean =>\n normalizeContentType(mimeType) === \"application/octet-stream\";\n\nconst startsWithBytes = (bytes: Uint8Array, prefix: readonly number[]): boolean =>\n prefix.every((byte, index) => bytes[index] === byte);\n\nconst isLikelyUtf8Text = (bytes: Uint8Array): boolean => {\n if (bytes.length === 0) return false;\n let text: string;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: TextDecoder throws while probing arbitrary binary content\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return false;\n }\n let suspicious = 0;\n for (let index = 0; index < text.length; index += 1) {\n const code = text.charCodeAt(index);\n const allowedControl = code === 0x09 || code === 0x0a || code === 0x0c || code === 0x0d;\n if (code === 0x00) return false;\n if (code < 0x20 && !allowedControl) suspicious += 1;\n }\n return suspicious / Math.max(1, text.length) <= 0.02;\n};\n\nconst sniffMimeType = (bytes: Uint8Array): string | null => {\n if (startsWithBytes(bytes, [0xff, 0xd8, 0xff])) return \"image/jpeg\";\n if (startsWithBytes(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n if (\n startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]) ||\n startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38, 0x39, 0x61])\n ) {\n return \"image/gif\";\n }\n if (\n startsWithBytes(bytes, [0x52, 0x49, 0x46, 0x46]) &&\n bytes[8] === 0x57 &&\n bytes[9] === 0x45 &&\n bytes[10] === 0x42 &&\n bytes[11] === 0x50\n ) {\n return \"image/webp\";\n }\n if (startsWithBytes(bytes, [0x25, 0x50, 0x44, 0x46, 0x2d])) return \"application/pdf\";\n if (\n startsWithBytes(bytes, [0x50, 0x4b, 0x03, 0x04]) ||\n startsWithBytes(bytes, [0x50, 0x4b, 0x05, 0x06]) ||\n startsWithBytes(bytes, [0x50, 0x4b, 0x07, 0x08])\n ) {\n return \"application/zip\";\n }\n if (isLikelyUtf8Text(bytes)) return \"text/plain\";\n return null;\n};\n\nconst bytesFromBase64Prefix = (base64: string): Uint8Array => {\n const prefix = base64.slice(0, Math.min(base64.length, 64));\n const binary = atob(prefix);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n};\n\nconst sniffMimeTypeFromBase64 = (base64: string): string | null =>\n sniffMimeType(bytesFromBase64Prefix(base64));\n\ntype DecodedBase64Body = { readonly ok: true; readonly bytes: Uint8Array } | { readonly ok: false };\n\nconst base64ToUint8Array = (value: string): Uint8Array | null => {\n let binary = \"\";\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: atob throws for invalid base64; invalid shapes are treated as non-byte input\n try {\n binary = atob(normalizeBase64(value, \"base64\"));\n } catch {\n return null;\n }\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n};\n\nconst decodeBase64Body = (value: string): DecodedBase64Body => {\n const bytes = base64ToUint8Array(value);\n return bytes ? { ok: true, bytes } : { ok: false };\n};\n\nconst toUint8Array = (value: unknown): Uint8Array | null => {\n if (value instanceof Uint8Array) return value;\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n if (Array.isArray(value) && value.every((v) => typeof v === \"number\")) {\n return new Uint8Array(value as readonly number[]);\n }\n return null;\n};\n\nconst readNestedBodyBase64 = (value: unknown): unknown =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.hasOwnProperty.call(value, \"bodyBase64\")\n ? (value as Record<string, unknown>).bodyBase64\n : undefined;\n\nconst readHintString = (option: OperationFileHint[\"dataField\"], fallback: string): string =>\n Option.getOrElse(option, () => fallback);\n\nconst readHintMimeType = (hint: OperationFileHint, fallback: string): string =>\n Option.getOrElse(hint.mimeType, () => fallback);\n\nconst readHintEncoding = (hint: OperationFileHint): \"base64\" | \"base64url\" =>\n Option.getOrElse(hint.encoding, () => \"base64\");\n\nconst fileFromByteField = (body: unknown, hint: OperationFileHint): ToolFileValue | null => {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return null;\n const record = body as Record<string, unknown>;\n const dataField = readHintString(hint.dataField, \"data\");\n const rawData = record[dataField];\n if (typeof rawData !== \"string\") return null;\n\n const data = normalizeBase64(rawData, readHintEncoding(hint));\n const sizeField = Option.getOrUndefined(hint.sizeField);\n const byteLength =\n sizeField && typeof record[sizeField] === \"number\"\n ? record[sizeField]\n : byteLengthFromBase64(data);\n const hintedMimeType = readHintMimeType(hint, \"application/octet-stream\");\n\n return {\n _tag: \"ToolFile\",\n mimeType: isGenericMimeType(hintedMimeType)\n ? (sniffMimeTypeFromBase64(data) ?? hintedMimeType)\n : hintedMimeType,\n encoding: \"base64\",\n data,\n byteLength,\n };\n};\n\nconst fileFromBinaryBytes = (\n bytes: Uint8Array,\n hint: OperationFileHint,\n contentType: string | null | undefined,\n): ToolFileValue => {\n const hintedMimeType = contentType ?? readHintMimeType(hint, \"application/octet-stream\");\n return {\n _tag: \"ToolFile\",\n mimeType: isGenericMimeType(hintedMimeType)\n ? (sniffMimeType(bytes) ?? hintedMimeType)\n : hintedMimeType,\n encoding: \"base64\",\n data: bytesToBase64(bytes),\n byteLength: bytes.byteLength,\n };\n};\n\ntype FormDataRecord = Parameters<typeof HttpClientRequest.bodyFormDataRecord>[1];\ntype FormDataCoercible = FormDataRecord[string];\n\n// Pull a plain ArrayBuffer out of a Uint8Array — `new Blob([u8])` rejects\n// views whose `.buffer` is `SharedArrayBuffer | ArrayBuffer` under strict\n// lib.dom typings.\nconst toArrayBuffer = (bytes: Uint8Array): ArrayBuffer => {\n const copy = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(copy).set(bytes);\n return copy;\n};\n\n// ---------------------------------------------------------------------------\n// OpenAPI 3.x encoding — per-property style/explode/allowReserved/contentType\n// for multipart/form-data and application/x-www-form-urlencoded bodies.\n// Spec ref: https://spec.openapis.org/oas/v3.1.0#encoding-object\n// ---------------------------------------------------------------------------\n\ntype StyleExplode = {\n readonly style: string;\n readonly explode: boolean;\n readonly allowReserved: boolean;\n};\n\nconst DEFAULT_FORM_STYLE: StyleExplode = {\n style: \"form\",\n explode: true,\n allowReserved: false,\n};\n\nconst resolveStyleExplode = (e: EncodingObject | undefined): StyleExplode => {\n if (!e) return DEFAULT_FORM_STYLE;\n return {\n style: Option.getOrElse(e.style, () => DEFAULT_FORM_STYLE.style),\n explode: Option.getOrElse(e.explode, () => DEFAULT_FORM_STYLE.explode),\n allowReserved: Option.getOrElse(e.allowReserved, () => DEFAULT_FORM_STYLE.allowReserved),\n };\n};\n\nconst encodeFormValue = (v: unknown, allowReserved: boolean): string => {\n const raw = typeof v === \"object\" && v !== null ? JSON.stringify(v) : String(v);\n return encodeReservedAware(raw, allowReserved);\n};\n\n/**\n * Serialize a record to application/x-www-form-urlencoded with OAS3 style\n * rules honored per-field. Supports `form` (default), `deepObject`,\n * `pipeDelimited`, `spaceDelimited` styles with `explode` true / false.\n */\nconst serializeFormUrlEncoded = (\n value: Record<string, unknown>,\n encoding: Record<string, EncodingObject> | undefined,\n): string => {\n const parts: string[] = [];\n for (const [key, raw] of Object.entries(value)) {\n if (raw === undefined || raw === null) continue;\n const { style, explode, allowReserved } = resolveStyleExplode(encoding?.[key]);\n const encKey = encodeURIComponent(key);\n\n if (Array.isArray(raw)) {\n if (explode) {\n for (const v of raw) {\n parts.push(`${encKey}=${encodeFormValue(v, allowReserved)}`);\n }\n } else {\n const sep = style === \"spaceDelimited\" ? \" \" : style === \"pipeDelimited\" ? \"|\" : \",\";\n parts.push(\n `${encKey}=${encodeFormValue(\n raw.map((v) => (typeof v === \"object\" ? JSON.stringify(v) : String(v))).join(sep),\n allowReserved,\n )}`,\n );\n }\n continue;\n }\n\n if (typeof raw === \"object\") {\n const entries = Object.entries(raw as Record<string, unknown>).filter(\n ([, v]) => v !== undefined && v !== null,\n );\n if (style === \"deepObject\") {\n for (const [subkey, subval] of entries) {\n // Encode the whole `key[subkey]` fragment so `[` / `]` become\n // `%5B` / `%5D`. Matches swagger-client's behaviour and remains\n // accepted by common server-side parsers (qs, Rails, etc.).\n parts.push(\n `${encodeURIComponent(`${key}[${subkey}]`)}=${encodeFormValue(subval, allowReserved)}`,\n );\n }\n } else if (explode) {\n // form + explode=true on object: sub-keys become top-level fields.\n for (const [subkey, subval] of entries) {\n parts.push(`${encodeURIComponent(subkey)}=${encodeFormValue(subval, allowReserved)}`);\n }\n } else {\n // form + explode=false on object: flatten to csv key,val,key,val.\n const flat = entries.flatMap(([k, v]) => [\n k,\n typeof v === \"object\" ? JSON.stringify(v) : String(v),\n ]);\n parts.push(`${encKey}=${encodeFormValue(flat.join(\",\"), allowReserved)}`);\n }\n continue;\n }\n\n parts.push(`${encKey}=${encodeFormValue(raw, allowReserved)}`);\n }\n return parts.join(\"&\");\n};\n\n/**\n * Best-effort build of a multipart FormData entry record.\n *\n * If `encoding[key].contentType` is declared (OAS3 §4.8.15), wrap the value\n * in a `Blob` with that type so the runtime multipart framer emits the\n * per-part `Content-Type` header (e.g. `application/json` for a metadata\n * part whose server expects parsed JSON).\n *\n * Otherwise: primitives pass through, arrays handle their item types, byte\n * shapes wrap as Blob, nested objects JSON-stringify (never `[object Object]`).\n */\nconst coerceFormDataRecord = (\n value: Record<string, unknown>,\n encoding: Record<string, EncodingObject> | undefined,\n): FormDataRecord => {\n const out: Record<string, FormDataCoercible> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (raw === undefined || raw === null) continue;\n\n const partType = encoding?.[key]\n ? Option.getOrUndefined(encoding[key]!.contentType)\n : undefined;\n\n // Explicit per-part content type: wrap in a typed Blob so the framer\n // emits `Content-Type: <partType>` on this part. JSON types get the\n // value JSON-stringified first so the blob body is valid JSON.\n if (partType) {\n const isJson = partType.startsWith(\"application/json\") || partType.includes(\"+json\");\n const serialized =\n typeof raw === \"string\"\n ? raw\n : isJson\n ? JSON.stringify(raw)\n : typeof raw === \"object\"\n ? JSON.stringify(raw)\n : String(raw);\n out[key] = new Blob([serialized], { type: partType });\n continue;\n }\n\n if (\n typeof raw === \"string\" ||\n typeof raw === \"number\" ||\n typeof raw === \"boolean\" ||\n raw instanceof Blob ||\n (typeof File !== \"undefined\" && raw instanceof File)\n ) {\n out[key] = raw as FormDataCoercible;\n continue;\n }\n if (Array.isArray(raw)) {\n out[key] = raw.map((v) =>\n typeof v === \"string\" ||\n typeof v === \"number\" ||\n typeof v === \"boolean\" ||\n v instanceof Blob ||\n (typeof File !== \"undefined\" && v instanceof File)\n ? (v as FormDataCoercible)\n : JSON.stringify(v),\n ) as FormDataCoercible;\n continue;\n }\n const bytes = toUint8Array(raw);\n if (bytes) {\n out[key] = new Blob([toArrayBuffer(bytes)]);\n continue;\n }\n out[key] = JSON.stringify(raw);\n }\n return out;\n};\n\n// ---------------------------------------------------------------------------\n// Request body dispatch\n//\n// Dispatch is driven by the spec-declared content type first, JS type of\n// the provided body second. Servers that advertise a specific content type\n// almost always reject anything else (e.g. a multipart endpoint will hang\n// waiting for valid framing if it receives `application/json`), so the\n// content type wins.\n//\n// Within each content type we accept both pre-serialized strings (user\n// already produced the wire format) and structured JS values we can\n// serialize ourselves. The last-resort fallback is `JSON.stringify(body)`\n// — never `String(body)` (which produces the useless `[object Object]`).\n// ---------------------------------------------------------------------------\n\nconst applyRequestBody = (\n request: HttpClientRequest.HttpClientRequest,\n contentType: string,\n bodyValue: unknown,\n encoding: Record<string, EncodingObject> | undefined,\n): HttpClientRequest.HttpClientRequest => {\n if (isJsonContentType(contentType)) {\n // Pre-serialized JSON strings pass through with the declared media\n // type preserved (important for `application/vnd.foo+json` etc.).\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n return HttpClientRequest.bodyJsonUnsafe(request, bodyValue);\n }\n\n if (isFormUrlEncoded(contentType)) {\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n if (typeof bodyValue === \"object\" && bodyValue !== null && !Array.isArray(bodyValue)) {\n // Serialize ourselves so OAS3 encoding (style/explode/deepObject)\n // is honored. bodyUrlParams doesn't know about per-field style.\n const serialized = serializeFormUrlEncoded(bodyValue as Record<string, unknown>, encoding);\n return HttpClientRequest.bodyText(request, serialized, contentType);\n }\n // Non-object body — fall back to platform helper (handles URLSearchParams).\n return HttpClientRequest.bodyUrlParams(\n request,\n bodyValue as Parameters<typeof HttpClientRequest.bodyUrlParams>[1],\n );\n }\n\n if (isMultipartFormData(contentType)) {\n if (bodyValue instanceof FormData) {\n return HttpClientRequest.bodyFormData(request, bodyValue);\n }\n if (typeof bodyValue === \"object\" && bodyValue !== null) {\n return HttpClientRequest.bodyFormDataRecord(\n request,\n coerceFormDataRecord(bodyValue as Record<string, unknown>, encoding),\n );\n }\n // String / primitive under multipart is almost certainly wrong on the\n // caller's end — send it as text with their declared content type and\n // let the server produce a useful error.\n return HttpClientRequest.bodyText(request, String(bodyValue), contentType);\n }\n\n if (isOctetStream(contentType)) {\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n // Unknown shape — serialize as JSON so at least the payload is visible.\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n }\n\n if (isXmlContentType(contentType) || isTextContentType(contentType)) {\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n // Object body under text/xml is unusual — stringify so the caller sees\n // their own payload instead of `[object Object]`.\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n }\n\n // Unknown content type: respect what the caller supplied.\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n};\n\n// ---------------------------------------------------------------------------\n// Public API — build the outbound request for an operation\n//\n// The full pre-flight phase of an invocation: read/validate caller args\n// (path params, request body, base64 payloads) and construct the\n// HttpClientRequest. Pure — nothing is sent. Exposed separately so the\n// executor's approval flow can validate args BEFORE raising an approval\n// elicitation, guaranteeing the validation semantics are exactly what\n// `invoke` applies (one code path, not a parallel re-implementation).\n// ---------------------------------------------------------------------------\n\nconst acceptedArgumentNames = (operation: OperationBinding): readonly string[] => {\n const accepted = new Set<string>();\n\n for (const param of operation.parameters) {\n accepted.add(param.name);\n for (const container of CONTAINER_KEYS[param.location] ?? []) accepted.add(container);\n }\n\n for (const match of operation.pathTemplate.matchAll(/\\{([^{}]+)\\}/g)) {\n if (match[1]) accepted.add(match[1]);\n }\n\n if (Option.isSome(operation.requestBody)) {\n const requestBody = operation.requestBody.value;\n const contents = Option.getOrUndefined(requestBody.contents);\n accepted.add(\"body\");\n accepted.add(\"input\");\n if (\n isOctetStream(requestBody.contentType) ||\n contents?.some((content) => isOctetStream(content.contentType))\n ) {\n accepted.add(\"bodyBase64\");\n }\n if (contents && contents.length > 1) accepted.add(\"contentType\");\n }\n\n const servers = operation.servers ?? [];\n const hasServerVariables = servers.some(\n (server) => Object.keys(Option.getOrUndefined(server.variables) ?? {}).length > 0,\n );\n if (servers.length > 1 || hasServerVariables) accepted.add(\"server\");\n\n return [...accepted];\n};\n\nexport const buildRequest = Effect.fn(\"OpenApi.buildRequest\")(function* (\n operation: OperationBinding,\n args: Record<string, unknown>,\n resolvedHeaders: Record<string, string>,\n integrationQueryParams: Record<string, string> = {},\n) {\n const accepted = acceptedArgumentNames(operation);\n const acceptedSet = new Set(accepted);\n const unknown = Object.keys(args).filter((name) => !acceptedSet.has(name));\n if (unknown.length > 0) {\n const label = unknown.length === 1 ? \"Unknown argument\" : \"Unknown arguments\";\n const names = unknown.map((name) => JSON.stringify(name)).join(\", \");\n const acceptedMessage =\n accepted.length > 0\n ? `This operation accepts: ${accepted.join(\", \")}.`\n : \"This operation accepts no arguments.\";\n return yield* new OpenApiInvocationError({\n message: `${label} ${names}. ${acceptedMessage}`,\n statusCode: Option.none(),\n reason: \"unknown_arguments\",\n });\n }\n\n const resolvedPath = yield* resolvePath(operation.pathTemplate, args, operation.parameters);\n\n const path = resolvedPath.startsWith(\"/\") ? resolvedPath : `/${resolvedPath}`;\n\n let request = HttpClientRequest.make(operation.method.toUpperCase() as \"GET\")(path);\n\n // Default first so operation header params and resolved auth headers below\n // can override it; the upstream still gets a User-Agent if nothing else sets one.\n request = HttpClientRequest.setHeader(request, \"User-Agent\", DEFAULT_USER_AGENT);\n\n for (const [name, value] of Object.entries(integrationQueryParams)) {\n request = HttpClientRequest.setUrlParam(request, name, value);\n }\n\n for (const param of operation.parameters) {\n if (param.location !== \"query\") continue;\n const value = readParamValue(args, param);\n for (const paramValue of queryParamValues(value, param)) {\n request = HttpClientRequest.appendUrlParam(request, param.name, paramValue);\n }\n }\n\n for (const param of operation.parameters) {\n if (param.location !== \"header\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) continue;\n request = HttpClientRequest.setHeader(request, param.name, String(value));\n }\n\n const cookieValues: string[] = [];\n for (const param of operation.parameters) {\n if (param.location !== \"cookie\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) continue;\n cookieValues.push(`${param.name}=${primitiveToString(value)}`);\n }\n\n if (Option.isSome(operation.requestBody)) {\n const rb = operation.requestBody.value;\n const contentsOpt = Option.getOrUndefined(rb.contents);\n const requestedCt = typeof args.contentType === \"string\" ? args.contentType : undefined;\n const octetStreamContent = contentsOpt?.find((c) => isOctetStream(c.contentType));\n const bodyAcceptsOctetStream = Boolean(octetStreamContent) || isOctetStream(rb.contentType);\n const hasBodyBase64 = Object.prototype.hasOwnProperty.call(args, \"bodyBase64\");\n const bodyBase64Raw = args.bodyBase64;\n const bodyBase64 =\n typeof bodyBase64Raw === \"string\" ? decodeBase64Body(bodyBase64Raw) : undefined;\n\n if (hasBodyBase64 && typeof bodyBase64Raw !== \"string\") {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` must be a base64 string\",\n statusCode: Option.none(),\n });\n }\n if (bodyBase64?.ok === false) {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` is not valid base64\",\n statusCode: Option.none(),\n });\n }\n if (bodyBase64?.ok === true && !bodyAcceptsOctetStream) {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` requires an application/octet-stream request body\",\n statusCode: Option.none(),\n });\n }\n if (bodyBase64?.ok === true && requestedCt && !isOctetStream(requestedCt)) {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` requires an application/octet-stream contentType\",\n statusCode: Option.none(),\n });\n }\n\n const rawBodyValue = args.body ?? args.input;\n const nestedBodyBase64Raw = readNestedBodyBase64(rawBodyValue);\n const hasNestedBodyBase64 = nestedBodyBase64Raw !== undefined;\n const nestedBodyBase64 =\n typeof nestedBodyBase64Raw === \"string\" ? decodeBase64Body(nestedBodyBase64Raw) : undefined;\n\n if (hasNestedBodyBase64 && typeof nestedBodyBase64Raw !== \"string\") {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` must be a base64 string\",\n statusCode: Option.none(),\n });\n }\n if (nestedBodyBase64?.ok === false) {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` is not valid base64\",\n statusCode: Option.none(),\n });\n }\n if (nestedBodyBase64?.ok === true && !bodyAcceptsOctetStream) {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` requires an application/octet-stream request body\",\n statusCode: Option.none(),\n });\n }\n if (nestedBodyBase64?.ok === true && requestedCt && !isOctetStream(requestedCt)) {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` requires an application/octet-stream contentType\",\n statusCode: Option.none(),\n });\n }\n\n const binaryBody = bodyBase64?.ok === true ? bodyBase64 : nestedBodyBase64;\n const bodyValue = binaryBody?.ok === true ? binaryBody.bytes : rawBodyValue;\n if (rb.required && bodyValue === undefined) {\n return yield* new OpenApiInvocationError({\n message: bodyAcceptsOctetStream\n ? \"Missing required request body: provide `bodyBase64`\"\n : \"Missing required request body\",\n statusCode: Option.none(),\n });\n }\n if (bodyValue !== undefined) {\n // Resolve which declared media type to use. When the spec declares\n // multiple, the caller can override via `args.contentType`; otherwise\n // we use the first-declared (spec author's preferred ordering).\n const selected: MediaBinding | undefined =\n binaryBody?.ok === true && octetStreamContent\n ? octetStreamContent\n : contentsOpt && requestedCt\n ? contentsOpt.find((c) => c.contentType === requestedCt)\n : undefined;\n const chosenCt =\n binaryBody?.ok === true && !octetStreamContent && isOctetStream(rb.contentType)\n ? rb.contentType\n : (selected?.contentType ?? rb.contentType);\n // A `bodyBase64` arg already decoded to bytes above. A plain string\n // `body` is the long-standing way callers pass (text) octet-stream\n // upload content, and applyRequestBody sends it through as-is, so let it\n // past. Only a genuinely non-byte, non-string shape (an object, say)\n // can't be uploaded as octet-stream and needs `bodyBase64`.\n if (\n isOctetStream(chosenCt) &&\n typeof bodyValue !== \"string\" &&\n toUint8Array(bodyValue) === null\n ) {\n return yield* new OpenApiInvocationError({\n message: \"application/octet-stream request body must be bytes; provide `bodyBase64`\",\n statusCode: Option.none(),\n });\n }\n const chosenEncoding = selected\n ? Option.getOrUndefined(selected.encoding)\n : contentsOpt && contentsOpt[0]\n ? Option.getOrUndefined(contentsOpt[0].encoding)\n : undefined;\n request = applyRequestBody(request, chosenCt, bodyValue, chosenEncoding);\n }\n }\n\n request = applyHeaders(request, resolvedHeaders);\n if (cookieValues.length > 0) {\n const existingCookie = request.headers.cookie;\n const serializedCookies = cookieValues.join(\"; \");\n request = HttpClientRequest.setHeader(\n request,\n \"Cookie\",\n existingCookie ? `${existingCookie}; ${serializedCookies}` : serializedCookies,\n );\n }\n\n return request;\n});\n\n// ---------------------------------------------------------------------------\n// Public API — invoke a single operation\n// ---------------------------------------------------------------------------\n\nexport const invoke = Effect.fn(\"OpenApi.invoke\")(function* (\n operation: OperationBinding,\n args: Record<string, unknown>,\n resolvedHeaders: Record<string, string>,\n integrationQueryParams: Record<string, string> = {},\n options: InvokeOptions = {},\n) {\n const client = yield* HttpClient.HttpClient;\n\n yield* Effect.annotateCurrentSpan({\n \"http.method\": operation.method.toUpperCase(),\n \"http.route\": operation.pathTemplate,\n \"plugin.openapi.method\": operation.method.toUpperCase(),\n \"plugin.openapi.path_template\": operation.pathTemplate,\n \"plugin.openapi.headers.resolved_count\": Object.keys(resolvedHeaders).length,\n });\n\n const request = yield* buildRequest(operation, args, resolvedHeaders, integrationQueryParams);\n\n const responseHeadersTimeoutMs = options.responseHeadersTimeoutMs ?? RESPONSE_HEADERS_TIMEOUT_MS;\n const runFork = Effect.runForkWith(yield* Effect.context<never>());\n const responseExitOption = yield* Effect.callback<\n Option.Option<Exit.Exit<HttpClientResponse.HttpClientResponse, OpenApiInvocationError>>\n >((resume, signal) => {\n let settled = false;\n const responseEffect = client.execute(request).pipe(\n Effect.mapError(\n (err) =>\n new OpenApiInvocationError({\n message: \"HTTP request failed\",\n statusCode: Option.none(),\n cause: err,\n }),\n ),\n Effect.exit,\n Effect.tap((exit) =>\n Effect.sync(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resume(Effect.succeed(Option.some(exit)));\n }),\n ),\n );\n const fiber = runFork(responseEffect);\n const interrupt = () => {\n runFork(Fiber.interrupt(fiber));\n };\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n interrupt();\n resume(Effect.succeed(Option.none()));\n }, responseHeadersTimeoutMs);\n signal.addEventListener(\"abort\", interrupt, { once: true });\n return Effect.sync(() => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", interrupt);\n if (!settled) interrupt();\n });\n });\n if (Option.isNone(responseExitOption)) {\n return yield* new OpenApiInvocationError({\n message: responseHeadersTimeoutMessage(responseHeadersTimeoutMs),\n statusCode: Option.none(),\n reason: \"response_headers_timeout\",\n });\n }\n const responseExit = responseExitOption.value;\n if (Exit.isFailure(responseExit)) return yield* Effect.failCause(responseExit.cause);\n const response = responseExit.value;\n\n const status = response.status;\n yield* Effect.annotateCurrentSpan({\n \"http.status_code\": status,\n });\n const responseHeaders: Record<string, string> = { ...response.headers };\n\n const contentType = response.headers[\"content-type\"] ?? null;\n const mapBodyError = Effect.mapError(\n (err: unknown) =>\n new OpenApiInvocationError({\n message: \"Failed to read response body\",\n statusCode: Option.some(status),\n cause: err,\n }),\n );\n const responseBodyBinding = Option.getOrUndefined(operation.responseBody);\n const fileHint = responseBodyBinding\n ? Option.getOrUndefined(responseBodyBinding.fileHint)\n : undefined;\n const ok = status >= 200 && status < 300;\n const streamingBody =\n ok &&\n status !== 204 &&\n fileHint?.kind !== \"binaryResponse\" &&\n isStreamingResponseContentType(contentType)\n ? yield* collectStreamingBody(response.stream, contentType).pipe(mapBodyError)\n : null;\n if (streamingBody) {\n Object.assign(responseHeaders, streamingBody.headers);\n }\n const responseBody: unknown =\n status === 204\n ? null\n : ok && fileHint?.kind === \"binaryResponse\"\n ? fileFromBinaryBytes(\n new Uint8Array(yield* response.arrayBuffer.pipe(mapBodyError)),\n fileHint,\n contentType,\n )\n : streamingBody\n ? streamingBody.data\n : isJsonContentType(contentType)\n ? yield* response.json.pipe(\n Effect.catch(() => response.text),\n mapBodyError,\n )\n : yield* response.text.pipe(mapBodyError);\n\n const dataBody =\n ok && fileHint?.kind === \"byteField\"\n ? (fileFromByteField(responseBody, fileHint) ?? responseBody)\n : responseBody;\n return InvocationResult.make({\n status,\n headers: responseHeaders,\n data: ok ? dataBody : null,\n error: ok ? null : responseBody,\n });\n});\n\n// Connection `baseUrl` wins; otherwise the call's chosen server (`server.url`, or\n// the first) resolved with its `{variables}` (call values, else spec defaults).\nconst resolveRequestHost = (\n servers: readonly ServerInfo[],\n serverArg: unknown,\n baseUrl: string,\n): string => {\n if (baseUrl) return baseUrl;\n if (servers.length === 0) return \"\";\n\n const arg = (\n typeof serverArg === \"object\" && serverArg !== null && !Array.isArray(serverArg)\n ? serverArg\n : {}\n ) as { url?: unknown; variables?: unknown };\n const chosen = servers.find((server) => server.url === arg.url) ?? servers[0]!;\n\n const overrides: Record<string, string> = {};\n if (typeof arg.variables === \"object\" && arg.variables !== null) {\n for (const [name, value] of Object.entries(arg.variables as Record<string, unknown>)) {\n if (value != null && value !== \"\") overrides[name] = String(value);\n }\n }\n return resolveServerUrl(chosen.url, Option.getOrUndefined(chosen.variables), overrides);\n};\n\n// ---------------------------------------------------------------------------\n// Invoke with a provided HttpClient layer + per-call host resolution\n// ---------------------------------------------------------------------------\n\nexport const invokeWithLayer = (\n operation: OperationBinding,\n args: Record<string, unknown>,\n baseUrl: string,\n resolvedHeaders: Record<string, string>,\n integrationQueryParams: Record<string, string>,\n httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,\n options: InvokeOptions = {},\n) => {\n const effectiveBaseUrl = resolveRequestHost(operation.servers ?? [], args.server, baseUrl);\n const clientWithBaseUrl = effectiveBaseUrl\n ? Layer.effect(\n HttpClient.HttpClient,\n Effect.map(\n Effect.service(HttpClient.HttpClient),\n HttpClient.mapRequest(HttpClientRequest.prependUrl(effectiveBaseUrl)),\n ),\n ).pipe(Layer.provide(httpClientLayer))\n : httpClientLayer;\n\n return invoke(operation, args, resolvedHeaders, integrationQueryParams, options).pipe(\n Effect.provide(clientWithBaseUrl),\n // `invoke` annotates http.status_code on ITS span (`OpenApi.invoke`,\n // via Effect.fn) — annotateCurrentSpan inside it never reaches this\n // wrapper span. Stamp the status here too so queries against\n // `plugin.openapi.invoke` see the upstream outcome directly.\n Effect.tap((result) => Effect.annotateCurrentSpan({ \"http.status_code\": result.status })),\n Effect.withSpan(\"plugin.openapi.invoke\", {\n attributes: {\n \"plugin.openapi.method\": operation.method.toUpperCase(),\n \"plugin.openapi.path_template\": operation.pathTemplate,\n \"plugin.openapi.base_url\": effectiveBaseUrl,\n },\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Derive annotations from HTTP method\n// ---------------------------------------------------------------------------\n\nexport const REQUIRE_APPROVAL = new Set([\"post\", \"put\", \"patch\", \"delete\"]);\n\nexport const annotationsForOperation = (\n method: string,\n pathTemplate: string,\n): { requiresApproval?: boolean; approvalDescription?: string } => {\n const m = method.toLowerCase();\n if (!REQUIRE_APPROVAL.has(m)) return {};\n return {\n requiresApproval: true,\n approvalDescription: `${method.toUpperCase()} ${pathTemplate}`,\n };\n};\n","import { Effect, Option, Schema } from \"effect\";\nimport type { Layer } from \"effect\";\nimport { HttpClient } from \"effect/unstable/http\";\n\nimport {\n ToolFileJsonSchema,\n ToolName,\n ToolResult,\n authToolFailure,\n classifyHttpStatus,\n detectInsufficientScope,\n sortHealthCheckCandidatesByIdentity,\n extractIdentity,\n extractResponseFields,\n projectResponseFields,\n type HealthCheckCandidate,\n type HealthCheckResponseField,\n type HealthCheckResult,\n type HealthCheckSpec,\n type IntegrationRecord,\n type PluginCtx,\n type ResolveToolsResult,\n type StorageFailure,\n type ToolDef,\n type ToolInvocationCredential,\n} from \"@rafads/sdk/core\";\n\nimport {\n decodeOpenApiIntegrationConfig,\n renderAuthTemplate,\n requiredTemplateVariables,\n type OpenApiIntegrationConfig,\n} from \"./config\";\nimport { OpenApiExtractionError, OpenApiInvocationError, OpenApiParseError } from \"./errors\";\nimport {\n buildInputSchema,\n extract,\n outputSchemaFromResponseBody,\n streamOperationBindings,\n streamOperationBindingsFromStructure,\n} from \"./extract\";\nimport { compileToolDefinitions, type ToolDefinition } from \"./definitions\";\nimport {\n annotationsForOperation,\n buildRequest,\n invokeWithLayer,\n REQUIRE_APPROVAL,\n type InvokeOptions,\n} from \"./invoke\";\nimport { parse, type ParsedDocument } from \"./parse\";\nimport { parseEntry, structuralSplit, type KeepPathItem, type SpecStructure } from \"./split\";\nimport { type OpenapiStore, type StoredOperation } from \"./store\";\nimport { OperationBinding } from \"./types\";\n\nconst STRINGIFIED_BODY_CAP = 1024;\nconst UpstreamMessageBody = Schema.Struct({ message: Schema.String });\nconst UpstreamErrorMessageBody = Schema.Struct({ errorMessage: Schema.String });\nconst UpstreamNestedErrorBody = Schema.Struct({ error: UpstreamMessageBody });\nconst UpstreamErrorsArrayBody = Schema.Struct({\n errors: Schema.Array(\n Schema.Struct({\n detail: Schema.optional(Schema.String),\n message: Schema.optional(Schema.String),\n title: Schema.optional(Schema.String),\n }),\n ),\n});\nconst UpstreamDescriptionBody = Schema.Struct({\n detail: Schema.optional(Schema.String),\n title: Schema.optional(Schema.String),\n description: Schema.optional(Schema.String),\n});\n\nconst decodeUpstreamMessageBody = Schema.decodeUnknownOption(UpstreamMessageBody);\nconst decodeUpstreamErrorMessageBody = Schema.decodeUnknownOption(UpstreamErrorMessageBody);\nconst decodeUpstreamNestedErrorBody = Schema.decodeUnknownOption(UpstreamNestedErrorBody);\nconst decodeUpstreamErrorsArrayBody = Schema.decodeUnknownOption(UpstreamErrorsArrayBody);\nconst decodeUpstreamDescriptionBody = Schema.decodeUnknownOption(UpstreamDescriptionBody);\n\nconst clampedStringify = (value: unknown): string => {\n let s: string;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: JSON.stringify may throw on cycles; fall back to String() so the upstream body can still be surfaced as ToolError.details fallback text\n try {\n s = JSON.stringify(value);\n } catch {\n s = String(value);\n }\n return s.length > STRINGIFIED_BODY_CAP ? `${s.slice(0, STRINGIFIED_BODY_CAP)}…` : s;\n};\n\nconst firstNonEmpty = (...values: readonly (string | undefined)[]): string | undefined =>\n values.find((value) => value !== undefined && value.length > 0);\n\nexport const extractOpenApiUpstreamMessage = (body: unknown, status: number): string => {\n if (typeof body === \"string\") {\n return body.length > 0 ? body : `Upstream returned HTTP ${status}`;\n }\n const nested = Option.getOrUndefined(decodeUpstreamNestedErrorBody(body));\n const messageBody = Option.getOrUndefined(decodeUpstreamMessageBody(body));\n const errorMessageBody = Option.getOrUndefined(decodeUpstreamErrorMessageBody(body));\n const errorsBody = Option.getOrUndefined(decodeUpstreamErrorsArrayBody(body));\n const descriptionBody = Option.getOrUndefined(decodeUpstreamDescriptionBody(body));\n const arrayMessage = errorsBody?.errors\n .map(\n ({\n detail,\n message: upstreamMessage,\n title,\n }: {\n detail?: string;\n message?: string;\n title?: string;\n }) => firstNonEmpty(detail, upstreamMessage, title),\n )\n .find((message: string | undefined) => message !== undefined);\n const message = firstNonEmpty(\n nested?.error.message,\n messageBody?.message,\n errorMessageBody?.errorMessage,\n arrayMessage,\n descriptionBody?.detail,\n descriptionBody?.title,\n descriptionBody?.description,\n );\n if (message !== undefined) return message;\n if (body !== null && typeof body === \"object\") {\n return clampedStringify(body);\n }\n return `Upstream returned HTTP ${status}`;\n};\n\nconst openApiAuthToolFailure = (failure: {\n readonly code: string;\n readonly message: string;\n readonly owner: \"org\" | \"user\";\n readonly integration: string;\n readonly connection: string;\n readonly credentialKind: \"secret\" | \"oauth\" | \"upstream\";\n readonly credentialLabel?: string;\n readonly status?: number;\n readonly details?: unknown;\n}) =>\n authToolFailure({\n code: failure.code as Parameters<typeof authToolFailure>[0][\"code\"],\n message: failure.message,\n integration: { id: failure.integration, scope: failure.owner },\n credential: {\n kind: failure.credentialKind,\n ...(failure.credentialLabel ? { label: failure.credentialLabel } : {}),\n },\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.details !== undefined\n ? {\n upstream: {\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n details: failure.details,\n },\n }\n : {}),\n });\n\n/** Rewrite OpenAPI `#/components/schemas/X` refs to standard `#/$defs/X`. */\nexport const normalizeOpenApiRefs = (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 = normalizeOpenApiRefs(item);\n if (n !== item) changed = true;\n return n;\n });\n return changed ? out : node;\n }\n\n const obj = node as Record<string, unknown>;\n\n if (typeof obj.$ref === \"string\") {\n const match = obj.$ref.match(/^#\\/components\\/schemas\\/(.+)$/);\n if (match) return { ...obj, $ref: `#/$defs/${match[1]}` };\n return obj;\n }\n\n let changed = false;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n const n = normalizeOpenApiRefs(v);\n if (n !== v) changed = true;\n result[k] = n;\n }\n return changed ? result : obj;\n};\n\nconst toBinding = (def: ToolDefinition): OperationBinding =>\n OperationBinding.make({\n method: def.operation.method,\n servers: def.operation.servers,\n pathTemplate: def.operation.pathTemplate,\n parameters: [...def.operation.parameters],\n requestBody: def.operation.requestBody,\n responseBody: def.operation.responseBody,\n ...(def.operation.requiredScopeAlternatives\n ? { requiredScopeAlternatives: def.operation.requiredScopeAlternatives }\n : {}),\n });\n\nconst descriptionFor = (def: ToolDefinition): string => {\n const op = def.operation;\n return Option.getOrElse(op.description, () =>\n Option.getOrElse(op.summary, () => `${op.method.toUpperCase()} ${op.pathTemplate}`),\n );\n};\n\n/**\n * Copyable contract appended to the stored description of any tool whose\n * output is a ToolFile. Stored descriptions ride both `search` (the step a\n * model always walks) and `describe.tool`, so baking the emit instruction\n * here puts it in front of the agent before the first call, where the\n * output schema alone (dropped from the hot list projection) cannot.\n */\nconst FILE_OUTPUT_HINT =\n 'Returns a ToolFile: the file bytes already decoded into { _tag: \"ToolFile\", mimeType, encoding, data, byteLength }. ' +\n \"To display or forward it, pass the result's data straight to emit(result.data). \" +\n \"Do not rebuild the envelope or read upstream fields like size.\";\n\nconst withFileEmitHint = (description: string, returnsFile: boolean): string =>\n returnsFile ? `${description}\\n\\n${FILE_OUTPUT_HINT}` : description;\n\nexport interface CompiledOpenApiSpec {\n readonly definitions: readonly ToolDefinition[];\n readonly hoistedDefs: Record<string, unknown>;\n readonly title: string | undefined;\n readonly description: string | undefined;\n}\n\nexport const compileOpenApiDocument = (\n doc: ParsedDocument,\n): Effect.Effect<CompiledOpenApiSpec, OpenApiExtractionError> =>\n Effect.gen(function* () {\n const result = yield* extract(doc);\n const hoistedDefs: Record<string, unknown> = {};\n if (doc.components?.schemas) {\n for (const [k, v] of Object.entries(doc.components.schemas)) {\n hoistedDefs[k] = normalizeOpenApiRefs(v);\n }\n }\n return {\n definitions: compileToolDefinitions(result.operations),\n hoistedDefs,\n title: Option.getOrUndefined(result.title),\n description: Option.getOrUndefined(result.description),\n };\n });\n\nexport const compileOpenApiSpec = (\n specText: string,\n): Effect.Effect<CompiledOpenApiSpec, OpenApiParseError | OpenApiExtractionError> =>\n Effect.gen(function* () {\n const doc = yield* parse(specText);\n return yield* compileOpenApiDocument(doc);\n });\n\n/**\n * Bounded reuse of compiled specs for the serve-side fallback paths (health\n * checks, candidate listing, tools/invoke legacy fallbacks). These paths run\n * per request, and the UI auto-fires the health endpoints on every page mount,\n * so recompiling a multi-MB spec on each call grows the dev server heap until\n * the process hits the V8 limit. The stored spec is content-addressed: the\n * config's `specHash` keys the blob the text is loaded from, so the hash is a\n * free, already-computed identity (same hash means byte-identical text means\n * identical compile output), and a spec update writes a new hash so stale\n * entries age out naturally.\n *\n * An insertion-ordered Map serves as a tiny LRU: hits are re-inserted to\n * refresh recency and the oldest entry is evicted past capacity. Capacity 4\n * covers the handful of integrations a page's probes touch at once while\n * keeping worst-case retention to a few compiled documents.\n */\nconst COMPILED_SPEC_CACHE_CAPACITY = 4;\nconst compiledSpecCache = new Map<string, CompiledOpenApiSpec>();\n\n/** Test-only reset so unit tests can observe cold-cache behavior. */\nexport const clearCompiledOpenApiSpecCache = (): void => {\n compiledSpecCache.clear();\n};\n\n/** Compile through the module-level LRU. `specHash` is the content hash the\n * spec text was loaded by (`OpenApiIntegrationConfig.specHash`). A missing\n * hash (legacy config shape) bypasses the cache rather than paying to hash\n * multi-MB text on the request path. */\nexport const compileOpenApiSpecCached = (\n specHash: string | null | undefined,\n specText: string,\n): Effect.Effect<CompiledOpenApiSpec, OpenApiParseError | OpenApiExtractionError> =>\n Effect.gen(function* () {\n if (specHash == null) return yield* compileOpenApiSpec(specText);\n const hit = compiledSpecCache.get(specHash);\n if (hit !== undefined) {\n compiledSpecCache.delete(specHash);\n compiledSpecCache.set(specHash, hit);\n return hit;\n }\n const compiled = yield* compileOpenApiSpec(specText);\n compiledSpecCache.set(specHash, compiled);\n while (compiledSpecCache.size > COMPILED_SPEC_CACHE_CAPACITY) {\n const oldest = compiledSpecCache.keys().next().value;\n if (oldest === undefined) break;\n compiledSpecCache.delete(oldest);\n }\n return compiled;\n });\n\nexport const openApiToolDefsFromCompiled = (compiled: CompiledOpenApiSpec): readonly ToolDef[] =>\n compiled.definitions.map((def): ToolDef => {\n const returnsFile = Option.match(def.operation.responseBody, {\n onNone: () => false,\n onSome: (responseBody) => Option.isSome(responseBody.fileHint),\n });\n return {\n name: ToolName.make(def.toolPath),\n description: withFileEmitHint(descriptionFor(def), returnsFile),\n inputSchema: normalizeOpenApiRefs(Option.getOrUndefined(def.operation.inputSchema)),\n outputSchema: returnsFile\n ? ToolFileJsonSchema\n : normalizeOpenApiRefs(Option.getOrUndefined(def.operation.outputSchema)),\n annotations: annotationsForOperation(def.operation.method, def.operation.pathTemplate),\n };\n });\n\nexport const openApiStoredOperationsFromCompiled = (\n integration: string,\n compiled: CompiledOpenApiSpec,\n): readonly StoredOperation[] =>\n compiled.definitions.map((def) => ({\n integration,\n toolName: def.toolPath,\n binding: toBinding(def),\n description: descriptionFor(def),\n }));\n\n/**\n * Serialize a document's `components.schemas` into the content-addressed defs\n * blob JSON (`{ \"<Name>\": <normalized schema>, ... }`), one schema at a time.\n * Normalizing + stringifying per entry keeps the whole normalized definition\n * tree from ever being co-resident with the parsed document, so the streaming\n * add path's peak stays near parse level. The serve path JSON-parses this blob\n * to rebuild the shared `definitions` instead of re-parsing the spec.\n */\nexport const buildDefsJson = (doc: ParsedDocument): string => {\n const schemas = doc.components?.schemas;\n if (!schemas) return \"{}\";\n let json = \"{\";\n let first = true;\n for (const [name, schema] of Object.entries(schemas)) {\n const serialized = JSON.stringify(normalizeOpenApiRefs(schema));\n if (serialized === undefined) continue;\n json += `${first ? \"\" : \",\"}${JSON.stringify(name)}:${serialized}`;\n first = false;\n }\n return `${json}}`;\n};\n\n/**\n * Streaming twin of `buildDefsJson`: serialize the content-addressed defs blob\n * from a `SpecStructure` by parsing each `components.schemas` entry in isolation\n * (indent-4 range) rather than from a whole-document parse. Used by the fully\n * streaming add path so the 37MB Microsoft Graph spec never builds its\n * ~300MB tree. The blob carries *all* source schemas (it is shared across every\n * tenant/selection on the same spec hash); extra unreferenced `$defs` are\n * harmless. Like `buildDefsJson`, normalizing + stringifying per entry keeps the\n * whole normalized tree from being co-resident with any parsed schema, and the\n * ConsString accumulation avoids the join-doubling of an array build.\n */\nexport const buildDefsJsonStreaming = (structure: SpecStructure): string => {\n let json = \"{\";\n let first = true;\n for (const range of structure.schemas) {\n const entry = parseEntry(structure.text, range, 4);\n if (!entry) continue;\n const [name, schema] = entry;\n const serialized = JSON.stringify(normalizeOpenApiRefs(schema));\n if (serialized === undefined) continue;\n json += `${first ? \"\" : \",\"}${JSON.stringify(name)}:${serialized}`;\n first = false;\n }\n return `${json}}`;\n};\n\nconst DefsJson = Schema.Record(Schema.String, Schema.Unknown);\n/** Decode the content-addressed defs blob back into the shared `definitions`\n * map. Returns `None` on a corrupt/non-object blob so the serve path falls\n * back to the spec re-parse rather than failing `tools/list`. */\nconst decodeDefsJson = Schema.decodeUnknownOption(Schema.fromJsonString(DefsJson));\n\n/** Rebuild a tool def from a stored operation binding, no spec parse. Mirrors\n * `openApiToolDefsFromCompiled` but sources its schemas from the persisted\n * binding (params/body/response carry `$ref`s into the shared defs blob). The\n * file-emit hint is applied here, at the same ToolDef projection step the\n * re-parse path applies it, so a file-returning op carries the contract\n * whether it is served fast (from the binding) or via the spec fallback. */\nconst toolDefFromStoredOperation = (op: StoredOperation): ToolDef => {\n const binding = op.binding;\n const returnsFile = Option.match(binding.responseBody, {\n onNone: () => false,\n onSome: (responseBody) => Option.isSome(responseBody.fileHint),\n });\n return {\n name: ToolName.make(op.toolName),\n description: withFileEmitHint(\n op.description ?? `${binding.method.toUpperCase()} ${binding.pathTemplate}`,\n returnsFile,\n ),\n inputSchema: normalizeOpenApiRefs(\n buildInputSchema(\n binding.parameters,\n Option.getOrUndefined(binding.requestBody),\n binding.servers ?? [],\n ),\n ),\n outputSchema: returnsFile\n ? ToolFileJsonSchema\n : Option.match(binding.responseBody, {\n onNone: () => undefined,\n onSome: (responseBody) =>\n normalizeOpenApiRefs(outputSchemaFromResponseBody(responseBody)),\n }),\n annotations: annotationsForOperation(binding.method, binding.pathTemplate),\n };\n};\n\nexport interface OpenApiPersistResult {\n readonly toolCount: number;\n readonly toolNames: readonly string[];\n}\n\n/**\n * Compile a parsed document straight to persisted operation bindings, streaming\n * in bounded chunks so a huge spec's bindings are never all co-resident with\n * the parsed tree. This is the memory-safe replacement for\n * `compileOpenApiDocument` + `openApiStoredOperationsFromCompiled` + `putOperations`\n * on the add/update path: it skips per-op input/output schema assembly (the\n * serve path rebuilds those on demand from the bindings). Clears existing\n * operations first, then appends each chunk. When `specHash` is given, also\n * stream-serializes the document's `#/$defs/*` into the content-addressed defs\n * blob so the serve path can resolve the shared `definitions` without\n * re-parsing the spec.\n */\nexport const compileAndPersistOpenApiOperations = ({\n doc,\n integration,\n storage,\n specHash,\n chunkSize,\n}: {\n readonly doc: ParsedDocument;\n readonly integration: string;\n readonly storage: OpenapiStore;\n readonly specHash?: string;\n readonly chunkSize?: number;\n}): Effect.Effect<OpenApiPersistResult, OpenApiExtractionError | StorageFailure> =>\n Effect.gen(function* () {\n yield* storage.removeOperations(integration);\n const result = yield* streamOperationBindings(doc, chunkSize ?? 500, (chunk) =>\n storage.appendOperations(\n integration,\n chunk.map((item) => ({\n integration,\n toolName: item.toolName,\n binding: item.binding,\n description: item.description,\n })),\n ),\n );\n if (specHash != null) {\n yield* storage.putDefs(specHash, buildDefsJson(doc));\n }\n return result;\n });\n\n/** Parse spec text, then stream-compile + persist its bindings (and, when\n * `specHash` is given, the content-addressed defs blob). */\nexport const compileAndPersistOpenApiSpec = ({\n specText,\n integration,\n storage,\n specHash,\n chunkSize,\n}: {\n readonly specText: string;\n readonly integration: string;\n readonly storage: OpenapiStore;\n readonly specHash?: string;\n readonly chunkSize?: number;\n}): Effect.Effect<\n OpenApiPersistResult,\n OpenApiParseError | OpenApiExtractionError | StorageFailure\n> =>\n Effect.gen(function* () {\n const doc = yield* parse(specText);\n return yield* compileAndPersistOpenApiOperations({\n doc,\n integration,\n storage,\n specHash,\n chunkSize,\n });\n });\n\n/**\n * Fully streaming add/update path: compile + persist operation bindings (and the\n * content-addressed defs blob) straight from spec *text*, without ever parsing\n * the whole document. The text is structurally split, then each path-item and\n * each schema is parsed in isolation and discarded, so peak memory stays near\n * one item rather than the ~300MB whole-tree parse that OOMs a 128MB Workers\n * isolate on the 37MB Microsoft Graph spec.\n *\n * There is deliberately no whole-parse fallback: a spec that does not present\n * the streamable block-YAML profile (no top-level `paths:` block) is a hard\n * `OpenApiExtractionError`, because the fallback is exactly the OOM this path\n * exists to avoid. `keepPathItem` optionally filters/trims path-items (the\n * Microsoft Graph scope selection), so the same primitive serves a full-spec\n * compile and a selection identically.\n */\nexport const compileAndPersistOpenApiSpecStreaming = ({\n specText,\n integration,\n storage,\n specHash,\n chunkSize,\n keepPathItem,\n}: {\n readonly specText: string;\n readonly integration: string;\n readonly storage: OpenapiStore;\n readonly specHash?: string;\n readonly chunkSize?: number;\n readonly keepPathItem?: KeepPathItem;\n}): Effect.Effect<OpenApiPersistResult, OpenApiExtractionError | StorageFailure> =>\n Effect.gen(function* () {\n const structure = structuralSplit(specText);\n if (!structure) {\n return yield* new OpenApiExtractionError({\n message:\n \"OpenAPI spec is not in the streamable block-YAML profile (no top-level `paths:` block); cannot stream-compile a spec this large in-band.\",\n });\n }\n yield* storage.removeOperations(integration);\n const result = yield* streamOperationBindingsFromStructure(\n structure,\n { chunkSize: chunkSize ?? 500, keepPathItem },\n (chunk) =>\n storage.appendOperations(\n integration,\n chunk.map((item) => ({\n integration,\n toolName: item.toolName,\n binding: item.binding,\n description: item.description,\n })),\n ),\n );\n if (specHash != null) {\n yield* storage.putDefs(specHash, buildDefsJsonStreaming(structure));\n }\n return result;\n });\n\nexport const loadOpenApiSpecText = (\n storage: OpenapiStore,\n config: OpenApiIntegrationConfig,\n): Effect.Effect<string | null, StorageFailure> =>\n config.specHash != null ? storage.getSpec(config.specHash) : Effect.succeed(null);\n\n/**\n * Resolve the tool defs + shared definitions for a connection refresh\n * (`tools/list`). Fast path: serve from the persisted operation bindings plus\n * the content-addressed defs blob, rebuilding each tool's input/output schema\n * on demand, so a 37MB spec is never re-parsed (the 2nd OOM site). The defs\n * blob is global per `specHash`, so the heavy normalize work is done once at\n * add time and shared across every tenant on the same spec. Falls back to the\n * spec re-parse for legacy rows persisted before the defs blob existed (or if\n * the blob is missing/corrupt).\n */\nexport const resolveOpenApiBackedTools = ({\n integration,\n config,\n storage,\n}: {\n readonly integration: { readonly slug: string };\n readonly config: unknown;\n readonly storage: OpenapiStore;\n}): Effect.Effect<ResolveToolsResult, StorageFailure> =>\n Effect.gen(function* () {\n const incomplete = (reason: string): ResolveToolsResult => ({\n tools: [],\n definitions: {},\n incomplete: true,\n incompleteReason: reason,\n });\n const openApiConfig = decodeOpenApiIntegrationConfig(config);\n if (!openApiConfig) return { tools: [], definitions: {} };\n if (openApiConfig.specHash != null) {\n const defsJson = yield* storage\n .getDefs(openApiConfig.specHash)\n .pipe(Effect.catch(() => Effect.succeed(null)));\n if (defsJson != null) {\n const definitions = Option.getOrNull(decodeDefsJson(defsJson));\n if (definitions != null) {\n const ops = yield* storage\n .listOperations(String(integration.slug))\n .pipe(Effect.catch(() => Effect.succeed(null)));\n if (ops == null) return incomplete(\"OpenAPI operation bindings could not be loaded.\");\n return { tools: ops.map(toolDefFromStoredOperation), definitions };\n }\n }\n }\n const specText = yield* loadOpenApiSpecText(storage, openApiConfig).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n if (specText == null) return incomplete(\"OpenAPI spec blob could not be loaded.\");\n const compiled = yield* compileOpenApiSpecCached(openApiConfig.specHash, specText).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n if (!compiled) return incomplete(\"OpenAPI spec could not be parsed.\");\n return {\n tools: openApiToolDefsFromCompiled(compiled),\n definitions: compiled.hoistedDefs,\n };\n });\n\nexport const invokeOpenApiBackedTool = (input: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly toolRow: { readonly integration: string; readonly name: string };\n readonly credential: ToolInvocationCredential;\n readonly args: unknown;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>;\n readonly invokeOptions?: InvokeOptions;\n}) =>\n Effect.gen(function* () {\n const integration = input.toolRow.integration;\n const config = decodeOpenApiIntegrationConfig(input.credential.config);\n\n let binding = (yield* input.ctx.storage.getOperation(integration, input.toolRow.name))?.binding;\n // Only re-parse when the binding is entirely absent (a legacy row predating\n // persisted bindings). A present binding is authoritative even if it has no\n // responseBody: the persisted spec is now the *full* source (37MB for\n // Microsoft Graph), so re-parsing it here to \"enrich\" a binding would OOM\n // the isolate. A genuinely body-less operation must serve from its binding.\n if (!binding && config) {\n const specText = yield* loadOpenApiSpecText(input.ctx.storage, config).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n const compiled =\n specText == null\n ? null\n : yield* compileOpenApiSpecCached(config.specHash, specText).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n binding = compiled\n ? openApiStoredOperationsFromCompiled(integration, compiled).find(\n (op) => op.toolName === input.toolRow.name,\n )?.binding\n : undefined;\n }\n if (!binding) {\n return yield* new OpenApiExtractionError({\n message: `No OpenAPI operation found for tool \"${input.toolRow.name}\" on \"${integration}\"`,\n });\n }\n\n const headers: Record<string, string> = { ...(config?.headers ?? {}) };\n const queryParams: Record<string, string> = {\n ...(config?.queryParams ?? {}),\n };\n\n const template = (config?.authenticationTemplate ?? []).find(\n (entry) => String(entry.slug) === String(input.credential.template),\n );\n if (template) {\n const missing = requiredTemplateVariables(template).filter((name) => {\n const value = input.credential.values[name];\n return value == null || value === \"\";\n });\n if (missing.length > 0) {\n return openApiAuthToolFailure({\n code:\n template.kind === \"oauth2\" ? \"oauth_connection_missing\" : \"connection_value_missing\",\n message: `Connection \"${input.credential.connection}\" for \"${integration}\" has no resolvable credential value. Re-authenticate or update the connection.`,\n owner: input.credential.owner,\n integration,\n connection: String(input.credential.connection),\n credentialKind: template.kind === \"oauth2\" ? \"oauth\" : \"secret\",\n });\n }\n const rendered = renderAuthTemplate(template, input.credential.values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n }\n\n const invocation = yield* invokeWithLayer(\n binding,\n (input.args ?? {}) as Record<string, unknown>,\n config?.baseUrl ?? \"\",\n headers,\n queryParams,\n input.httpClientLayer,\n input.invokeOptions,\n ).pipe(\n Effect.map((result) => ({ ok: true as const, result })),\n Effect.catchTag(\"OpenApiInvocationError\", (error: OpenApiInvocationError) =>\n error.reason === \"response_headers_timeout\"\n ? Effect.succeed({\n ok: false as const,\n failure: ToolResult.fail({\n code: \"upstream_response_headers_timeout\",\n message: error.message,\n details: error.cause ?? error,\n }),\n })\n : Effect.fail(error),\n ),\n );\n\n if (!invocation.ok) return invocation.failure;\n\n const result = invocation.result;\n const ok = result.status >= 200 && result.status < 300;\n if (!ok) {\n if (result.status === 401 || result.status === 403) {\n // A 403 naming a scope shortfall (RFC 6750 insufficient_scope,\n // Google's ACCESS_TOKEN_SCOPE_INSUFFICIENT) cannot be fixed by\n // re-running the same grant, so it gets its own code and recovery\n // guidance instead of the re-authenticate loop.\n const insufficientScope =\n result.status === 403\n ? detectInsufficientScope({ body: result.error, headers: result.headers })\n : null;\n if (insufficientScope) {\n // Name the shortfall as precisely as the data allows: the scopes\n // the upstream challenge asked for, else the operation's declared\n // requirement (from the binding; alternatives joined with \"or\",\n // since each Security Requirement Object is one acceptable set),\n // plus what the connection's grant actually holds. Advisory only —\n // the upstream made the call; this annotation tells the agent/user\n // what to reconnect with.\n const required =\n insufficientScope.requiredScopes.length > 0\n ? insufficientScope.requiredScopes.join(\" \")\n : (binding.requiredScopeAlternatives ?? [])\n .map((alternative) => alternative.join(\" \"))\n .join(\", or \");\n const granted = input.credential.grantedScopes;\n return openApiAuthToolFailure({\n code: \"oauth_scope_insufficient\",\n status: result.status,\n message: `The connection \"${input.credential.connection}\" for \"${integration}\" is authorized, but its grant${granted && granted.length > 0 ? ` (${granted.join(\" \")})` : \"\"} does not cover the scope this operation requires${required.length > 0 ? ` (${required})` : \"\"}. Re-authenticating with the same grant will return the same error; reconnect with broader access.`,\n owner: input.credential.owner,\n integration,\n connection: String(input.credential.connection),\n credentialKind: \"oauth\",\n credentialLabel: \"Upstream authorization\",\n details: result.error,\n });\n }\n return openApiAuthToolFailure({\n code: \"connection_rejected\",\n status: result.status,\n message: `Upstream rejected credentials for \"${integration}\" with HTTP ${result.status}. Re-authenticate or update the connection \"${input.credential.connection}\" before retrying this tool.`,\n owner: input.credential.owner,\n integration,\n connection: String(input.credential.connection),\n credentialKind: \"upstream\",\n credentialLabel: \"Upstream authorization\",\n details: result.error,\n });\n }\n return ToolResult.fail({\n code: \"upstream_http_error\",\n status: result.status,\n message: extractOpenApiUpstreamMessage(result.error, result.status),\n details: result.error,\n });\n }\n return ToolResult.ok(result.data, {\n http: { status: result.status, headers: result.headers },\n });\n });\n\n/** Pre-approval argument validation: run the exact request-building pass\n * `invoke` runs (path params, request body, base64 payloads) and discard the\n * built request. Fails with the same pre-flight OpenApiInvocationError the\n * real invocation would raise, so a call guaranteed to fail is rejected\n * before the executor pauses it for approval. Legacy rows without a\n * persisted binding skip validation (re-parsing the spec here would repeat\n * invokeTool's heavy fallback for no user-visible gain). */\nexport const validateOpenApiBackedToolArgs = (input: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly toolRow: { readonly integration: string; readonly name: string };\n readonly args: unknown;\n}) =>\n Effect.gen(function* () {\n const operation = yield* input.ctx.storage.getOperation(\n input.toolRow.integration,\n input.toolRow.name,\n );\n if (!operation) return;\n yield* buildRequest(operation.binding, (input.args ?? {}) as Record<string, unknown>, {});\n });\n\nexport const resolveOpenApiBackedAnnotations = (input: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly integration: string;\n readonly toolRows: readonly { readonly name: string }[];\n}) =>\n Effect.gen(function* () {\n const out: Record<string, ReturnType<typeof annotationsForOperation>> = {};\n for (const row of input.toolRows) {\n const operation = yield* input.ctx.storage.getOperation(input.integration, row.name);\n if (!operation) continue;\n out[row.name] = annotationsForOperation(\n operation.binding.method,\n operation.binding.pathTemplate,\n );\n }\n return out;\n });\n\n// ---------------------------------------------------------------------------\n// Health checks: the declared liveness/identity probe for a connection.\n// ---------------------------------------------------------------------------\n\n/** Resolve the invocation binding for a health-check operation. Unlike the tool\n * invoke path we do not need `responseBody` (the probe reads the raw response),\n * so the stored binding is enough; only recompile the spec when it is missing\n * (e.g. an operation added to the spec but not yet persisted). */\nconst resolveHealthCheckBinding = (\n ctx: PluginCtx<OpenapiStore>,\n integration: string,\n operation: string,\n config: OpenApiIntegrationConfig | null,\n): Effect.Effect<OperationBinding | undefined, StorageFailure> =>\n Effect.gen(function* () {\n const stored = (yield* ctx.storage.getOperation(integration, operation))?.binding;\n if (stored) return stored;\n if (!config) return undefined;\n const specText = yield* loadOpenApiSpecText(ctx.storage, config).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n if (specText == null) return undefined;\n const compiled = yield* compileOpenApiSpecCached(config.specHash, specText).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n if (!compiled) return undefined;\n return openApiStoredOperationsFromCompiled(integration, compiled).find(\n (op) => op.toolName === operation,\n )?.binding;\n });\n\n/** Run the given probe against a resolved credential and classify the outcome.\n * The spec is resolved by CORE (its own storage) and passed in; this never\n * reads it from the plugin config. Never fails for credential/upstream\n * reasons: a rejected credential is a `HealthCheckResult` with\n * `status: \"expired\"`, not an error. */\nexport const checkHealthOpenApi = (input: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly integration: IntegrationRecord;\n readonly credential: ToolInvocationCredential;\n readonly spec?: HealthCheckSpec;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>;\n}): Effect.Effect<HealthCheckResult, StorageFailure> =>\n Effect.gen(function* () {\n const checkedAt = Date.now();\n const config = decodeOpenApiIntegrationConfig(input.integration.config);\n const spec = input.spec;\n if (!spec) {\n return {\n status: \"unknown\",\n checkedAt,\n detail: \"No health check configured.\",\n } satisfies HealthCheckResult;\n }\n\n const integration = String(input.integration.slug);\n const binding = yield* resolveHealthCheckBinding(\n input.ctx,\n integration,\n spec.operation,\n config,\n );\n if (!binding) {\n return {\n status: \"unknown\",\n checkedAt,\n detail: `Health check operation \"${spec.operation}\" not found on \"${integration}\".`,\n } satisfies HealthCheckResult;\n }\n\n // HARD block, not just a ranking hint: a health check runs unattended and\n // repeatedly, so a mutating operation must never execute through it. The\n // normal tool path gates these behind approval, and this path has no\n // approval step. The candidate list labels these \"(writes)\"; refusing here\n // is the enforcement.\n if (REQUIRE_APPROVAL.has(binding.method.toLowerCase())) {\n return {\n status: \"unknown\",\n checkedAt,\n detail: `Health check operation \"${spec.operation}\" is a ${binding.method.toUpperCase()} (mutating): pick a read-only operation.`,\n } satisfies HealthCheckResult;\n }\n\n const headers: Record<string, string> = { ...(config?.headers ?? {}) };\n const queryParams: Record<string, string> = { ...(config?.queryParams ?? {}) };\n\n const template = (config?.authenticationTemplate ?? []).find(\n (entry) => String(entry.slug) === String(input.credential.template),\n );\n if (template) {\n const missing = requiredTemplateVariables(template).filter((name) => {\n const value = input.credential.values[name];\n return value == null || value === \"\";\n });\n if (missing.length > 0) {\n return {\n status: \"expired\",\n checkedAt,\n detail: `Connection \"${input.credential.connection}\" has no resolvable credential value.`,\n } satisfies HealthCheckResult;\n }\n const rendered = renderAuthTemplate(template, input.credential.values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n }\n\n // `invokeWithLayer` fails only with the typed `OpenApiInvocationError`\n // (transport / body-read failures before an HTTP status); fold it onto the\n // success channel so a dead upstream reads as `degraded`, not a thrown error.\n const probe = yield* invokeWithLayer(\n binding,\n { ...(spec.args ?? {}) } as Record<string, unknown>,\n config?.baseUrl ?? \"\",\n headers,\n queryParams,\n input.httpClientLayer,\n ).pipe(\n Effect.map((result) => ({ ok: true as const, result })),\n Effect.catch((failure) => Effect.succeed({ ok: false as const, failure })),\n );\n\n // Upstream error text can echo the request back (URLs with query params,\n // auth headers), so scrub every credential value out of anything that leaves\n // as `detail` so a probe can never leak the secret it authenticated with.\n const secretValues = Object.values(input.credential.values).filter(\n (value): value is string => typeof value === \"string\" && value.length > 0,\n );\n const scrubSecrets = (text: string): string =>\n secretValues.reduce((out, secret) => out.split(secret).join(\"[redacted]\"), text);\n\n if (!probe.ok) {\n return {\n status: \"degraded\",\n checkedAt,\n detail: scrubSecrets(`Health check request failed: ${probe.failure.message}`),\n } satisfies HealthCheckResult;\n }\n\n const status = classifyHttpStatus(probe.result.status);\n const identity =\n status === \"healthy\" ? extractIdentity(probe.result.data, spec.identityField) : undefined;\n // Sample the returned body ONLY on a healthy probe: the sample exists to\n // pick an identity field, and error bodies (upstream internals, auth error\n // envelopes) have no business in the preview. Non-healthy runs carry the\n // classified `detail` instead.\n const responseSample = status === \"healthy\" ? extractResponseFields(probe.result.data) : [];\n return {\n status,\n httpStatus: probe.result.status,\n ...(identity !== undefined ? { identity } : {}),\n checkedAt,\n ...(responseSample.length > 0 ? { responseSample } : {}),\n ...(status === \"healthy\"\n ? {}\n : {\n detail: scrubSecrets(\n extractOpenApiUpstreamMessage(probe.result.error, probe.result.status),\n ),\n }),\n } satisfies HealthCheckResult;\n });\n\n/** List the operations a user can pick as the health check, ranked\n * non-destructive-first then fewest-required-args so the obvious \"GET /me\"\n * identity endpoint floats to the top. Recompiles the spec once (best-effort)\n * to recover human summaries the stored binding does not keep. */\nexport const listHealthCheckCandidatesOpenApi = (input: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly integration: IntegrationRecord;\n}): Effect.Effect<readonly HealthCheckCandidate[], StorageFailure> =>\n Effect.gen(function* () {\n const integration = String(input.integration.slug);\n const operations = yield* input.ctx.storage.listOperations(integration);\n const config = decodeOpenApiIntegrationConfig(input.integration.config);\n\n const summaries = new Map<string, string>();\n const responseFieldsByTool = new Map<string, readonly HealthCheckResponseField[]>();\n if (config) {\n const specText = yield* loadOpenApiSpecText(input.ctx.storage, config).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n const compiled =\n specText == null\n ? null\n : yield* compileOpenApiSpecCached(config.specHash, specText).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n if (compiled) {\n for (const def of compiled.definitions) {\n const summary =\n Option.getOrUndefined(def.operation.summary) ??\n Option.getOrUndefined(def.operation.description);\n if (summary) summaries.set(def.toolPath, summary);\n // `outputSchema` is NOT pre-normalized; `hoistedDefs` ARE, so normalize\n // the schema before walking refs against them.\n const fields = projectResponseFields(\n normalizeOpenApiRefs(Option.getOrUndefined(def.operation.outputSchema)),\n compiled.hoistedDefs,\n );\n if (fields.length > 0) responseFieldsByTool.set(def.toolPath, fields);\n }\n }\n }\n\n const candidates = operations.map((op): HealthCheckCandidate => {\n const method = op.binding.method.toLowerCase();\n const parameters = op.binding.parameters.map((parameter) => ({\n name: parameter.name,\n location: parameter.location,\n required: parameter.required,\n ...(Option.isSome(parameter.description)\n ? { description: parameter.description.value }\n : {}),\n }));\n const responseFields = responseFieldsByTool.get(op.toolName);\n return {\n operation: op.toolName,\n method,\n requiredArgCount: op.binding.parameters.filter((parameter) => parameter.required).length,\n destructive: REQUIRE_APPROVAL.has(method),\n summary: summaries.get(op.toolName) ?? `${method.toUpperCase()} ${op.binding.pathTemplate}`,\n ...(parameters.length > 0 ? { parameters } : {}),\n ...(responseFields && responseFields.length > 0 ? { responseFields } : {}),\n };\n });\n return sortHealthCheckCandidatesByIdentity(candidates);\n });\n","import { Effect, Option, Predicate } from \"effect\";\nimport { Schema } from \"effect\";\n\nimport {\n HealthCheckCandidate,\n compareHealthCheckCandidates,\n projectResponseFields,\n} from \"@rafads/sdk/core\";\n\nimport { parse, resolveSpecText, type ParsedDocument } from \"./parse\";\nimport { extract } from \"./extract\";\nimport { compileToolDefinitions } from \"./definitions\";\nimport { normalizeOpenApiRefs } from \"./backing\";\nimport { DocResolver } from \"./openapi-utils\";\nimport { HttpMethod, ServerInfo, type ExtractedOperation, type ExtractionResult } from \"./types\";\n\n// Mutating HTTP methods: mirrors `REQUIRE_APPROVAL` in `./invoke` but kept\n// inline so this browser-safe preview module never pulls in the HTTP execution\n// path. A health check should be safe to re-run, so these rank last.\nconst DESTRUCTIVE_METHODS = new Set([\"post\", \"put\", \"patch\", \"delete\"]);\n\n// Cap on health-check candidate METADATA carried in the preview, so the add\n// screen's operation picker can search the whole spec (not just a top few).\n// Building this is cheap (the rank/sort already runs over every operation); only\n// the payload grows, so the cap bounds Graph-sized specs (16k+ ops) to the\n// top-ranked 1000. Beyond that, the picker stays freeform (type an exact op).\nconst MAX_PREVIEW_CANDIDATES = 1000;\n\n// Cap on how many carried candidates get their response schema WALKED for the\n// typed identity picker. Walking is the only expensive part, so it stays small:\n// the top-ranked survivors get typed identity fields; the long tail is\n// metadata-only and its identity picker falls back to a freeform dot-path.\nconst MAX_PREVIEW_RESPONSE_FIELD_CANDIDATES = 50;\n\n// ---------------------------------------------------------------------------\n// OAuth 2.0 flows — one entry per supported grant type\n// ---------------------------------------------------------------------------\n\n/** Scopes declared by a flow: `{ scopeName: description }` */\nconst OAuth2Scopes = Schema.Record(Schema.String, Schema.String);\nconst SecuritySchemeType = Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]);\ntype SecuritySchemeType = typeof SecuritySchemeType.Type;\n\nconst decodeSecuritySchemeType = Schema.decodeUnknownOption(SecuritySchemeType);\n\nexport const OAuth2AuthorizationCodeFlow = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2AuthorizationCodeFlow = typeof OAuth2AuthorizationCodeFlow.Type;\n\nexport const OAuth2ClientCredentialsFlow = Schema.Struct({\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2ClientCredentialsFlow = typeof OAuth2ClientCredentialsFlow.Type;\n\nexport const OAuth2Flows = Schema.Struct({\n authorizationCode: Schema.OptionFromOptional(OAuth2AuthorizationCodeFlow),\n clientCredentials: Schema.OptionFromOptional(OAuth2ClientCredentialsFlow),\n});\nexport type OAuth2Flows = typeof OAuth2Flows.Type;\n\n// ---------------------------------------------------------------------------\n// Security scheme — what the spec declares it needs\n// ---------------------------------------------------------------------------\n\nexport const SecurityScheme = Schema.Struct({\n /** Key name in components.securitySchemes (e.g. \"api_token\") */\n name: Schema.String,\n /** OpenAPI security scheme type */\n type: SecuritySchemeType,\n /** For type: \"http\" — e.g. \"bearer\", \"basic\" */\n scheme: Schema.OptionFromOptional(Schema.String),\n /** For type: \"http\" with scheme \"bearer\" — e.g. \"JWT\" */\n bearerFormat: Schema.OptionFromOptional(Schema.String),\n /** For type: \"apiKey\" — where the key goes */\n in: Schema.OptionFromOptional(Schema.Literals([\"header\", \"query\", \"cookie\"])),\n /** For type: \"apiKey\" — the header/query/cookie name */\n headerName: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n /** For type: \"oauth2\" — declared flows (authorizationCode / clientCredentials only; implicit and password are deprecated). */\n flows: Schema.OptionFromOptional(OAuth2Flows),\n /** For type: \"openIdConnect\" — the discovery URL. */\n openIdConnectUrl: Schema.OptionFromOptional(Schema.String),\n});\nexport type SecurityScheme = typeof SecurityScheme.Type;\n\n// ---------------------------------------------------------------------------\n// Auth strategy — a valid combination of security schemes\n// ---------------------------------------------------------------------------\n\nexport const AuthStrategy = Schema.Struct({\n /** The security schemes required together for this strategy */\n schemes: Schema.Array(Schema.String),\n});\nexport type AuthStrategy = typeof AuthStrategy.Type;\n\n// ---------------------------------------------------------------------------\n// Header preset — derived from an auth strategy\n// ---------------------------------------------------------------------------\n\nexport const HeaderPreset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"Bearer Token\", \"API Key + Email\") */\n label: Schema.String,\n /** Headers this strategy needs. Value is null when the user must provide it. */\n headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),\n /** Which headers should be stored as secrets */\n secretHeaders: Schema.Array(Schema.String),\n});\nexport type HeaderPreset = typeof HeaderPreset.Type;\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset — derived from an oauth2 security scheme + a flow choice\n// ---------------------------------------------------------------------------\n\nexport const OAuth2Preset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"OAuth2 (Authorization Code) — oauth_app\") */\n label: Schema.String,\n /** The source security scheme this preset came from (components.securitySchemes key). */\n securitySchemeName: Schema.String,\n /** Which OAuth2 flow this preset uses. */\n flow: Schema.Literals([\"authorizationCode\", \"clientCredentials\"]),\n /** For authorizationCode: user-agent redirect URL (from the spec). */\n authorizationUrl: Schema.OptionFromOptional(Schema.String),\n /** Token endpoint to exchange the code / refresh. */\n tokenUrl: Schema.String,\n /** RFC 8707 resource indicator discovered from protected-resource metadata. */\n resource: Schema.OptionFromOptional(Schema.String),\n /** Optional refresh endpoint if the spec declares one separately. */\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n /** Declared scopes for this flow: `{ scope: description }`. */\n scopes: Schema.Record(Schema.String, Schema.String),\n /** Identity scopes to request alongside API scopes. `\"auto\"` discovers standard OIDC scopes. */\n identityScopes: Schema.Union([\n Schema.Literal(\"auto\"),\n Schema.Literal(false),\n Schema.Array(Schema.String),\n ]),\n /** Provider metadata advertised Client ID Metadata Document support. */\n supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\n});\nexport type OAuth2Preset = typeof OAuth2Preset.Type;\n\n// ---------------------------------------------------------------------------\n// Preview operation — lightweight shape for the add-integration UI list\n// ---------------------------------------------------------------------------\n\nexport const PreviewOperation = Schema.Struct({\n operationId: Schema.String,\n method: HttpMethod,\n path: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n deprecated: Schema.Boolean,\n});\nexport type PreviewOperation = typeof PreviewOperation.Type;\n\n// ---------------------------------------------------------------------------\n// Spec preview — everything the frontend needs\n// ---------------------------------------------------------------------------\n\nexport const SpecPreview = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n /** The spec's `info.description` — prefills the add form's description field. */\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n /** Reuses ServerInfo from extraction */\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n /** Lightweight operation list for the add-integration UI */\n operations: Schema.Array(PreviewOperation),\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n /** Valid auth strategies (each is a set of schemes used together) */\n authStrategies: Schema.Array(AuthStrategy),\n /** Pre-built header presets derived from auth strategies */\n headerPresets: Schema.Array(HeaderPreset),\n /** OAuth2 presets — one per (oauth2 scheme × supported flow) combination */\n oauth2Presets: Schema.Array(OAuth2Preset),\n /** Top-ranked health-check candidates (bounded), so the add screen can offer a\n * typed operation + identity picker before the integration is registered. */\n healthCheckCandidates: Schema.Array(HealthCheckCandidate),\n});\nexport type SpecPreview = typeof SpecPreview.Type;\n\n// HTTP/UI preview deliberately omits the per-operation list. Graph-sized specs\n// can define 16k+ operations, while the add flow only needs counts, tags,\n// servers, and auth metadata before registration.\nexport const SpecPreviewSummary = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n authStrategies: Schema.Array(AuthStrategy),\n headerPresets: Schema.Array(HeaderPreset),\n oauth2Presets: Schema.Array(OAuth2Preset),\n healthCheckCandidates: Schema.Array(HealthCheckCandidate),\n});\nexport type SpecPreviewSummary = typeof SpecPreviewSummary.Type;\n\nexport const specPreviewSummary = (preview: SpecPreview): SpecPreviewSummary =>\n SpecPreviewSummary.make({\n title: preview.title,\n description: preview.description,\n version: preview.version,\n servers: preview.servers,\n operationCount: preview.operationCount,\n tags: preview.tags,\n securitySchemes: preview.securitySchemes,\n authStrategies: preview.authStrategies,\n headerPresets: preview.headerPresets,\n oauth2Presets: preview.oauth2Presets,\n healthCheckCandidates: preview.healthCheckCandidates,\n });\n\n// ---------------------------------------------------------------------------\n// Security scheme extraction\n// ---------------------------------------------------------------------------\n\nconst stringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n};\n\nconst extractFlows = (rawFlows: unknown): Option.Option<OAuth2Flows> => {\n if (!rawFlows || typeof rawFlows !== \"object\") return Option.none();\n const flows = rawFlows as Record<string, unknown>;\n\n const parseFlow = <K extends \"authorizationCode\" | \"clientCredentials\">(key: K): unknown =>\n flows[key];\n\n let authorizationCode: Option.Option<OAuth2AuthorizationCodeFlow> = Option.none();\n const authCodeRaw = parseFlow(\"authorizationCode\");\n if (authCodeRaw && typeof authCodeRaw === \"object\") {\n const f = authCodeRaw as Record<string, unknown>;\n const authUrl = typeof f.authorizationUrl === \"string\" ? f.authorizationUrl : null;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (authUrl && tokenUrl) {\n authorizationCode = Option.some(\n OAuth2AuthorizationCodeFlow.make({\n authorizationUrl: authUrl,\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n let clientCredentials: Option.Option<OAuth2ClientCredentialsFlow> = Option.none();\n const ccRaw = parseFlow(\"clientCredentials\");\n if (ccRaw && typeof ccRaw === \"object\") {\n const f = ccRaw as Record<string, unknown>;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (tokenUrl) {\n clientCredentials = Option.some(\n OAuth2ClientCredentialsFlow.make({\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n if (Option.isNone(authorizationCode) && Option.isNone(clientCredentials)) {\n return Option.none();\n }\n return Option.some(OAuth2Flows.make({ authorizationCode, clientCredentials }));\n};\n\nconst extractSecuritySchemes = (\n rawSchemes: Record<string, unknown>,\n resolver: DocResolver,\n): SecurityScheme[] =>\n Object.entries(rawSchemes).flatMap(([name, schemeOrRef]) => {\n if (!schemeOrRef || typeof schemeOrRef !== \"object\") return [];\n // Resolve $ref so schemes defined via `$ref` aren't silently dropped.\n const resolved = resolver.resolve<Record<string, unknown>>(\n schemeOrRef as Record<string, unknown>,\n );\n if (!resolved || typeof resolved !== \"object\") return [];\n const scheme = resolved;\n\n const type = decodeSecuritySchemeType(scheme.type);\n if (Option.isNone(type)) return [];\n const schemeType = type.value;\n\n return [\n SecurityScheme.make({\n name,\n type: schemeType,\n scheme: Option.fromNullishOr(scheme.scheme as string | undefined),\n bearerFormat: Option.fromNullishOr(scheme.bearerFormat as string | undefined),\n in: Option.fromNullishOr(scheme.in as \"header\" | \"query\" | \"cookie\" | undefined),\n headerName: Option.fromNullishOr(scheme.name as string | undefined),\n description: Option.fromNullishOr(scheme.description as string | undefined),\n flows: schemeType === \"oauth2\" ? extractFlows(scheme.flows) : Option.none(),\n openIdConnectUrl: Option.fromNullishOr(scheme.openIdConnectUrl as string | undefined),\n }),\n ];\n });\n\n// ---------------------------------------------------------------------------\n// Header preset builder\n// ---------------------------------------------------------------------------\n\nconst buildHeaderPresets = (\n schemes: readonly SecurityScheme[],\n strategies: readonly AuthStrategy[],\n): HeaderPreset[] => {\n const schemeMap = new Map(schemes.map((s) => [s.name, s]));\n\n return strategies.flatMap((strategy) => {\n const resolved = strategy.schemes\n .map((name) => schemeMap.get(name))\n .filter(Predicate.isNotUndefined);\n\n if (resolved.length === 0) return [];\n\n const headers: Record<string, string | null> = {};\n const secretHeaders: string[] = [];\n const labelParts: string[] = [];\n\n for (const scheme of resolved) {\n if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"bearer\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Bearer Token\");\n } else if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"basic\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Basic Auth\");\n } else if (scheme.type === \"apiKey\" && Option.getOrElse(scheme.in, () => \"\") === \"header\") {\n const headerName = Option.getOrElse(scheme.headerName, () => scheme.name);\n headers[headerName] = null;\n secretHeaders.push(headerName);\n labelParts.push(scheme.name);\n } else if (scheme.type === \"apiKey\") {\n labelParts.push(`${scheme.name} (${Option.getOrElse(scheme.in, () => \"unknown\")})`);\n } else if (scheme.type === \"oauth2\" || scheme.type === \"openIdConnect\") {\n return [];\n } else {\n labelParts.push(scheme.name);\n }\n }\n\n if (Object.keys(headers).length === 0 && resolved.length > 0) {\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers: {},\n secretHeaders: [],\n }),\n ];\n }\n\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers,\n secretHeaders,\n }),\n ];\n });\n};\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset builder\n// ---------------------------------------------------------------------------\n\nconst buildOAuth2Presets = (schemes: readonly SecurityScheme[]): OAuth2Preset[] => {\n const presets: OAuth2Preset[] = [];\n for (const scheme of schemes) {\n if (scheme.type !== \"oauth2\") continue;\n if (Option.isNone(scheme.flows)) continue;\n const flows = scheme.flows.value;\n\n if (Option.isSome(flows.authorizationCode)) {\n const flow = flows.authorizationCode.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Authorization Code · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"authorizationCode\",\n authorizationUrl: Option.some(flow.authorizationUrl),\n tokenUrl: flow.tokenUrl,\n resource: Option.none(),\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: \"auto\",\n }),\n );\n }\n\n if (Option.isSome(flows.clientCredentials)) {\n const flow = flows.clientCredentials.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Client Credentials · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"clientCredentials\",\n authorizationUrl: Option.none(),\n tokenUrl: flow.tokenUrl,\n resource: Option.none(),\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: false,\n }),\n );\n }\n }\n return presets;\n};\n\n// ---------------------------------------------------------------------------\n// Collect unique tags from extraction result\n// ---------------------------------------------------------------------------\n\nconst collectTags = (result: ExtractionResult): string[] => {\n const tagSet = new Set<string>();\n for (const op of result.operations) {\n for (const tag of op.tags) tagSet.add(tag);\n }\n return [...tagSet].sort();\n};\n\n// ---------------------------------------------------------------------------\n// Health-check candidates (bounded) for the add screen\n// ---------------------------------------------------------------------------\n\n/**\n * Project the top-ranked health-check candidates from a parsed doc + its\n * extracted operations, so the add screen can offer a typed operation/identity\n * picker before registration.\n *\n * Tool paths are computed on the FULL operation set (`compileToolDefinitions`\n * collision resolution is stateful, so they must match the paths the operations\n * get at registration). Candidates are ranked, sliced to `MAX_PREVIEW_CANDIDATES`\n * (enough for the operation picker to search the whole spec), and only the\n * top `MAX_PREVIEW_RESPONSE_FIELD_CANDIDATES` get their response schema walked for\n * the typed identity field; the rest stay metadata-only (freeform identity).\n */\nconst buildPreviewHealthCheckCandidates = (\n doc: ParsedDocument,\n operations: readonly ExtractedOperation[],\n): HealthCheckCandidate[] => {\n if (operations.length === 0) return [];\n\n const definitions = compileToolDefinitions(operations);\n\n const ranked = definitions\n .map((def): HealthCheckCandidate => {\n const op = def.operation;\n const method = op.method.toLowerCase();\n const parameters = op.parameters.map((parameter) => ({\n name: parameter.name,\n location: parameter.location,\n required: parameter.required,\n ...(Option.isSome(parameter.description)\n ? { description: parameter.description.value }\n : {}),\n }));\n return {\n operation: def.toolPath,\n method,\n requiredArgCount: op.parameters.filter((parameter) => parameter.required).length,\n destructive: DESTRUCTIVE_METHODS.has(method),\n summary:\n Option.getOrUndefined(op.summary) ??\n Option.getOrUndefined(op.description) ??\n `${method.toUpperCase()} ${op.pathTemplate}`,\n ...(parameters.length > 0 ? { parameters } : {}),\n };\n })\n .sort(compareHealthCheckCandidates)\n .slice(0, MAX_PREVIEW_CANDIDATES);\n\n // Walk response schemas only for the top survivors (the realistic health-check\n // picks). `outputSchema` is NOT pre-normalized; the hoisted `$defs` ARE, so\n // normalize the schema first. The rest are returned metadata-only so the\n // operation picker still lists them while keeping schema walking bounded.\n const hoistedDefs: Record<string, unknown> = {};\n const rawSchemas = doc.components?.schemas;\n if (rawSchemas) {\n for (const [name, schema] of Object.entries(rawSchemas)) {\n hoistedDefs[name] = normalizeOpenApiRefs(schema);\n }\n }\n const operationByToolPath = new Map(definitions.map((def) => [def.toolPath, def.operation]));\n\n return ranked.map((candidate, index): HealthCheckCandidate => {\n if (index >= MAX_PREVIEW_RESPONSE_FIELD_CANDIDATES) return candidate;\n const op = operationByToolPath.get(candidate.operation);\n if (!op) return candidate;\n const responseFields = projectResponseFields(\n normalizeOpenApiRefs(Option.getOrUndefined(op.outputSchema)),\n hoistedDefs,\n );\n return responseFields.length > 0 ? { ...candidate, responseFields } : candidate;\n });\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** Preview already-resolved spec text — extract metadata without registering\n * anything and without any HTTP dependency. */\nexport const previewSpecText = Effect.fn(\"OpenApi.previewSpecText\")(function* (specText: string) {\n const doc: ParsedDocument = yield* parse(specText);\n const result = yield* extract(doc);\n\n const resolver = new DocResolver(doc);\n const securitySchemes = extractSecuritySchemes(doc.components?.securitySchemes ?? {}, resolver);\n\n const rawSecurity = (doc.security ?? []) as Array<Record<string, unknown>>;\n const declaredStrategies = rawSecurity.map((entry) =>\n AuthStrategy.make({ schemes: Object.keys(entry) }),\n );\n // Fall back to one strategy per scheme when the spec only declares schemes\n // under components (e.g. Sentry) so the user still sees auth options.\n const authStrategies =\n declaredStrategies.length > 0\n ? declaredStrategies\n : securitySchemes.map((scheme) => AuthStrategy.make({ schemes: [scheme.name] }));\n\n return SpecPreview.make({\n title: result.title,\n description: result.description,\n version: result.version,\n servers: result.servers,\n operationCount: result.operations.length,\n operations: result.operations.map((op) =>\n PreviewOperation.make({\n operationId: op.operationId,\n method: op.method,\n path: op.pathTemplate,\n summary: op.summary,\n tags: op.tags,\n deprecated: op.deprecated,\n }),\n ),\n tags: collectTags(result),\n securitySchemes,\n authStrategies,\n headerPresets: buildHeaderPresets(securitySchemes, authStrategies),\n oauth2Presets: buildOAuth2Presets(securitySchemes),\n healthCheckCandidates: buildPreviewHealthCheckCandidates(doc, result.operations),\n });\n});\n\n/** Preview an OpenAPI spec — extract metadata without registering anything.\n * Accepts either a URL or raw JSON/YAML text. */\nexport const previewSpec = Effect.fn(\"OpenApi.previewSpec\")(function* (input: string) {\n const specText = yield* resolveSpecText(input);\n return yield* previewSpecText(specText);\n});\n"],"mappings":";;;;;;;;;;;;;;;;AACA,SAAS,UAAU,QAAQ,cAAc;AACzC,SAAS,YAAY,yBAAyB;AAC9C,SAAS,aAAa,QAAQ,yBAAyB;AAYvD,IAAM,kCAAN,cAA8C,uBAAuB;AAAC;AAQ/D,IAAM,gBAAgB,OAAO,GAAG,uBAAuB,EAAE,WAC9D,KACA,aACA;AACA,QAAM,SAAS,OAAO,WAAW;AACjC,QAAM,aAAa,IAAI,IAAI,GAAG;AAC9B,aAAW,CAAC,MAAM,K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AAAA,IAChB,SAAS,OAAO;AAAA,IAChB,gBAAgB,OAAO,WAAW;AAAA,IAClC,YAAY,OAAO,WAAW;AAAA,MAAI,CAAC,OACjC,iBAAiB,KAAK;AAAA,QACpB,aAAa,GAAG;AAAA,QAChB,QAAQ,GAAG;AAAA,QACX,MAAM,GAAG;AAAA,QACT,SAAS,GAAG;AAAA,QACZ,MAAM,GAAG;AAAA,QACT,YAAY,GAAG;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,IACA,MAAM,YAAY,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA,eAAe,mBAAmB,iBAAiB,cAAc;AAAA,IACjE,eAAe,mBAAmB,eAAe;AAAA,IACjD,uBAAuB,kCAAkC,KAAK,OAAO,UAAU;AAAA,EACjF,CAAC;AACH,CAAC;AAIM,IAAM,cAAcA,QAAO,GAAG,qBAAqB,EAAE,WAAW,OAAe;AACpF,QAAM,WAAW,OAAO,gBAAgB,KAAK;AAC7C,SAAO,OAAO,gBAAgB,QAAQ;AACxC,CAAC;","names":["Schema","Effect","Option","group","leaf","Option","Effect","Effect","Option","Schema","HttpClient","HttpClientRequest","Option","Effect","HttpClientRequest","Schema","bytes","HttpClient","Effect","Option","Schema","Schema","Option","message","changed","Effect","Effect","Option","Schema","result","Effect","Option","Schema","projectResponseFields","Schema","Option","projectResponseFields","Effect"]}