@dual-os/sdk 0.9.2 → 0.10.0

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.
package/dist/Http.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Http.js","names":["ToolFile.Schema","Files.read","Files.File","Action.ActionHandlerError","Action.fromHttpClientFailure","Files.write","Mcp.connect","Mcp.CallToolResult","Mcp.McpError"],"sources":["../src/Http.ts"],"sourcesContent":["/**\n * The HTTP runtime of generated API plugins: each operation's contract and call, request encoding,\n * response decoding, continuation links, redirects and uploads.\n *\n * @since 0.0.0\n */\nimport {\n Array,\n Boolean,\n DateTime,\n Effect,\n Equal,\n Option,\n Order,\n Predicate,\n Random,\n Record,\n Result,\n Schema,\n SchemaGetter,\n SchemaIssue,\n String,\n flow,\n pipe,\n} from \"effect\";\nimport type { SchemaAST } from \"effect\";\n\nimport { Base64, Base64Url } from \"effect/encoding\";\nimport {\n FetchHttpClient,\n HttpBody,\n HttpClient,\n HttpClientError,\n HttpClientRequest,\n Headers,\n UrlParams,\n} from \"effect/http\";\nimport type { HttpClientResponse } from \"effect/http\";\n\nimport * as Action from \"./Action.ts\";\nimport type * as AuthMethod from \"./AuthMethod.ts\";\nimport { Files } from \"./Files.ts\";\nimport { Mcp } from \"./Mcp.ts\";\nimport * as ToolFile from \"./ToolFile.ts\";\n\nfunction preserveJsonProperties<A, Input>(value: A, input: Input): A {\n if (Equal.equals(value, input)) return value;\n if (Array.isArray(value) && Array.isArray(input)) {\n for (const entry of Array.zip(value, input)) preserveJsonProperties(entry[0], entry[1]);\n } else if (Predicate.isObject(value) && Predicate.isObject(input)) {\n for (const entry of Record.toEntries(input)) {\n if (Record.has(value, entry[0])) {\n preserveJsonProperties(value[entry[0]], entry[1]);\n } else {\n Object.defineProperty(value, entry[0], {\n configurable: true,\n enumerable: true,\n value: entry[1],\n writable: true,\n });\n }\n }\n }\n return value;\n}\n\nfunction decodeResponse<Output extends Schema.Top>(output: Output) {\n return flow(\n Effect.succeed,\n Effect.flatMap(input =>\n pipe(\n Schema.decodeUnknownEffect(output)(input),\n Effect.map(value => preserveJsonProperties(value, input)),\n ),\n ),\n );\n}\n\n/**\n * An action's input and output schemas.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface Contract {\n readonly input: Schema.Top;\n readonly output: Schema.Top;\n}\n\n/**\n * Runs an action: its input in, its output or a failure out.\n *\n * @since 0.0.0\n * @category models\n */\nexport type Handler<Methods extends readonly AuthMethod.Any[], Input, Output> = (\n input: Input,\n context: Action.HandlerContext<Methods>,\n) => Effect.Effect<Output, Action.ActionHandlerFailure, HttpClient.HttpClient>;\n\n/**\n * A file input: a ToolFile as a download returns it, or just its bytes with a type and name.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport type File = typeof File.Type;\nexport const File = Schema.Struct({\n _tag: Schema.optionalKey(Schema.Literal(\"ToolFile\")),\n contentBase64: Schema.Uint8ArrayFromBase64,\n contentType: Schema.optionalKey(Schema.NullOr(Schema.String)),\n filename: Schema.optionalKey(Schema.NullOr(Schema.String)),\n sizeBytes: Schema.optionalKey(Schema.Natural),\n}).annotate({\n description:\n \"A ToolFile, such as the result of a download, passed unchanged; or its contentBase64 with an optional contentType and filename.\",\n});\n\nconst signatures: [string, [number, number[]][]][] = [\n [\"image/jpeg\", [[0, [0xff, 0xd8, 0xff]]]],\n [\"image/png\", [[0, [0x89, 0x50, 0x4e, 0x47]]]],\n [\"image/gif\", [[0, [0x47, 0x49, 0x46, 0x38]]]],\n [\n \"image/webp\",\n [\n [0, [0x52, 0x49, 0x46, 0x46]],\n [8, [0x57, 0x45, 0x42, 0x50]],\n ],\n ],\n [\"application/pdf\", [[0, [0x25, 0x50, 0x44, 0x46]]]],\n [\"application/zip\", [[0, [0x50, 0x4b, 0x03, 0x04]]]],\n];\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\n\nfunction sniff(bytes: Uint8Array) {\n return pipe(\n Array.findFirst(signatures, signature =>\n Array.every(signature[1], part =>\n Array.every(part[1], (byte, index) => bytes[part[0] + index] === byte),\n ),\n ),\n Option.map(signature => signature[0]),\n Option.orElse(() =>\n Option.liftPredicate(\"text/plain\", () =>\n Result.isSuccess(Result.try(() => utf8.decode(bytes))),\n ),\n ),\n Option.getOrNull,\n );\n}\n\nfunction toolFile(bytes: Uint8Array, declared: string | null, filename: string | null) {\n return {\n _tag: \"ToolFile\",\n contentBase64: Base64.encode(bytes),\n contentType:\n declared === null || pipe(declared, String.startsWith(\"application/octet-stream\"))\n ? (sniff(bytes) ?? declared)\n : declared,\n filename,\n sizeBytes: bytes.byteLength,\n } satisfies ToolFile.File;\n}\n\nfunction invalid(expected: string, value: unknown, options: SchemaAST.ParseOptions) {\n return Effect.fail(new SchemaIssue.InvalidValue({ expected }, value, options));\n}\n\nfunction decodeBytes(text: string, options: SchemaAST.ParseOptions) {\n return Result.match(\n Base64Url.decode(pipe(text, String.replaceAll(\"+\", \"-\"), String.replaceAll(\"/\", \"_\"))),\n {\n onFailure: () => invalid(\"a Base64 or Base64Url string\", text, options),\n onSuccess: bytes => Effect.succeed(bytes),\n },\n );\n}\n\ntype Carrier = \"base64\" | \"base64url\" | \"data-uri\";\n\ninterface Content {\n bytes: Uint8Array;\n contentType: string | null;\n}\n\nfunction contentOf(carrier: Carrier) {\n return SchemaGetter.transformEffect<Content, string>((text, options) => {\n if (carrier !== \"data-uri\") {\n return Effect.map(decodeBytes(text, options), bytes => ({ bytes, contentType: null }));\n }\n return Option.match(pipe(text, String.match(/^data:([^;,]*)(?:;[^;,]*)*;base64,(.*)$/su)), {\n onNone: () => invalid(\"a Base64 data URI\", text, options),\n onSome: parts =>\n Effect.map(decodeBytes(Array.getUnsafe(parts, 2), options), bytes => ({\n bytes,\n contentType: pipe(\n Array.getUnsafe(parts, 1),\n Option.liftPredicate(String.isNonEmpty),\n Option.getOrNull,\n ),\n })),\n });\n });\n}\n\nfunction textOf(carrier: Carrier, content: Content) {\n if (carrier === \"base64\") return Base64.encode(content.bytes);\n if (carrier === \"base64url\") return Base64Url.encode(content.bytes);\n const contentType = content.contentType ?? sniff(content.bytes) ?? \"application/octet-stream\";\n return `data:${contentType};base64,${Base64.encode(content.bytes)}`;\n}\n\nfunction fileFrom(carrier: Carrier) {\n return Schema.String.pipe(\n Schema.decodeTo(ToolFile.Schema, {\n decode: SchemaGetter.compose(\n contentOf(carrier),\n SchemaGetter.transform(content => toolFile(content.bytes, content.contentType, null)),\n ),\n encode: SchemaGetter.transformEffect((file: ToolFile.File, options) =>\n Effect.map(decodeBytes(file.contentBase64, options), bytes =>\n textOf(carrier, { bytes, contentType: file.contentType }),\n ),\n ),\n }),\n );\n}\n\nfunction encodedFrom(carrier: Carrier) {\n return File.pipe(\n Schema.decodeTo(Schema.String, {\n decode: SchemaGetter.transform(file =>\n textOf(carrier, { bytes: file.contentBase64, contentType: file.contentType ?? null }),\n ),\n encode: SchemaGetter.compose(\n contentOf(carrier),\n SchemaGetter.transform(content => ({\n contentBase64: content.bytes,\n contentType: content.contentType,\n })),\n ),\n }),\n );\n}\n\n/**\n * A file the API returns as a Base64 string inside JSON, decoded into a ToolFile with its content\n * type recognized from the bytes.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const FileFromBase64 = fileFrom(\"base64\");\n\n/**\n * {@link FileFromBase64} for an API that writes the file in Base64Url.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const FileFromBase64Url = fileFrom(\"base64url\");\n\n/**\n * A {@link File} input the API reads as a Base64 string inside JSON.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const Base64FromFile = encodedFrom(\"base64\");\n\n/**\n * {@link Base64FromFile} for an API that reads the file in Base64Url.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const Base64UrlFromFile = encodedFrom(\"base64url\");\n\n/**\n * {@link FileFromBase64} for an API that writes the file as a data URI, which also carries its\n * content type.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const FileFromDataUri = fileFrom(\"data-uri\");\n\n/**\n * {@link Base64FromFile} for an API that reads the file as a data URI, built from the file's\n * content type.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const DataUriFromFile = encodedFrom(\"data-uri\");\n\ntype DateTimeText = typeof DateTimeText.Type;\nconst DateTimeText = Schema.String.annotate({ format: \"date-time\" });\n\nconst rfc3339 = /^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})(?:\\.\\d+)?(?:Z|([+-]\\d{2}:\\d{2}))$/u;\n\n/** The instant of an RFC 3339 date-time with its offset; an impossible date such as February 30 has none. */\nfunction rfc3339Instant(text: string) {\n return pipe(\n Option.fromNullishOr(rfc3339.exec(text)),\n Option.flatMap(match =>\n Option.filter(DateTime.makeZoned(text, { timeZone: match[2] ?? \"+00:00\" }), zoned =>\n String.startsWith(match[1] ?? \"\")(DateTime.formatIsoOffset(zoned)),\n ),\n ),\n Option.map(DateTime.toUtc),\n );\n}\n\nfunction instants<Wire>(\n wire: Schema.Codec<Wire>,\n expected: string,\n read: (value: Wire) => Option.Option<DateTime.Utc>,\n write: (instant: DateTime.Utc) => Wire,\n) {\n const fromWire = SchemaGetter.transformEffect<string, Wire>((value, options) =>\n Option.match(read(value), {\n onNone: () => invalid(expected, value, options),\n onSome: instant => Effect.succeed(DateTime.formatIso(instant)),\n }),\n );\n const toWire = SchemaGetter.transformEffect<Wire, string>((text, options) =>\n Option.match(rfc3339Instant(text), {\n onNone: () => invalid(\"an ISO 8601 date-time\", text, options),\n onSome: instant => Effect.succeed(write(instant)),\n }),\n );\n return {\n input: pipe(DateTimeText, Schema.decodeTo(wire, { decode: toWire, encode: fromWire })),\n output: pipe(wire, Schema.decodeTo(DateTimeText, { decode: fromWire, encode: toWire })),\n };\n}\n\nconst unixSeconds = instants(\n Schema.Int,\n \"Unix seconds\",\n seconds => Option.map(DateTime.make(seconds * 1000), DateTime.toUtc),\n instant => Math.floor(DateTime.toEpochMillis(instant) / 1000),\n);\n\nconst rfc2822 = instants(\n Schema.String,\n \"an RFC 2822 date-time\",\n text => Option.map(DateTime.make(text), DateTime.toUtc),\n instant => DateTime.toDateUtc(instant).toUTCString(),\n);\n\n/**\n * A date-time the API writes as Unix seconds, decoded into an ISO 8601 UTC string.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const DateTimeFromUnixSeconds = unixSeconds.output;\n\n/**\n * An ISO 8601 date-time input the API reads as Unix seconds.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const UnixSecondsFromDateTime = unixSeconds.input;\n\n/**\n * A date-time the API writes in RFC 2822 form, decoded into an ISO 8601 UTC string.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const DateTimeFromRfc2822 = rfc2822.output;\n\n/**\n * An ISO 8601 date-time input the API reads in RFC 2822 form.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const Rfc2822FromDateTime = rfc2822.input;\n\n/**\n * An action output whose response decodes into a different shape, such as a file the API sends as\n * Base64: the action declares the decoded shape and the call decodes the response with `wire`.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface Decoded<Wire extends Schema.Top> {\n readonly _tag: \"Decoded\";\n readonly wire: Wire;\n}\n\n/**\n * Declares an output by the response schema it decodes from; see {@link Decoded}.\n *\n * @since 0.0.0\n * @category constructors\n */\nexport function decoded<const Wire extends Schema.Top>(wire: Wire): Decoded<Wire> {\n return { _tag: \"Decoded\", wire };\n}\n\ntype Request =\n | HttpClientRequest.HttpClientRequest\n | Effect.Effect<HttpClientRequest.HttpClientRequest, Action.ActionHandlerError>;\n\n/** `binary` returns a released version's base64 `ToolFile`; `file` stores the body as a file. */\ntype Body = \"json\" | \"text\" | \"binary\" | \"file\" | \"void\" | \"unknown\";\n\ntype GraphqlResponse = typeof GraphqlResponse.Type;\nconst GraphqlResponse = Schema.Struct({\n data: Schema.optionalKey(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))),\n errors: Schema.optionalKey(\n Schema.Array(\n Schema.StructWithRest(Schema.Struct({ message: Schema.String }), [\n Schema.Record(Schema.String, Schema.Unknown),\n ]),\n ),\n ),\n});\n\n/**\n * A response status, media type and decoding mode advertised by an HTTP action.\n *\n * @since 0.4.1\n * @category models\n */\nexport interface Variant {\n readonly status?: number;\n readonly contentType: string;\n readonly body: Body;\n readonly headers?: readonly string[];\n}\n\ntype Media =\n | { readonly contentBase64: Uint8Array; readonly contentType?: string | null }\n | Files.File;\n\ntype Upload =\n | { readonly mode: \"media\"; readonly media: Media }\n | { readonly mode: \"multipart\"; readonly media: Media; readonly metadata: unknown }\n | {\n readonly mode: \"start\";\n readonly contentType: string;\n readonly metadata?: unknown;\n readonly totalBytes: number;\n }\n | {\n readonly mode: \"chunk\";\n readonly sessionUrl: string;\n readonly totalBytes: number;\n readonly offset: number;\n readonly media: Media;\n }\n | { readonly mode: \"status\"; readonly sessionUrl: string; readonly totalBytes: number };\n\nfunction coerce(value: unknown) {\n return Predicate.isObject(value) ? JSON.stringify(value) : `${value}`;\n}\n\n/**\n * Encodes a path parameter as one segment.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function path(value: unknown) {\n return encodeURIComponent(coerce(value));\n}\n\n/**\n * Encodes a path parameter written inside single quotes, an OData string literal, doubling its\n * quotes: `O'Brien` in `People('{name}')` is sent as `People('O''Brien')`.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function literal(value: unknown) {\n return path(pipe(coerce(value), String.replaceAll(\"'\", \"''\")));\n}\n\n/**\n * Encodes a path parameter whose slashes stay path separators.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function segments(value: unknown) {\n return Array.join(Array.map(String.split(coerce(value), \"/\"), encodeURIComponent), \"/\");\n}\n\nfunction deepObject(name: string, value: unknown): [string, string][] {\n if (Array.isArray(value)) {\n return Array.flatMap(value, (item, index) => deepObject(`${name}[${index}]`, item));\n }\n if (Predicate.isObject(value)) {\n return Array.flatMap(Record.toEntries(value), entry =>\n deepObject(`${name}[${entry[0]}]`, entry[1]),\n );\n }\n return value === undefined ? [] : [[name, coerce(value)]];\n}\n\n/**\n * Query, header or form entries, repeating array values unless their name is joined, and encoding\n * `deep` names as bracketed keys such as `metadata[plan]` and `expand[0]`. A joined name is\n * comma-separated, or separated by the delimiter it is paired with, such as `[\"ids\", \"|\"]`.\n * `exploded` object parameters use their property names as query keys (`role=vet&active=true`).\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function params(\n fields: Record.ReadonlyRecord<string, unknown>,\n joined: readonly (string | readonly [string, string])[] = [],\n deep: readonly string[] = [],\n exploded: readonly string[] = [],\n) {\n return Array.flatMap(Record.toEntries(fields), field => {\n if (field[1] === undefined) return [];\n if (Array.contains(deep, field[0])) return deepObject(field[0], field[1]);\n const values = field[1];\n if (\n Array.contains(exploded, field[0]) &&\n Predicate.isObject(values) &&\n !Array.isArray(values)\n ) {\n return Array.filterMap(Record.toEntries(values), entry =>\n entry[1] === undefined\n ? Result.failVoid\n : Result.succeed([entry[0], coerce(entry[1])] as const),\n );\n }\n if (!Array.isArray(values)) return [[field[0], coerce(values)] as const];\n const separator = Array.findFirst(joined, entry => {\n const pair = Predicate.isString(entry) ? ([entry, \",\"] as const) : entry;\n return pair[0] === field[0] ? Option.some(pair[1]) : Option.none();\n });\n return Option.match(separator, {\n onNone: () => Array.map(values, item => [field[0], coerce(item)] as const),\n onSome: value => [[field[0], Array.join(Array.map(values, coerce), value)] as const],\n });\n });\n}\n\nfunction filePart(bytes: Uint8Array, name: string, contentType: string) {\n return new globalThis.File([new Uint8Array(bytes)], name, { type: contentType });\n}\n\n/**\n * Multipart form fields, sending each {@link File} as a file part.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function form(payload: Record.ReadonlyRecord<string, unknown>) {\n return Record.map(payload, (value, name) =>\n Array.map(Array.ensure(value), item => {\n if (item === undefined) return undefined;\n if (!Schema.is(File)(item)) return coerce(item);\n return filePart(\n item.contentBase64,\n item.filename ?? name,\n item.contentType ?? \"application/octet-stream\",\n );\n }),\n );\n}\n\nfunction fileFailed(error: Files.FileError) {\n return Action.ActionHandlerError.make({ cause: error, message: error.message });\n}\n\nfunction readFile(file: Files.File) {\n return pipe(Files.read(file), Effect.mapError(fileFailed));\n}\n\n/**\n * Sends a file as the raw request body.\n *\n * @since 0.1.0\n * @category encoding\n */\nexport const withFile = Effect.fnUntraced(function* (\n request: HttpClientRequest.HttpClientRequest,\n file: Files.File,\n) {\n return HttpClientRequest.bodyUint8Array(request, yield* readFile(file), file.contentType);\n});\n\n/**\n * Sends multipart form fields, each {@link Files.File} as a file part.\n *\n * @since 0.1.0\n * @category encoding\n */\nexport const withForm = Effect.fnUntraced(function* (\n request: HttpClientRequest.HttpClientRequest,\n payload: Record.ReadonlyRecord<string, unknown>,\n) {\n return HttpClientRequest.bodyFormDataRecord(\n request,\n Record.fromEntries(\n yield* Effect.forEach(Record.toEntries(payload), field =>\n Effect.map(\n Effect.forEach(\n Array.filter(Array.ensure(field[1]), item => item !== undefined),\n item =>\n Effect.gen(function* () {\n if (!Schema.is(Files.File)(item)) return coerce(item);\n return filePart(yield* readFile(item), item.name, item.contentType);\n }),\n ),\n parts => [field[0], parts] satisfies [string, (string | globalThis.File)[]],\n ),\n ),\n ),\n );\n});\n\nfunction mediaBytes(media: Media) {\n if (Schema.is(Files.File)(media)) {\n return Effect.map(readFile(media), bytes => ({ bytes, contentType: media.contentType }));\n }\n return Effect.succeed({\n bytes: media.contentBase64,\n contentType: Option.getOrNull(Option.fromNullishOr(media.contentType)),\n });\n}\n\nfunction isSafeUrl(value: string, origin?: string) {\n if (!URL.canParse(value)) return false;\n const url = new URL(value);\n return (\n url.protocol === \"https:\" &&\n url.username === \"\" &&\n url.password === \"\" &&\n (origin === undefined || url.origin === origin)\n );\n}\n\nfunction refused(message: string) {\n return Effect.fail(Action.ActionHandlerError.make({ message }));\n}\n\n/**\n * Follows a returned next-page link on the operation's own origin: only its path and query are\n * taken, so the connection's host routing applies and credentials never reach another host.\n *\n * @since 0.0.0\n * @category requests\n */\nexport function continuation(request: HttpClientRequest.HttpClientRequest, nextLink?: string) {\n if (nextLink === undefined) return Effect.succeed(request);\n const declared = new URL(request.url);\n const next = URL.canParse(nextLink) ? new URL(nextLink) : undefined;\n if (next === undefined || !isSafeUrl(nextLink) || next.pathname !== declared.pathname) {\n return refused(\"A continuation URL must be an HTTPS link to the same operation path\");\n }\n return Effect.succeed(\n HttpClientRequest.makeWith(\n request.method,\n `${declared.origin}${next.pathname}${next.search}`,\n UrlParams.empty,\n Option.none(),\n request.headers,\n HttpBody.empty,\n ),\n );\n}\n\n/**\n * A request to a preauthenticated upload URL, which is sent without the connection's credentials.\n *\n * @since 0.0.0\n * @category requests\n */\nexport function preauthenticated(\n method: (url: string) => HttpClientRequest.HttpClientRequest,\n url: string,\n ...steps: readonly ((\n request: HttpClientRequest.HttpClientRequest,\n ) => HttpClientRequest.HttpClientRequest)[]\n) {\n if (!isSafeUrl(url)) return refused(\"An upload session requires a preauthenticated HTTPS URL\");\n return Effect.succeed(Array.reduce(steps, method(url), (request, step) => step(request)));\n}\n\nfunction failure(\n error:\n | Action.ActionHandlerError\n | Action.HttpClientFailure\n | { readonly cause: unknown; readonly response: HttpClientResponse.HttpClientResponse },\n) {\n return Schema.is(Action.ActionHandlerError)(error) ? error : Action.fromHttpClientFailure(error);\n}\n\n// Like HttpClient.followRedirects, except that a redirect to another origin sends no\n// request header at all: auth methods may set any header, such as GitLab's PRIVATE-TOKEN.\nfunction redirect(response: HttpClientResponse.HttpClientResponse) {\n const location = response.headers[\"location\"];\n if (response.status < 300 || response.status >= 400 || location === undefined) return undefined;\n const sent = response.request;\n const url = new URL(location, sent.url);\n const request =\n (response.status === 303 && sent.method !== \"GET\" && sent.method !== \"HEAD\") ||\n ((response.status === 301 || response.status === 302) && sent.method === \"POST\")\n ? HttpClientRequest.setBody(HttpClientRequest.setMethod(sent, \"GET\"), HttpBody.empty)\n : sent;\n return url.origin === new URL(sent.url).origin\n ? HttpClientRequest.setUrl(request, url)\n : HttpClientRequest.setUrl(\n HttpClientRequest.makeWith(\n request.method,\n \"\",\n UrlParams.empty,\n Option.none(),\n Headers.empty,\n request.body,\n ),\n url,\n );\n}\n\nfunction follow(\n client: HttpClient.HttpClient,\n response: HttpClientResponse.HttpClientResponse,\n redirects: number,\n): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> {\n const next = redirect(response);\n return next === undefined || redirects === 10\n ? Effect.succeed(response)\n : Effect.flatMap(client.execute(next), result => follow(client, result, redirects + 1));\n}\n\n/** The file name a `Content-Disposition` header suggests, preferring its encoded form. */\nfunction dispositionName(header?: string) {\n if (header === undefined) return undefined;\n const encoded = pipe(\n String.match(/(?:^|;)\\s*filename\\*\\s*=\\s*UTF-8'[^']*'([^;]+)/iu)(header),\n Option.flatMap(match => Option.fromUndefinedOr(match[1])),\n );\n const decoded = pipe(\n encoded,\n Option.flatMap(value => Option.liftThrowable(() => decodeURIComponent(String.trim(value)))()),\n );\n return Option.getOrElse(decoded, () =>\n pipe(\n String.match(/(?:^|;)\\s*filename\\s*=\\s*(?:\"((?:\\\\.|[^\"\\\\])*)\"|([^;]*))/iu)(header),\n Option.flatMap(match =>\n Option.orElse(\n Option.map(Option.fromUndefinedOr(match[1]), name =>\n String.replace(/\\\\(.)/gu, \"$1\")(name),\n ),\n () => Option.map(Option.fromUndefinedOr(match[2]), String.trim),\n ),\n ),\n Option.getOrUndefined,\n ),\n );\n}\n\nconst read = Effect.fnUntraced(function* (\n response: HttpClientResponse.HttpClientResponse,\n body: Body,\n) {\n if (body === \"json\") return yield* response.json;\n if (body === \"text\") return yield* response.text;\n if (body === \"void\") return {};\n if (body === \"unknown\") {\n const text = yield* response.text;\n if (String.isEmpty(String.trim(text))) return null;\n return Option.getOrElse(\n Schema.decodeOption(Schema.fromJsonString(Schema.Json))(text),\n () => text,\n );\n }\n const bytes = new Uint8Array(yield* response.arrayBuffer);\n const name = dispositionName(response.headers[\"content-disposition\"]);\n if (body === \"file\") {\n return yield* pipe(\n Files.write({\n bytes,\n contentType: Option.getOrNull(Option.fromUndefinedOr(response.headers[\"content-type\"])),\n name: name ?? \"file\",\n }),\n Effect.mapError(fileFailed),\n );\n }\n return toolFile(bytes, response.headers[\"content-type\"] ?? null, name ?? null);\n});\n\n/**\n * One API operation as {@link make} returns it: its contract and the call that performs it. The\n * `Context` parameter lets a package name its handler context once, so declaration files print\n * `Endpoint<Context, …>` instead of repeating its auth methods in every action.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface Endpoint<Context, Input extends Schema.Top, Output extends Schema.Top> {\n readonly input: Input;\n readonly output: Output;\n readonly run: (\n input: Input[\"Type\"],\n context: Context,\n ) => Effect.Effect<Output[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>;\n}\n\n/**\n * An {@link Endpoint} whose output is the decoded type of the response schema it keeps as `wire`.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface DecodedEndpoint<Context, Input extends Schema.Top, Wire extends Schema.Top> {\n readonly input: Input;\n readonly output: Schema.toType<Wire>;\n readonly wire: Wire;\n readonly run: (\n input: Input[\"Type\"],\n context: Context,\n ) => Effect.Effect<Wire[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>;\n}\n\n/**\n * Binds the runtime to a package's auth module: the calls a generated version file makes. Its\n * `authorize` applies a connection's credentials to the client. Its optional `checkResponse` fails\n * a successful response that reports a failed call, such as Slack's `{ ok: false, error }`.\n * `preauthenticatedUploadUrl` restricts credential-free upload requests and every redirect to\n * provider-approved HTTPS URLs, without changing authenticated calls or other providers.\n *\n * @since 0.0.0\n * @category constructors\n */\nexport function make<\n const Methods extends readonly AuthMethod.Any[],\n Context extends Action.HandlerContext<Methods> = Action.HandlerContext<Methods>,\n>(auth: {\n readonly authorize: (\n client: HttpClient.HttpClient,\n context: Action.HandlerContext<Methods>,\n ) => HttpClient.HttpClient;\n readonly checkResponse?: (\n response: HttpClientResponse.HttpClientResponse,\n ) => Effect.Effect<void, Action.ActionHandlerError | HttpClientError.HttpClientError>;\n readonly preauthenticatedUploadUrl?: Schema.Schema<string>;\n}) {\n const { authorize, checkResponse = () => Effect.void } = auth;\n const send = Effect.fnUntraced(function* (context: Context | undefined, request: Request) {\n const base = yield* HttpClient.HttpClient;\n const uploadPolicy = context === undefined ? auth.preauthenticatedUploadUrl : undefined;\n const client =\n uploadPolicy === undefined\n ? base\n : HttpClient.mapRequestEffect(base, outgoing =>\n isSafeUrl(outgoing.url) && Schema.is(uploadPolicy)(outgoing.url)\n ? Effect.succeed(outgoing)\n : Effect.fail(\n new HttpClientError.HttpClientError({\n reason: new HttpClientError.InvalidUrlError({\n description: \"The upload URL is not an approved provider HTTPS destination\",\n request: outgoing,\n }),\n }),\n ),\n );\n const transport = HttpClient.transformResponse(\n client,\n Effect.flatMap(response => follow(client, response, 0)),\n );\n const authorized = context === undefined ? transport : authorize(transport, context);\n const execution = authorized.execute(Effect.isEffect(request) ? yield* request : request);\n const options = yield* Effect.serviceOption(FetchHttpClient.RequestInit);\n const response = yield* Boolean.match(uploadPolicy !== undefined, {\n onFalse: () => execution,\n onTrue: () =>\n Effect.provideService(execution, FetchHttpClient.RequestInit, {\n ...Option.getOrElse(options, () => ({})),\n redirect: \"manual\",\n }),\n });\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n yield* checkResponse(response);\n return response;\n });\n\n /**\n * One API operation: its action contract and the call that performs it. A {@link Decoded} output\n * declares the decoded shape and hands the call its response schema.\n */\n function endpoint<const Input extends Schema.Top, const Output extends Schema.Top>(\n contract: { readonly input: Input; readonly output: Output },\n run: (\n input: Input[\"Type\"],\n context: Context,\n output: Output,\n ) => Effect.Effect<Output[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>,\n ): Endpoint<Context, Input, Output>;\n function endpoint<const Input extends Schema.Top, const Wire extends Schema.Top>(\n contract: { readonly input: Input; readonly output: Decoded<Wire> },\n run: (\n input: Input[\"Type\"],\n context: Context,\n output: Wire,\n ) => Effect.Effect<Wire[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>,\n ): DecodedEndpoint<Context, Input, Wire>;\n function endpoint<const Input extends Schema.Top, const Output extends Schema.Top>(\n contract: { readonly input: Input; readonly output: Output | Decoded<Output> },\n run: (\n input: Input[\"Type\"],\n context: Context,\n output: Output,\n ) => Effect.Effect<Output[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>,\n ) {\n if (!Schema.isSchema(contract.output)) {\n const wire = contract.output.wire;\n return {\n input: contract.input,\n output: Schema.toType(wire),\n run: (input: Input[\"Type\"], context: Context) => run(input, context, wire),\n wire,\n };\n }\n const output = contract.output;\n return {\n input: contract.input,\n output,\n run: (input: Input[\"Type\"], context: Context) => run(input, context, output),\n };\n }\n\n /** Sends a request and decodes its body as the operation's single response. */\n function execute<Output extends Schema.Top>(\n context: Context | undefined,\n output: Output,\n request: Request,\n body: Body,\n ) {\n return pipe(\n send(context, request),\n Effect.flatMap(response => read(response, body)),\n Effect.flatMap(decodeResponse(output)),\n Effect.mapError(failure),\n );\n }\n\n /** Sends a request and decodes the declared response variant its status and media type select. */\n const variants = Effect.fnUntraced(function* <Output extends Schema.Top>(\n context: Context | undefined,\n output: Output,\n request: Request,\n declared: readonly Variant[],\n media?: boolean,\n ) {\n const response = yield* send(context, request);\n const exact = Array.flatMap(declared, variant =>\n variant.status === undefined ? [] : [variant.status],\n );\n const contentType = pipe(\n response.headers[\"content-type\"] ?? \"\",\n String.split(\";\"),\n Array.headNonEmpty,\n String.trim,\n String.toLowerCase,\n );\n const ordered = Array.sort(\n declared,\n Order.mapInput(Order.Number, (variant: Variant) => {\n if (variant.body === \"void\" || variant.body === \"unknown\") return 3;\n if (variant.contentType === \"*/*\") return 2;\n return pipe(variant.contentType, String.endsWith(\"/*\")) ? 1 : 0;\n }),\n );\n const variant = Array.findFirst(ordered, candidate => {\n const status =\n candidate.status === undefined\n ? !Array.contains(exact, response.status)\n : candidate.status === response.status;\n if (!status) return false;\n if (media !== undefined) {\n return (candidate.body === \"binary\" || candidate.body === \"file\") === media;\n }\n if (\n candidate.body === \"void\" ||\n candidate.body === \"unknown\" ||\n candidate.contentType === \"*/*\"\n ) {\n return true;\n }\n if (pipe(candidate.contentType, String.endsWith(\"/*\"))) {\n return pipe(\n contentType,\n String.startsWith(pipe(candidate.contentType, String.slice(0, -1))),\n );\n }\n return contentType === candidate.contentType;\n });\n if (Option.isNone(variant)) {\n return yield* Effect.fail({\n cause: \"The API returned an undeclared successful response\",\n response,\n });\n }\n const headers = Array.flatMap(variant.value.headers ?? [], name => {\n const value = response.headers[String.toLowerCase(name)];\n return value === undefined ? [] : [[name, value] as const];\n });\n return yield* decodeResponse(output)({\n body: yield* read(response, variant.value.body),\n contentType: variant.value.contentType,\n status: response.status,\n ...(variant.value.headers === undefined ? {} : { headers: Record.fromEntries(headers) }),\n });\n }, Effect.mapError(failure));\n\n /** Google's media, multipart and resumable upload protocols. */\n const googleUpload = Effect.fnUntraced(function* <Output extends Schema.Top>(\n context: Context,\n output: Output,\n request: HttpClientRequest.HttpClientRequest,\n payload: Upload,\n options: { readonly maxSize?: number; readonly resumable?: string },\n ) {\n const client = authorize(yield* HttpClient.HttpClient, context);\n const media = \"media\" in payload ? yield* mediaBytes(payload.media) : undefined;\n const size = \"totalBytes\" in payload ? payload.totalBytes : (media?.bytes.byteLength ?? 0);\n if (size < 0 || (options.maxSize !== undefined && size > options.maxSize)) {\n return yield* refused(\"The upload size is outside the API's declared limit\");\n }\n const origin = new URL(request.url).origin;\n if (payload.mode === \"start\") {\n if (options.resumable === undefined) {\n return yield* refused(\"This API has no resumable upload protocol\");\n }\n const response = yield* client.execute(\n pipe(\n HttpClientRequest.setUrl(request, options.resumable),\n HttpClientRequest.setUrlParam(\"uploadType\", \"resumable\"),\n HttpClientRequest.setHeaders({\n \"x-upload-content-length\": `${size}`,\n \"x-upload-content-type\": payload.contentType,\n }),\n HttpClientRequest.bodyJsonUnsafe(payload.metadata ?? {}),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n const sessionUrl = response.headers[\"location\"];\n if (sessionUrl === undefined || !isSafeUrl(sessionUrl, origin)) {\n return yield* Effect.fail({\n cause: \"The API returned an invalid upload session URL\",\n response,\n });\n }\n return yield* decodeResponse(output)({ nextOffset: 0, sessionUrl, state: \"pending\" });\n }\n if (payload.mode === \"chunk\" || payload.mode === \"status\") {\n if (!isSafeUrl(payload.sessionUrl, origin)) {\n return yield* refused(\"The upload session URL must use the API's HTTPS origin\");\n }\n const bytes = media?.bytes ?? new Uint8Array();\n const end = payload.mode === \"chunk\" ? payload.offset + bytes.byteLength : 0;\n if (\n payload.mode === \"chunk\" &&\n (payload.offset < 0 ||\n bytes.byteLength === 0 ||\n end > size ||\n (end < size && bytes.byteLength % 262_144 !== 0))\n ) {\n return yield* refused(\n \"Upload chunks must fit the total size and use 256 KiB multiples except for the final chunk\",\n );\n }\n const response = yield* client.execute(\n pipe(\n HttpClientRequest.put(payload.sessionUrl),\n HttpClientRequest.bodyUint8Array(bytes, media?.contentType ?? \"application/octet-stream\"),\n HttpClientRequest.setHeader(\n \"content-range\",\n payload.mode === \"status\"\n ? `bytes */${size}`\n : `bytes ${payload.offset}-${end - 1}/${size}`,\n ),\n ),\n );\n if (response.status === 308) {\n const range = response.headers[\"range\"];\n if (range !== undefined && !/^bytes=0-\\d+$/u.test(range)) {\n return yield* Effect.fail({\n cause: \"The API returned an invalid upload range\",\n response,\n });\n }\n const nextOffset = range === undefined ? 0 : Number(pipe(range, String.slice(8))) + 1;\n if (nextOffset > size) {\n return yield* Effect.fail({\n cause: \"The API returned an upload offset beyond the total size\",\n response,\n });\n }\n return yield* decodeResponse(output)({\n nextOffset,\n sessionUrl: payload.sessionUrl,\n state: \"pending\",\n });\n }\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n return yield* decodeResponse(output)({ resource: yield* response.json, state: \"complete\" });\n }\n const selected = HttpClientRequest.setUrlParam(request, \"uploadType\", payload.mode);\n const bytes = media?.bytes ?? new Uint8Array();\n const contentType = media?.contentType ?? \"application/octet-stream\";\n const boundary = `dual-${yield* Random.nextInt}-${yield* Random.nextInt}`;\n const metadata =\n payload.mode === \"multipart\"\n ? yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown))(payload.metadata)\n : \"\";\n const body =\n payload.mode === \"media\"\n ? HttpClientRequest.bodyUint8Array(selected, bytes, contentType)\n : HttpClientRequest.bodyUint8Array(\n selected,\n new Uint8Array(\n yield* Effect.promise(() =>\n new Blob([\n `--${boundary}\\r\\nContent-Type: application/json; charset=UTF-8\\r\\n\\r\\n${metadata}\\r\\n--${boundary}\\r\\nContent-Type: ${contentType}\\r\\n\\r\\n`,\n new Uint8Array(bytes),\n `\\r\\n--${boundary}--\\r\\n`,\n ]).arrayBuffer(),\n ),\n ),\n `multipart/related; boundary=${boundary}`,\n );\n const response = yield* client.execute(body);\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n return yield* decodeResponse(output)({ resource: yield* response.json, state: \"complete\" });\n }, Effect.mapError(failure));\n\n /** Sends a GraphQL operation and decodes its root field, failing with the errors it returns. */\n const graphql = Effect.fnUntraced(function* <Output extends Schema.Top>(\n context: Context,\n output: Output,\n request: Request,\n field: string,\n ) {\n const response = yield* send(context, request);\n const body = yield* Schema.decodeUnknownEffect(GraphqlResponse)(yield* response.json);\n if (body.errors !== undefined && Array.isReadonlyArrayNonEmpty(body.errors)) {\n return yield* Action.ActionHandlerError.make({\n details: body.errors,\n message: Array.join(\n Array.map(body.errors, error => error.message),\n \"; \",\n ),\n });\n }\n return yield* decodeResponse(output)(body.data?.[field]);\n }, Effect.mapError(failure));\n\n /**\n * Calls a Model Context Protocol tool in a session with the server. A tool that reports an error\n * fails the action with its text; otherwise the output is its structured content, or its content\n * blocks when it declares no output schema.\n */\n const mcp = Effect.fnUntraced(\n function* <Output extends Schema.Top>(\n context: Context,\n output: Output,\n server: string,\n tool: string,\n args: unknown,\n structured: boolean,\n ) {\n const connection = yield* Mcp.connect(\n authorize(yield* HttpClient.HttpClient, context),\n server,\n {},\n );\n const result = yield* Schema.decodeUnknownEffect(Mcp.CallToolResult)(\n yield* connection.request(\"tools/call\", { arguments: args, name: tool }),\n );\n if (result.isError === true) {\n return yield* Action.ActionHandlerError.make({\n details: result.content,\n message: Array.join(\n Array.flatMap(result.content, block => Array.fromNullishOr(block.text)),\n \"\\n\",\n ),\n });\n }\n return yield* decodeResponse(output)(\n Boolean.match(structured, {\n onFalse: () => ({ content: result.content }),\n onTrue: () => result.structuredContent,\n }),\n );\n },\n Effect.scoped,\n Effect.mapError(error =>\n Schema.is(Mcp.McpError)(error)\n ? Action.ActionHandlerError.make({ message: error.message })\n : failure(error),\n ),\n );\n\n return { endpoint, execute, googleUpload, graphql, mcp, variants };\n}\n\nexport * as Http from \"./Http.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,uBAAiC,OAAU,OAAiB;CACnE,IAAI,MAAM,OAAO,OAAO,KAAK,GAAG,OAAO;CACvC,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,QAAQ,KAAK,GAC7C,KAAK,MAAM,SAAS,MAAM,IAAI,OAAO,KAAK,GAAG,uBAAuB,MAAM,IAAI,MAAM,EAAE;MACjF,IAAI,UAAU,SAAS,KAAK,KAAK,UAAU,SAAS,KAAK,GAC9D,KAAK,MAAM,SAAS,OAAO,UAAU,KAAK,GACxC,IAAI,OAAO,IAAI,OAAO,MAAM,EAAE,GAC5B,uBAAuB,MAAM,MAAM,KAAK,MAAM,EAAE;MAEhD,OAAO,eAAe,OAAO,MAAM,IAAI;EACrC,cAAc;EACd,YAAY;EACZ,OAAO,MAAM;EACb,UAAU;CACZ,CAAC;CAIP,OAAO;AACT;AAEA,SAAS,eAA0C,QAAgB;CACjE,OAAO,KACL,OAAO,SACP,OAAO,SAAQ,UACb,KACE,OAAO,oBAAoB,MAAM,CAAC,CAAC,KAAK,GACxC,OAAO,KAAI,UAA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AQ,MAAM,YAAY;IACxB,gBAAgB,EAAE,SAAS,OAAO,QAAQ;IAC1C,cAAc,OAAO;GACvB,CAAC,CACH;EACF,GACA,OAAO,QACP,OAAO,UAAS,UACd,OAAO,GAAGC,QAAY,CAAC,CAAC,KAAK,IAAA,mBACC,KAAK,EAAE,SAAS,MAAM,QAAQ,CAAC,IACzD,QAAQ,KAAK,CACnB,CAGmD;EAAG;CAAS;AACnE"}
1
+ {"version":3,"file":"Http.js","names":["Files.File","Files.write","Files.read","Action.ActionHandlerError","Action.fromHttpClientFailure","Mcp.connect","Mcp.CallToolResult","Mcp.McpError"],"sources":["../src/Http.ts"],"sourcesContent":["/**\n * The HTTP runtime of generated API plugins: each operation's contract and call, request encoding,\n * response decoding, continuation links, redirects and uploads.\n *\n * @since 0.0.0\n */\nimport {\n Array,\n Boolean,\n DateTime,\n Effect,\n Equal,\n Option,\n Order,\n Predicate,\n Random,\n Record,\n Result,\n Schema,\n SchemaGetter,\n SchemaIssue,\n String,\n flow,\n pipe,\n} from \"effect\";\nimport type { SchemaAST } from \"effect\";\n\nimport { Base64, Base64Url } from \"effect/encoding\";\nimport {\n FetchHttpClient,\n HttpBody,\n HttpClient,\n HttpClientError,\n HttpClientRequest,\n Headers,\n UrlParams,\n} from \"effect/http\";\nimport type { HttpClientResponse } from \"effect/http\";\n\nimport * as Action from \"./Action.ts\";\nimport type * as AuthMethod from \"./AuthMethod.ts\";\nimport { Files } from \"./Files.ts\";\nimport { Mcp } from \"./Mcp.ts\";\nimport * as ToolFile from \"./ToolFile.ts\";\n\nfunction preserveJsonProperties<A, Input>(value: A, input: Input): A {\n if (Equal.equals(value, input)) return value;\n if (Array.isArray(value) && Array.isArray(input)) {\n for (const entry of Array.zip(value, input)) preserveJsonProperties(entry[0], entry[1]);\n } else if (Predicate.isObject(value) && Predicate.isObject(input)) {\n for (const entry of Record.toEntries(input)) {\n if (Record.has(value, entry[0])) {\n preserveJsonProperties(value[entry[0]], entry[1]);\n } else {\n Object.defineProperty(value, entry[0], {\n configurable: true,\n enumerable: true,\n value: entry[1],\n writable: true,\n });\n }\n }\n }\n return value;\n}\n\nfunction decodeResponse<Output extends Schema.Top>(output: Output) {\n return flow(\n Effect.succeed,\n Effect.flatMap(input =>\n pipe(\n Schema.decodeUnknownEffect(output)(input),\n Effect.map(value => preserveJsonProperties(value, input)),\n ),\n ),\n );\n}\n\n/**\n * An action's input and output schemas.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface Contract {\n readonly input: Schema.Top;\n readonly output: Schema.Top;\n}\n\n/**\n * Runs an action: its input in, its output or a failure out.\n *\n * @since 0.0.0\n * @category models\n */\nexport type Handler<Methods extends readonly AuthMethod.Any[], Input, Output> = (\n input: Input,\n context: Action.HandlerContext<Methods>,\n) => Effect.Effect<Output, Action.ActionHandlerFailure, HttpClient.HttpClient>;\n\n/**\n * A file input: a ToolFile as a download returns it, or just its bytes with a type and name.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport type File = typeof File.Type;\nexport const File = Schema.Struct({\n _tag: Schema.optionalKey(Schema.Literal(\"ToolFile\")),\n contentBase64: Schema.Uint8ArrayFromBase64,\n contentType: Schema.optionalKey(Schema.NullOr(Schema.String)),\n filename: Schema.optionalKey(Schema.NullOr(Schema.String)),\n sizeBytes: Schema.optionalKey(Schema.Natural),\n}).annotate({\n description:\n \"A ToolFile, such as the result of a download, passed unchanged; or its contentBase64 with an optional contentType and filename.\",\n});\n\nconst signatures: [string, [number, number[]][]][] = [\n [\"image/jpeg\", [[0, [0xff, 0xd8, 0xff]]]],\n [\"image/png\", [[0, [0x89, 0x50, 0x4e, 0x47]]]],\n [\"image/gif\", [[0, [0x47, 0x49, 0x46, 0x38]]]],\n [\n \"image/webp\",\n [\n [0, [0x52, 0x49, 0x46, 0x46]],\n [8, [0x57, 0x45, 0x42, 0x50]],\n ],\n ],\n [\"application/pdf\", [[0, [0x25, 0x50, 0x44, 0x46]]]],\n [\"application/zip\", [[0, [0x50, 0x4b, 0x03, 0x04]]]],\n];\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\n\nfunction sniff(bytes: Uint8Array) {\n return pipe(\n Array.findFirst(signatures, signature =>\n Array.every(signature[1], part =>\n Array.every(part[1], (byte, index) => bytes[part[0] + index] === byte),\n ),\n ),\n Option.map(signature => signature[0]),\n Option.orElse(() =>\n Option.liftPredicate(\"text/plain\", () =>\n Result.isSuccess(Result.try(() => utf8.decode(bytes))),\n ),\n ),\n Option.getOrNull,\n );\n}\n\nfunction fileContentType(bytes: Uint8Array, declared: string | null) {\n return declared === null || pipe(declared, String.startsWith(\"application/octet-stream\"))\n ? (sniff(bytes) ?? declared)\n : declared;\n}\n\nfunction toolFile(bytes: Uint8Array, declared: string | null, filename: string | null) {\n return {\n _tag: \"ToolFile\",\n contentBase64: Base64.encode(bytes),\n contentType: fileContentType(bytes, declared),\n filename,\n sizeBytes: bytes.byteLength,\n } satisfies ToolFile.File;\n}\n\nfunction invalid(expected: string, value: unknown, options: SchemaAST.ParseOptions) {\n return Effect.fail(new SchemaIssue.InvalidValue({ expected }, value, options));\n}\n\nfunction decodeBytes(text: string, options: SchemaAST.ParseOptions) {\n return Result.match(\n Base64Url.decode(pipe(text, String.replaceAll(\"+\", \"-\"), String.replaceAll(\"/\", \"_\"))),\n {\n onFailure: () => invalid(\"a Base64 or Base64Url string\", text, options),\n onSuccess: bytes => Effect.succeed(bytes),\n },\n );\n}\n\ntype Carrier = \"base64\" | \"base64url\" | \"data-uri\";\n\ninterface Content {\n bytes: Uint8Array;\n contentType: string | null;\n}\n\nfunction contentOf(carrier: Carrier) {\n return SchemaGetter.transformEffect<Content, string>((text, options) => {\n if (carrier !== \"data-uri\") {\n return Effect.map(decodeBytes(text, options), bytes => ({ bytes, contentType: null }));\n }\n return Option.match(pipe(text, String.match(/^data:([^;,]*)(?:;[^;,]*)*;base64,(.*)$/su)), {\n onNone: () => invalid(\"a Base64 data URI\", text, options),\n onSome: parts =>\n Effect.map(decodeBytes(Array.getUnsafe(parts, 2), options), bytes => ({\n bytes,\n contentType: pipe(\n Array.getUnsafe(parts, 1),\n Option.liftPredicate(String.isNonEmpty),\n Option.getOrNull,\n ),\n })),\n });\n });\n}\n\nfunction textOf(carrier: Carrier, content: Content) {\n if (carrier === \"base64\") return Base64.encode(content.bytes);\n if (carrier === \"base64url\") return Base64Url.encode(content.bytes);\n const contentType = content.contentType ?? sniff(content.bytes) ?? \"application/octet-stream\";\n return `data:${contentType};base64,${Base64.encode(content.bytes)}`;\n}\n\nfunction fileFrom(carrier: Carrier) {\n return Schema.String.pipe(\n Schema.decodeTo(Files.File, {\n decode: SchemaGetter.compose(\n contentOf(carrier),\n SchemaGetter.transformEffect((content, options) =>\n pipe(\n Files.write({\n bytes: content.bytes,\n contentType: fileContentType(content.bytes, content.contentType),\n name: \"file\",\n }),\n Effect.mapError(\n error => new SchemaIssue.InvalidValue({ expected: error.message }, content, options),\n ),\n ),\n ),\n ),\n encode: SchemaGetter.transformEffect((file: Files.File, options) =>\n pipe(\n Files.read(file),\n Effect.mapBoth({\n onSuccess: bytes => textOf(carrier, { bytes, contentType: file.contentType }),\n onFailure: error =>\n new SchemaIssue.InvalidValue({ expected: error.message }, file, options),\n }),\n ),\n ),\n }),\n );\n}\n\nfunction encodedFrom(carrier: Carrier) {\n return Schema.flip(fileFrom(carrier));\n}\n\n/**\n * A file the API returns as a Base64 string inside JSON, stored by the host and returned by reference.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const FileFromBase64 = fileFrom(\"base64\");\n\n/**\n * {@link FileFromBase64} for an API that writes the file in Base64Url.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const FileFromBase64Url = fileFrom(\"base64url\");\n\n/**\n * A {@link Files.File} input the API reads as a Base64 string inside JSON.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const Base64FromFile = encodedFrom(\"base64\");\n\n/**\n * {@link Base64FromFile} for an API that reads the file in Base64Url.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const Base64UrlFromFile = encodedFrom(\"base64url\");\n\n/**\n * {@link FileFromBase64} for an API that writes the file as a data URI, which also carries its\n * content type.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const FileFromDataUri = fileFrom(\"data-uri\");\n\n/**\n * {@link Base64FromFile} for an API that reads the file as a data URI, built from the file's\n * content type.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const DataUriFromFile = encodedFrom(\"data-uri\");\n\ntype DateTimeText = typeof DateTimeText.Type;\nconst DateTimeText = Schema.String.annotate({ format: \"date-time\" });\n\nconst rfc3339 = /^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})(?:\\.\\d+)?(?:Z|([+-]\\d{2}:\\d{2}))$/u;\n\n/** The instant of an RFC 3339 date-time with its offset; an impossible date such as February 30 has none. */\nfunction rfc3339Instant(text: string) {\n return pipe(\n Option.fromNullishOr(rfc3339.exec(text)),\n Option.flatMap(match =>\n Option.filter(DateTime.makeZoned(text, { timeZone: match[2] ?? \"+00:00\" }), zoned =>\n String.startsWith(match[1] ?? \"\")(DateTime.formatIsoOffset(zoned)),\n ),\n ),\n Option.map(DateTime.toUtc),\n );\n}\n\nfunction instants<Wire>(\n wire: Schema.Codec<Wire>,\n expected: string,\n read: (value: Wire) => Option.Option<DateTime.Utc>,\n write: (instant: DateTime.Utc) => Wire,\n) {\n const fromWire = SchemaGetter.transformEffect<string, Wire>((value, options) =>\n Option.match(read(value), {\n onNone: () => invalid(expected, value, options),\n onSome: instant => Effect.succeed(DateTime.formatIso(instant)),\n }),\n );\n const toWire = SchemaGetter.transformEffect<Wire, string>((text, options) =>\n Option.match(rfc3339Instant(text), {\n onNone: () => invalid(\"an ISO 8601 date-time\", text, options),\n onSome: instant => Effect.succeed(write(instant)),\n }),\n );\n return {\n input: pipe(DateTimeText, Schema.decodeTo(wire, { decode: toWire, encode: fromWire })),\n output: pipe(wire, Schema.decodeTo(DateTimeText, { decode: fromWire, encode: toWire })),\n };\n}\n\nconst unixSeconds = instants(\n Schema.Int,\n \"Unix seconds\",\n seconds => Option.map(DateTime.make(seconds * 1000), DateTime.toUtc),\n instant => Math.floor(DateTime.toEpochMillis(instant) / 1000),\n);\n\nconst rfc2822 = instants(\n Schema.String,\n \"an RFC 2822 date-time\",\n text => Option.map(DateTime.make(text), DateTime.toUtc),\n instant => DateTime.toDateUtc(instant).toUTCString(),\n);\n\n/**\n * A date-time the API writes as Unix seconds, decoded into an ISO 8601 UTC string.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const DateTimeFromUnixSeconds = unixSeconds.output;\n\n/**\n * An ISO 8601 date-time input the API reads as Unix seconds.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const UnixSecondsFromDateTime = unixSeconds.input;\n\n/**\n * A date-time the API writes in RFC 2822 form, decoded into an ISO 8601 UTC string.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const DateTimeFromRfc2822 = rfc2822.output;\n\n/**\n * An ISO 8601 date-time input the API reads in RFC 2822 form.\n *\n * @since 0.0.0\n * @category schemas\n */\nexport const Rfc2822FromDateTime = rfc2822.input;\n\n/**\n * An action output whose response decodes into a different shape, such as a file the API sends as\n * Base64: the action declares the decoded shape and the call decodes the response with `wire`.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface Decoded<Wire extends Schema.Top> {\n readonly _tag: \"Decoded\";\n readonly wire: Wire;\n}\n\n/**\n * Declares an output by the response schema it decodes from; see {@link Decoded}.\n *\n * @since 0.0.0\n * @category constructors\n */\nexport function decoded<const Wire extends Schema.Top>(wire: Wire): Decoded<Wire> {\n return { _tag: \"Decoded\", wire };\n}\n\ntype Request =\n | HttpClientRequest.HttpClientRequest\n | Effect.Effect<HttpClientRequest.HttpClientRequest, Action.ActionHandlerError>;\n\n/** `binary` returns a released version's base64 `ToolFile`; `file` stores the body as a file. */\ntype Body = \"json\" | \"text\" | \"binary\" | \"file\" | \"void\" | \"unknown\";\n\ntype GraphqlResponse = typeof GraphqlResponse.Type;\nconst GraphqlResponse = Schema.Struct({\n data: Schema.optionalKey(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))),\n errors: Schema.optionalKey(\n Schema.Array(\n Schema.StructWithRest(Schema.Struct({ message: Schema.String }), [\n Schema.Record(Schema.String, Schema.Unknown),\n ]),\n ),\n ),\n});\n\n/**\n * A response status, media type and decoding mode advertised by an HTTP action.\n *\n * @since 0.4.1\n * @category models\n */\nexport interface Variant {\n readonly status?: number;\n readonly contentType: string;\n readonly body: Body;\n readonly headers?: readonly string[];\n}\n\ntype Media =\n | { readonly contentBase64: Uint8Array; readonly contentType?: string | null }\n | Files.File;\n\ntype Upload =\n | { readonly mode: \"media\"; readonly media: Media }\n | { readonly mode: \"multipart\"; readonly media: Media; readonly metadata: unknown }\n | {\n readonly mode: \"start\";\n readonly contentType: string;\n readonly metadata?: unknown;\n readonly totalBytes: number;\n }\n | {\n readonly mode: \"chunk\";\n readonly sessionUrl: string;\n readonly totalBytes: number;\n readonly offset: number;\n readonly media: Media;\n }\n | { readonly mode: \"status\"; readonly sessionUrl: string; readonly totalBytes: number };\n\nfunction coerce(value: unknown) {\n return Predicate.isObject(value) ? JSON.stringify(value) : `${value}`;\n}\n\n/**\n * Encodes a path parameter as one segment.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function path(value: unknown) {\n return encodeURIComponent(coerce(value));\n}\n\n/**\n * Encodes a path parameter written inside single quotes, an OData string literal, doubling its\n * quotes: `O'Brien` in `People('{name}')` is sent as `People('O''Brien')`.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function literal(value: unknown) {\n return path(pipe(coerce(value), String.replaceAll(\"'\", \"''\")));\n}\n\n/**\n * Encodes a path parameter whose slashes stay path separators.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function segments(value: unknown) {\n return Array.join(Array.map(String.split(coerce(value), \"/\"), encodeURIComponent), \"/\");\n}\n\nfunction deepObject(name: string, value: unknown): [string, string][] {\n if (Array.isArray(value)) {\n return Array.flatMap(value, (item, index) => deepObject(`${name}[${index}]`, item));\n }\n if (Predicate.isObject(value)) {\n return Array.flatMap(Record.toEntries(value), entry =>\n deepObject(`${name}[${entry[0]}]`, entry[1]),\n );\n }\n return value === undefined ? [] : [[name, coerce(value)]];\n}\n\n/**\n * Query, header or form entries, repeating array values unless their name is joined, and encoding\n * `deep` names as bracketed keys such as `metadata[plan]` and `expand[0]`. A joined name is\n * comma-separated, or separated by the delimiter it is paired with, such as `[\"ids\", \"|\"]`.\n * `exploded` object parameters use their property names as query keys (`role=vet&active=true`).\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function params(\n fields: Record.ReadonlyRecord<string, unknown>,\n joined: readonly (string | readonly [string, string])[] = [],\n deep: readonly string[] = [],\n exploded: readonly string[] = [],\n) {\n return Array.flatMap(Record.toEntries(fields), field => {\n if (field[1] === undefined) return [];\n if (Array.contains(deep, field[0])) return deepObject(field[0], field[1]);\n const values = field[1];\n if (\n Array.contains(exploded, field[0]) &&\n Predicate.isObject(values) &&\n !Array.isArray(values)\n ) {\n return Array.filterMap(Record.toEntries(values), entry =>\n entry[1] === undefined\n ? Result.failVoid\n : Result.succeed([entry[0], coerce(entry[1])] as const),\n );\n }\n if (!Array.isArray(values)) return [[field[0], coerce(values)] as const];\n const separator = Array.findFirst(joined, entry => {\n const pair = Predicate.isString(entry) ? ([entry, \",\"] as const) : entry;\n return pair[0] === field[0] ? Option.some(pair[1]) : Option.none();\n });\n return Option.match(separator, {\n onNone: () => Array.map(values, item => [field[0], coerce(item)] as const),\n onSome: value => [[field[0], Array.join(Array.map(values, coerce), value)] as const],\n });\n });\n}\n\nfunction filePart(bytes: Uint8Array, name: string, contentType: string) {\n return new globalThis.File([new Uint8Array(bytes)], name, { type: contentType });\n}\n\n/**\n * Multipart form fields, sending each {@link File} as a file part.\n *\n * @since 0.0.0\n * @category encoding\n */\nexport function form(payload: Record.ReadonlyRecord<string, unknown>) {\n return Record.map(payload, (value, name) =>\n Array.map(Array.ensure(value), item => {\n if (item === undefined) return undefined;\n if (!Schema.is(File)(item)) return coerce(item);\n return filePart(\n item.contentBase64,\n item.filename ?? name,\n item.contentType ?? \"application/octet-stream\",\n );\n }),\n );\n}\n\nfunction fileFailed(error: Files.FileError) {\n return Action.ActionHandlerError.make({ cause: error, message: error.message });\n}\n\nfunction readFile(file: Files.File) {\n return pipe(Files.read(file), Effect.mapError(fileFailed));\n}\n\n/**\n * Sends a file as the raw request body.\n *\n * @since 0.1.0\n * @category encoding\n */\nexport const withFile = Effect.fnUntraced(function* (\n request: HttpClientRequest.HttpClientRequest,\n file: Files.File,\n) {\n return HttpClientRequest.bodyUint8Array(request, yield* readFile(file), file.contentType);\n});\n\n/**\n * Sends multipart form fields, each {@link Files.File} as a file part.\n *\n * @since 0.1.0\n * @category encoding\n */\nexport const withForm = Effect.fnUntraced(function* (\n request: HttpClientRequest.HttpClientRequest,\n payload: Record.ReadonlyRecord<string, unknown>,\n) {\n return HttpClientRequest.bodyFormDataRecord(\n request,\n Record.fromEntries(\n yield* Effect.forEach(Record.toEntries(payload), field =>\n Effect.map(\n Effect.forEach(\n Array.filter(Array.ensure(field[1]), item => item !== undefined),\n item =>\n Effect.gen(function* () {\n if (!Schema.is(Files.File)(item)) return coerce(item);\n return filePart(yield* readFile(item), item.name, item.contentType);\n }),\n ),\n parts => [field[0], parts] satisfies [string, (string | globalThis.File)[]],\n ),\n ),\n ),\n );\n});\n\nfunction mediaBytes(media: Media) {\n if (Schema.is(Files.File)(media)) {\n return Effect.map(readFile(media), bytes => ({ bytes, contentType: media.contentType }));\n }\n return Effect.succeed({\n bytes: media.contentBase64,\n contentType: Option.getOrNull(Option.fromNullishOr(media.contentType)),\n });\n}\n\nfunction isSafeUrl(value: string, origin?: string) {\n if (!URL.canParse(value)) return false;\n const url = new URL(value);\n return (\n url.protocol === \"https:\" &&\n url.username === \"\" &&\n url.password === \"\" &&\n (origin === undefined || url.origin === origin)\n );\n}\n\nfunction refused(message: string) {\n return Effect.fail(Action.ActionHandlerError.make({ message }));\n}\n\n/**\n * Follows a returned next-page link on the operation's own origin: only its path and query are\n * taken, so the connection's host routing applies and credentials never reach another host.\n *\n * @since 0.0.0\n * @category requests\n */\nexport function continuation(request: HttpClientRequest.HttpClientRequest, nextLink?: string) {\n if (nextLink === undefined) return Effect.succeed(request);\n const declared = new URL(request.url);\n const next = URL.canParse(nextLink) ? new URL(nextLink) : undefined;\n if (next === undefined || !isSafeUrl(nextLink) || next.pathname !== declared.pathname) {\n return refused(\"A continuation URL must be an HTTPS link to the same operation path\");\n }\n return Effect.succeed(\n HttpClientRequest.makeWith(\n request.method,\n `${declared.origin}${next.pathname}${next.search}`,\n UrlParams.empty,\n Option.none(),\n request.headers,\n HttpBody.empty,\n ),\n );\n}\n\n/**\n * A request to a preauthenticated upload URL, which is sent without the connection's credentials.\n *\n * @since 0.0.0\n * @category requests\n */\nexport function preauthenticated(\n method: (url: string) => HttpClientRequest.HttpClientRequest,\n url: string,\n ...steps: readonly ((\n request: HttpClientRequest.HttpClientRequest,\n ) => HttpClientRequest.HttpClientRequest)[]\n) {\n if (!isSafeUrl(url)) return refused(\"An upload session requires a preauthenticated HTTPS URL\");\n return Effect.succeed(Array.reduce(steps, method(url), (request, step) => step(request)));\n}\n\nfunction failure(\n error:\n | Action.ActionHandlerError\n | Action.HttpClientFailure\n | { readonly cause: unknown; readonly response: HttpClientResponse.HttpClientResponse },\n) {\n return Schema.is(Action.ActionHandlerError)(error) ? error : Action.fromHttpClientFailure(error);\n}\n\n// Like HttpClient.followRedirects, except that a redirect to another origin sends no\n// request header at all: auth methods may set any header, such as GitLab's PRIVATE-TOKEN.\nfunction redirect(response: HttpClientResponse.HttpClientResponse) {\n const location = response.headers[\"location\"];\n if (response.status < 300 || response.status >= 400 || location === undefined) return undefined;\n const sent = response.request;\n const url = new URL(location, sent.url);\n const request =\n (response.status === 303 && sent.method !== \"GET\" && sent.method !== \"HEAD\") ||\n ((response.status === 301 || response.status === 302) && sent.method === \"POST\")\n ? HttpClientRequest.setBody(HttpClientRequest.setMethod(sent, \"GET\"), HttpBody.empty)\n : sent;\n return url.origin === new URL(sent.url).origin\n ? HttpClientRequest.setUrl(request, url)\n : HttpClientRequest.setUrl(\n HttpClientRequest.makeWith(\n request.method,\n \"\",\n UrlParams.empty,\n Option.none(),\n Headers.empty,\n request.body,\n ),\n url,\n );\n}\n\nfunction follow(\n client: HttpClient.HttpClient,\n response: HttpClientResponse.HttpClientResponse,\n redirects: number,\n): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> {\n const next = redirect(response);\n return next === undefined || redirects === 10\n ? Effect.succeed(response)\n : Effect.flatMap(client.execute(next), result => follow(client, result, redirects + 1));\n}\n\n/** The file name a `Content-Disposition` header suggests, preferring its encoded form. */\nfunction dispositionName(header?: string) {\n if (header === undefined) return undefined;\n const encoded = pipe(\n String.match(/(?:^|;)\\s*filename\\*\\s*=\\s*UTF-8'[^']*'([^;]+)/iu)(header),\n Option.flatMap(match => Option.fromUndefinedOr(match[1])),\n );\n const decoded = pipe(\n encoded,\n Option.flatMap(value => Option.liftThrowable(() => decodeURIComponent(String.trim(value)))()),\n );\n return Option.getOrElse(decoded, () =>\n pipe(\n String.match(/(?:^|;)\\s*filename\\s*=\\s*(?:\"((?:\\\\.|[^\"\\\\])*)\"|([^;]*))/iu)(header),\n Option.flatMap(match =>\n Option.orElse(\n Option.map(Option.fromUndefinedOr(match[1]), name =>\n String.replace(/\\\\(.)/gu, \"$1\")(name),\n ),\n () => Option.map(Option.fromUndefinedOr(match[2]), String.trim),\n ),\n ),\n Option.getOrUndefined,\n ),\n );\n}\n\nconst read = Effect.fnUntraced(function* (\n response: HttpClientResponse.HttpClientResponse,\n body: Body,\n) {\n if (body === \"json\") return yield* response.json;\n if (body === \"text\") return yield* response.text;\n if (body === \"void\") return {};\n if (body === \"unknown\") {\n const text = yield* response.text;\n if (String.isEmpty(String.trim(text))) return null;\n return Option.getOrElse(\n Schema.decodeOption(Schema.fromJsonString(Schema.Json))(text),\n () => text,\n );\n }\n const bytes = new Uint8Array(yield* response.arrayBuffer);\n const name = dispositionName(response.headers[\"content-disposition\"]);\n if (body === \"file\") {\n const declared = response.headers[\"content-type\"] ?? null;\n return yield* pipe(\n Files.write({ bytes, contentType: fileContentType(bytes, declared), name: name ?? \"file\" }),\n Effect.mapError(fileFailed),\n );\n }\n return toolFile(bytes, response.headers[\"content-type\"] ?? null, name ?? null);\n});\n\n/**\n * One API operation as {@link make} returns it: its contract and the call that performs it. The\n * `Context` parameter lets a package name its handler context once, so declaration files print\n * `Endpoint<Context, …>` instead of repeating its auth methods in every action.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface Endpoint<Context, Input extends Schema.Top, Output extends Schema.Top> {\n readonly input: Input;\n readonly output: Output;\n readonly run: (\n input: Input[\"Type\"],\n context: Context,\n ) => Effect.Effect<Output[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>;\n}\n\n/**\n * An {@link Endpoint} whose output is the decoded type of the response schema it keeps as `wire`.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface DecodedEndpoint<Context, Input extends Schema.Top, Wire extends Schema.Top> {\n readonly input: Input;\n readonly output: Schema.toType<Wire>;\n readonly wire: Wire;\n readonly run: (\n input: Input[\"Type\"],\n context: Context,\n ) => Effect.Effect<Wire[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>;\n}\n\n/**\n * Binds the runtime to a package's auth module: the calls a generated version file makes. Its\n * `authorize` applies a connection's credentials to the client. Its optional `checkResponse` fails\n * a successful response that reports a failed call, such as Slack's `{ ok: false, error }`.\n * `preauthenticatedUploadUrl` restricts credential-free upload requests and every redirect to\n * provider-approved HTTPS URLs, without changing authenticated calls or other providers.\n *\n * @since 0.0.0\n * @category constructors\n */\nexport function make<\n const Methods extends readonly AuthMethod.Any[],\n Context extends Action.HandlerContext<Methods> = Action.HandlerContext<Methods>,\n>(auth: {\n readonly authorize: (\n client: HttpClient.HttpClient,\n context: Action.HandlerContext<Methods>,\n ) => HttpClient.HttpClient;\n readonly checkResponse?: (\n response: HttpClientResponse.HttpClientResponse,\n ) => Effect.Effect<void, Action.ActionHandlerError | HttpClientError.HttpClientError>;\n readonly preauthenticatedUploadUrl?: Schema.Schema<string>;\n}) {\n const { authorize, checkResponse = () => Effect.void } = auth;\n const send = Effect.fnUntraced(function* (context: Context | undefined, request: Request) {\n const base = yield* HttpClient.HttpClient;\n const uploadPolicy = context === undefined ? auth.preauthenticatedUploadUrl : undefined;\n const client =\n uploadPolicy === undefined\n ? base\n : HttpClient.mapRequestEffect(base, outgoing =>\n isSafeUrl(outgoing.url) && Schema.is(uploadPolicy)(outgoing.url)\n ? Effect.succeed(outgoing)\n : Effect.fail(\n new HttpClientError.HttpClientError({\n reason: new HttpClientError.InvalidUrlError({\n description: \"The upload URL is not an approved provider HTTPS destination\",\n request: outgoing,\n }),\n }),\n ),\n );\n const transport = HttpClient.transformResponse(\n client,\n Effect.flatMap(response => follow(client, response, 0)),\n );\n const authorized = context === undefined ? transport : authorize(transport, context);\n const execution = authorized.execute(Effect.isEffect(request) ? yield* request : request);\n const options = yield* Effect.serviceOption(FetchHttpClient.RequestInit);\n const response = yield* Boolean.match(uploadPolicy !== undefined, {\n onFalse: () => execution,\n onTrue: () =>\n Effect.provideService(execution, FetchHttpClient.RequestInit, {\n ...Option.getOrElse(options, () => ({})),\n redirect: \"manual\",\n }),\n });\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n yield* checkResponse(response);\n return response;\n });\n\n /**\n * One API operation: its action contract and the call that performs it. A {@link Decoded} output\n * declares the decoded shape and hands the call its response schema.\n */\n function endpoint<const Input extends Schema.Top, const Output extends Schema.Top>(\n contract: { readonly input: Input; readonly output: Output },\n run: (\n input: Input[\"Type\"],\n context: Context,\n output: Output,\n ) => Effect.Effect<Output[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>,\n ): Endpoint<Context, Input, Output>;\n function endpoint<const Input extends Schema.Top, const Wire extends Schema.Top>(\n contract: { readonly input: Input; readonly output: Decoded<Wire> },\n run: (\n input: Input[\"Type\"],\n context: Context,\n output: Wire,\n ) => Effect.Effect<Wire[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>,\n ): DecodedEndpoint<Context, Input, Wire>;\n function endpoint<const Input extends Schema.Top, const Output extends Schema.Top>(\n contract: { readonly input: Input; readonly output: Output | Decoded<Output> },\n run: (\n input: Input[\"Type\"],\n context: Context,\n output: Output,\n ) => Effect.Effect<Output[\"Type\"], Action.ActionHandlerFailure, HttpClient.HttpClient>,\n ) {\n if (!Schema.isSchema(contract.output)) {\n const wire = contract.output.wire;\n return {\n input: contract.input,\n output: Schema.toType(wire),\n run: (input: Input[\"Type\"], context: Context) => run(input, context, wire),\n wire,\n };\n }\n const output = contract.output;\n return {\n input: contract.input,\n output,\n run: (input: Input[\"Type\"], context: Context) => run(input, context, output),\n };\n }\n\n /** Sends a request and decodes its body as the operation's single response. */\n function execute<Output extends Schema.Top>(\n context: Context | undefined,\n output: Output,\n request: Request,\n body: Body,\n ) {\n return pipe(\n send(context, request),\n Effect.flatMap(response => read(response, body)),\n Effect.flatMap(decodeResponse(output)),\n Effect.mapError(failure),\n );\n }\n\n /** Sends a request and decodes the declared response variant its status and media type select. */\n const variants = Effect.fnUntraced(function* <Output extends Schema.Top>(\n context: Context | undefined,\n output: Output,\n request: Request,\n declared: readonly Variant[],\n media?: boolean,\n ) {\n const response = yield* send(context, request);\n const exact = Array.flatMap(declared, variant =>\n variant.status === undefined ? [] : [variant.status],\n );\n const contentType = pipe(\n response.headers[\"content-type\"] ?? \"\",\n String.split(\";\"),\n Array.headNonEmpty,\n String.trim,\n String.toLowerCase,\n );\n const ordered = Array.sort(\n declared,\n Order.mapInput(Order.Number, (variant: Variant) => {\n if (variant.body === \"void\" || variant.body === \"unknown\") return 3;\n if (variant.contentType === \"*/*\") return 2;\n return pipe(variant.contentType, String.endsWith(\"/*\")) ? 1 : 0;\n }),\n );\n const variant = Array.findFirst(ordered, candidate => {\n const status =\n candidate.status === undefined\n ? !Array.contains(exact, response.status)\n : candidate.status === response.status;\n if (!status) return false;\n if (media !== undefined) {\n return (candidate.body === \"binary\" || candidate.body === \"file\") === media;\n }\n if (\n candidate.body === \"void\" ||\n candidate.body === \"unknown\" ||\n candidate.contentType === \"*/*\"\n ) {\n return true;\n }\n if (pipe(candidate.contentType, String.endsWith(\"/*\"))) {\n return pipe(\n contentType,\n String.startsWith(pipe(candidate.contentType, String.slice(0, -1))),\n );\n }\n return contentType === candidate.contentType;\n });\n if (Option.isNone(variant)) {\n return yield* Effect.fail({\n cause: \"The API returned an undeclared successful response\",\n response,\n });\n }\n const headers = Array.flatMap(variant.value.headers ?? [], name => {\n const value = response.headers[String.toLowerCase(name)];\n return value === undefined ? [] : [[name, value] as const];\n });\n return yield* decodeResponse(output)({\n body: yield* read(response, variant.value.body),\n contentType: variant.value.contentType,\n status: response.status,\n ...(variant.value.headers === undefined ? {} : { headers: Record.fromEntries(headers) }),\n });\n }, Effect.mapError(failure));\n\n /** Google's media, multipart and resumable upload protocols. */\n const googleUpload = Effect.fnUntraced(function* <Output extends Schema.Top>(\n context: Context,\n output: Output,\n request: HttpClientRequest.HttpClientRequest,\n payload: Upload,\n options: { readonly maxSize?: number; readonly resumable?: string },\n ) {\n const client = authorize(yield* HttpClient.HttpClient, context);\n const media = \"media\" in payload ? yield* mediaBytes(payload.media) : undefined;\n const size = \"totalBytes\" in payload ? payload.totalBytes : (media?.bytes.byteLength ?? 0);\n if (size < 0 || (options.maxSize !== undefined && size > options.maxSize)) {\n return yield* refused(\"The upload size is outside the API's declared limit\");\n }\n const origin = new URL(request.url).origin;\n if (payload.mode === \"start\") {\n if (options.resumable === undefined) {\n return yield* refused(\"This API has no resumable upload protocol\");\n }\n const response = yield* client.execute(\n pipe(\n HttpClientRequest.setUrl(request, options.resumable),\n HttpClientRequest.setUrlParam(\"uploadType\", \"resumable\"),\n HttpClientRequest.setHeaders({\n \"x-upload-content-length\": `${size}`,\n \"x-upload-content-type\": payload.contentType,\n }),\n HttpClientRequest.bodyJsonUnsafe(payload.metadata ?? {}),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n const sessionUrl = response.headers[\"location\"];\n if (sessionUrl === undefined || !isSafeUrl(sessionUrl, origin)) {\n return yield* Effect.fail({\n cause: \"The API returned an invalid upload session URL\",\n response,\n });\n }\n return yield* decodeResponse(output)({ nextOffset: 0, sessionUrl, state: \"pending\" });\n }\n if (payload.mode === \"chunk\" || payload.mode === \"status\") {\n if (!isSafeUrl(payload.sessionUrl, origin)) {\n return yield* refused(\"The upload session URL must use the API's HTTPS origin\");\n }\n const bytes = media?.bytes ?? new Uint8Array();\n const end = payload.mode === \"chunk\" ? payload.offset + bytes.byteLength : 0;\n if (\n payload.mode === \"chunk\" &&\n (payload.offset < 0 ||\n bytes.byteLength === 0 ||\n end > size ||\n (end < size && bytes.byteLength % 262_144 !== 0))\n ) {\n return yield* refused(\n \"Upload chunks must fit the total size and use 256 KiB multiples except for the final chunk\",\n );\n }\n const response = yield* client.execute(\n pipe(\n HttpClientRequest.put(payload.sessionUrl),\n HttpClientRequest.bodyUint8Array(bytes, media?.contentType ?? \"application/octet-stream\"),\n HttpClientRequest.setHeader(\n \"content-range\",\n payload.mode === \"status\"\n ? `bytes */${size}`\n : `bytes ${payload.offset}-${end - 1}/${size}`,\n ),\n ),\n );\n if (response.status === 308) {\n const range = response.headers[\"range\"];\n if (range !== undefined && !/^bytes=0-\\d+$/u.test(range)) {\n return yield* Effect.fail({\n cause: \"The API returned an invalid upload range\",\n response,\n });\n }\n const nextOffset = range === undefined ? 0 : Number(pipe(range, String.slice(8))) + 1;\n if (nextOffset > size) {\n return yield* Effect.fail({\n cause: \"The API returned an upload offset beyond the total size\",\n response,\n });\n }\n return yield* decodeResponse(output)({\n nextOffset,\n sessionUrl: payload.sessionUrl,\n state: \"pending\",\n });\n }\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n return yield* decodeResponse(output)({ resource: yield* response.json, state: \"complete\" });\n }\n const selected = HttpClientRequest.setUrlParam(request, \"uploadType\", payload.mode);\n const bytes = media?.bytes ?? new Uint8Array();\n const contentType = media?.contentType ?? \"application/octet-stream\";\n const boundary = `dual-${yield* Random.nextInt}-${yield* Random.nextInt}`;\n const metadata =\n payload.mode === \"multipart\"\n ? yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown))(payload.metadata)\n : \"\";\n const body =\n payload.mode === \"media\"\n ? HttpClientRequest.bodyUint8Array(selected, bytes, contentType)\n : HttpClientRequest.bodyUint8Array(\n selected,\n new Uint8Array(\n yield* Effect.promise(() =>\n new Blob([\n `--${boundary}\\r\\nContent-Type: application/json; charset=UTF-8\\r\\n\\r\\n${metadata}\\r\\n--${boundary}\\r\\nContent-Type: ${contentType}\\r\\n\\r\\n`,\n new Uint8Array(bytes),\n `\\r\\n--${boundary}--\\r\\n`,\n ]).arrayBuffer(),\n ),\n ),\n `multipart/related; boundary=${boundary}`,\n );\n const response = yield* client.execute(body);\n if (response.status < 200 || response.status >= 300) {\n return yield* Effect.fail({ cause: yield* response.text, response });\n }\n return yield* decodeResponse(output)({ resource: yield* response.json, state: \"complete\" });\n }, Effect.mapError(failure));\n\n /** Sends a GraphQL operation and decodes its root field, failing with the errors it returns. */\n const graphql = Effect.fnUntraced(function* <Output extends Schema.Top>(\n context: Context,\n output: Output,\n request: Request,\n field: string,\n ) {\n const response = yield* send(context, request);\n const body = yield* Schema.decodeUnknownEffect(GraphqlResponse)(yield* response.json);\n if (body.errors !== undefined && Array.isReadonlyArrayNonEmpty(body.errors)) {\n return yield* Action.ActionHandlerError.make({\n details: body.errors,\n message: Array.join(\n Array.map(body.errors, error => error.message),\n \"; \",\n ),\n });\n }\n return yield* decodeResponse(output)(body.data?.[field]);\n }, Effect.mapError(failure));\n\n /**\n * Calls a Model Context Protocol tool in a session with the server. A tool that reports an error\n * fails the action with its text; otherwise the output is its structured content, or its content\n * blocks when it declares no output schema.\n */\n const mcp = Effect.fnUntraced(\n function* <Output extends Schema.Top>(\n context: Context,\n output: Output,\n server: string,\n tool: string,\n args: unknown,\n structured: boolean,\n ) {\n const connection = yield* Mcp.connect(\n authorize(yield* HttpClient.HttpClient, context),\n server,\n {},\n );\n const result = yield* Schema.decodeUnknownEffect(Mcp.CallToolResult)(\n yield* connection.request(\"tools/call\", { arguments: args, name: tool }),\n );\n if (result.isError === true) {\n return yield* Action.ActionHandlerError.make({\n details: result.content,\n message: Array.join(\n Array.flatMap(result.content, block => Array.fromNullishOr(block.text)),\n \"\\n\",\n ),\n });\n }\n return yield* decodeResponse(output)(\n Boolean.match(structured, {\n onFalse: () => ({ content: result.content }),\n onTrue: () => result.structuredContent,\n }),\n );\n },\n Effect.scoped,\n Effect.mapError(error =>\n Schema.is(Mcp.McpError)(error)\n ? Action.ActionHandlerError.make({ message: error.message })\n : failure(error),\n ),\n );\n\n return { endpoint, execute, googleUpload, graphql, mcp, variants };\n}\n\nexport * as Http from \"./Http.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,uBAAiC,OAAU,OAAiB;CACnE,IAAI,MAAM,OAAO,OAAO,KAAK,GAAG,OAAO;CACvC,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,QAAQ,KAAK,GAC7C,KAAK,MAAM,SAAS,MAAM,IAAI,OAAO,KAAK,GAAG,uBAAuB,MAAM,IAAI,MAAM,EAAE;MACjF,IAAI,UAAU,SAAS,KAAK,KAAK,UAAU,SAAS,KAAK,GAC9D,KAAK,MAAM,SAAS,OAAO,UAAU,KAAK,GACxC,IAAI,OAAO,IAAI,OAAO,MAAM,EAAE,GAC5B,uBAAuB,MAAM,MAAM,KAAK,MAAM,EAAE;MAEhD,OAAO,eAAe,OAAO,MAAM,IAAI;EACrC,cAAc;EACd,YAAY;EACZ,OAAO,MAAM;EACb,UAAU;CACZ,CAAC;CAIP,OAAO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W;IAAM,MAAM;GAAK,CAAC,CACzE;GACA,IAAI,OAAO,YAAY,MACrB,OAAO,OAAA,mBAAiC,KAAK;IAC3C,SAAS,OAAO;IAChB,SAAS,MAAM,KACb,MAAM,QAAQ,OAAO,UAAS,UAAS,MAAM,cAAc,MAAM,IAAI,CAAC,GACtE,IACF;GACF,CAAC;GAEH,OAAO,OAAO,eAAe,MAAM,CAAC,CAClC,QAAQ,MAAM,YAAY;IACxB,gBAAgB,EAAE,SAAS,OAAO,QAAQ;IAC1C,cAAc,OAAO;GACvB,CAAC,CACH;EACF,GACA,OAAO,QACP,OAAO,UAAS,UACd,OAAO,GAAGC,QAAY,CAAC,CAAC,KAAK,IAAA,mBACC,KAAK,EAAE,SAAS,MAAM,QAAQ,CAAC,IACzD,QAAQ,KAAK,CACnB,CAGmD;EAAG;CAAS;AACnE"}
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { AuthMethodBinding_exports } from "./AuthMethodBinding.js";
4
4
  import { OAuth2TokenRefresher_exports } from "./OAuth2TokenRefresher.js";
5
5
  import { AuthMethodExecution_exports } from "./AuthMethodExecution.js";
6
6
  import { AuthMethod_exports } from "./AuthMethod.js";
7
- import { ToolFile_exports } from "./ToolFile.js";
7
+ import { Files_exports } from "./Files.js";
8
8
  import { AgentChannel_exports } from "./AgentChannel.js";
9
9
  import { ConnectionResolver_exports } from "./ConnectionResolver.js";
10
10
  import { AgentChannelRuntime_exports } from "./AgentChannelRuntime.js";
@@ -13,9 +13,9 @@ import { DualRegistry_exports } from "./DualRegistry.js";
13
13
  import { Trigger_exports } from "./Trigger.js";
14
14
  import { DualRuntime_exports } from "./DualRuntime.js";
15
15
  import { AgentChannelConformance_exports } from "./AgentChannelConformance.js";
16
- import { Files_exports } from "./Files.js";
17
16
  import { Group_exports } from "./Group.js";
18
17
  import { Mcp_exports } from "./Mcp.js";
18
+ import { ToolFile_exports } from "./ToolFile.js";
19
19
  import { Http_exports } from "./Http.js";
20
20
  import { OAuthFlow_exports } from "./OAuthFlow.js";
21
21
  import { Plugin_exports } from "./Plugin.js";
@@ -1 +1 @@
1
- {"version":3,"file":"remote-runtime.d.ts","names":["Files.Service","ConnectionResolver.Service","DualRuntime.ActionHandlerNotFoundError","DualRuntime.ActionNotFoundError","_$__AuthMethod_ts0.AuthMethodHookError","DualRuntime.AuthMethodNotFoundError","AgentChannel.ChannelError","ConnectionResolver.ConnectionIdNotAllowedError","ConnectionResolver.ConnectionReauthorizationRequiredError","ConnectionResolver.ConnectionRequiredError","ConnectionResolver.ConnectionResolverStoreError","ConnectionResolver.ConnectionSelectionRequiredError","_$__AuthMethod_ts0.ExpectedOAuth2MethodError","DualRuntime.InvalidActionInputError","DualRuntime.InvalidActionOutputError","ConnectionResolver.InvalidConnectionIdError","ConnectionResolver.InvalidResolvedConnectionError","_$__AuthMethod_ts0.OAuth2RefreshTokenUnavailableError","DualRuntime.Service"],"sources":["../src/remote-runtime.ts"],"mappings":";;;;;;;;;;;;YA6BY,kBAAkB,SAAS;qBAC1B,UAAQ,OAAA;;;;;;;YAoDT,mBAAmB,UAAU;qBAC5B,WAAS,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAeV,oBAAoB,WAAW;qBAC9B,YAAU,OAAA;;;;YACX,iBAAiB,QAAQ;qBACxB,SAAO,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAyBR,iBAAiB,QAAQ;qBACxB,SAAO,OAAA,uBAAA,2BAAA,6BAAA,OAAA;;;;;;;;;;;;;;;;;YAKR,kBAAkB,SAAS;qBAC1B,UAAQ,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAML,QAAQ,iBAAiB;qBAqG5B,kBAAgB,MAAA,MAAAA;wBA2Eb,gBAAgB,SAAS,UAAO,MAAA,MAAAC;;qBAiFnC,UAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA2DlBiB"}
1
+ {"version":3,"file":"remote-runtime.d.ts","names":["Files.Service","ConnectionResolver.Service","DualRuntime.ActionHandlerNotFoundError","DualRuntime.ActionNotFoundError","_$__AuthMethod_ts0.AuthMethodHookError","DualRuntime.AuthMethodNotFoundError","AgentChannel.ChannelError","ConnectionResolver.ConnectionIdNotAllowedError","ConnectionResolver.ConnectionReauthorizationRequiredError","ConnectionResolver.ConnectionRequiredError","ConnectionResolver.ConnectionResolverStoreError","ConnectionResolver.ConnectionSelectionRequiredError","_$__AuthMethod_ts0.ExpectedOAuth2MethodError","DualRuntime.InvalidActionInputError","DualRuntime.InvalidActionOutputError","ConnectionResolver.InvalidConnectionIdError","ConnectionResolver.InvalidResolv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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA2DlBiB"}
@@ -1,11 +1,11 @@
1
1
  import { __exportAll } from "./_virtual/_rolldown/runtime.js";
2
2
  import { ActionHandlerError, RetryableActionHandlerError } from "./Action.js";
3
3
  import { JsonRequest } from "./AuthMethodExecution.js";
4
+ import { File, FileError, Service } from "./Files.js";
4
5
  import { ChannelError, ErrorCode, FailureCode, VerifiedIdentity } from "./AgentChannel.js";
5
- import { ConnectionRequiredError, InvalidConnectionIdError, Service } from "./ConnectionResolver.js";
6
+ import { ConnectionRequiredError, InvalidConnectionIdError, Service as Service$1 } from "./ConnectionResolver.js";
6
7
  import { InvalidActionInputError, InvalidActionOutputError } from "./internal/dual/invoke.js";
7
- import { Service as Service$1 } from "./DualRuntime.js";
8
- import { File, FileError, Service as Service$2 } from "./Files.js";
8
+ import { Service as Service$2 } from "./DualRuntime.js";
9
9
  import "./remote-runtime.js";
10
10
  import { Array, Cause, Effect, Layer, Match, Option, Predicate, Redacted, Schema, flow, pipe } from "effect";
11
11
  import { HttpClient, HttpClientRequest } from "effect/http";
@@ -206,13 +206,14 @@ function failure(error) {
206
206
  retryable: false
207
207
  };
208
208
  }
209
- const unavailableFiles = Service$2.of({
209
+ const unavailableFiles = Service.of({
210
210
  read: () => Effect.fail(FileError.make({ message: "Dual Files is not available to this operation" })),
211
211
  write: () => Effect.fail(FileError.make({ message: "Dual Files is not available to this operation" }))
212
212
  });
213
- const filesUnavailable = Layer.succeed(Service$2, unavailableFiles);
213
+ const filesUnavailable = Layer.succeed(Service, unavailableFiles);
214
214
  const FileFailure = Schema.Struct({ message: Schema.String });
215
215
  function filesService(access, http) {
216
+ let writes = 0;
216
217
  const client = HttpClient.mapRequest(http, flow(HttpClientRequest.prependUrl(`${access.url}/api/plugin-files`), HttpClientRequest.bearerToken(access.token)));
217
218
  function call(request, read) {
218
219
  return pipe(Effect.gen(function* () {
@@ -224,13 +225,16 @@ function filesService(access, http) {
224
225
  message: "Cannot reach Dual Files"
225
226
  })));
226
227
  }
227
- return Service$2.of({
228
+ return Service.of({
228
229
  read: (file) => call(HttpClientRequest.get(`/${encodeURIComponent(file.id)}`), (response) => Effect.map(response.arrayBuffer, (buffer) => new Uint8Array(buffer))),
229
- write: (file) => call(pipe(HttpClientRequest.post("", { urlParams: { name: file.name } }), HttpClientRequest.bodyUint8Array(file.bytes, file.contentType ?? void 0)), (response) => Effect.flatMap(response.json, Schema.decodeUnknownEffect(File)))
230
+ write: (file) => Effect.suspend(() => call(pipe(HttpClientRequest.post("", { urlParams: {
231
+ name: file.name,
232
+ writeIndex: `${writes++}`
233
+ } }), HttpClientRequest.bodyUint8Array(file.bytes, file.contentType ?? void 0)), (response) => Effect.flatMap(response.json, Schema.decodeUnknownEffect(File))))
230
234
  });
231
235
  }
232
236
  function connectionService(request) {
233
- return Service.of({ resolve: (input) => {
237
+ return Service$1.of({ resolve: (input) => {
234
238
  const selected = request.connection;
235
239
  if (selected === void 0) return Effect.fail(ConnectionRequiredError.make(input.target));
236
240
  if (selected.providerId !== input.target.providerId || input.connectionId !== void 0 && input.connectionId !== selected.connectionId) return Effect.fail(InvalidConnectionIdError.make({
@@ -245,10 +249,10 @@ function connectionService(request) {
245
249
  } });
246
250
  }
247
251
  function connectionLayer(request) {
248
- return Layer.succeed(Service, connectionService(request));
252
+ return Layer.succeed(Service$1, connectionService(request));
249
253
  }
250
254
  const run = Effect.fnUntraced(function* (request) {
251
- const runtime = yield* Service$1;
255
+ const runtime = yield* Service$2;
252
256
  const connectionId = Option.match(Option.fromUndefinedOr(request.connection), {
253
257
  onNone: () => ({}),
254
258
  onSome: (selected) => ({ connectionId: selected.connectionId })
@@ -330,7 +334,7 @@ const execute = Effect.fn("RemoteRuntime.execute")(function* (request) {
330
334
  },
331
335
  identity: request.identity
332
336
  };
333
- return yield* pipe(run(request), Effect.provideService(Service, connectionService(request)), Effect.provideService(Service$2, pipe(Option.fromUndefinedOr(request.files), Option.flatMap((access) => Option.map(http, (client) => filesService(access, client))), Option.getOrElse(() => unavailableFiles))), Effect.flatMap(Effect.fnUntraced(function* (value) {
337
+ return yield* pipe(run(request), Effect.provideService(Service$1, connectionService(request)), Effect.provideService(Service, pipe(Option.fromUndefinedOr(request.files), Option.flatMap((access) => Option.map(http, (client) => filesService(access, client))), Option.getOrElse(() => unavailableFiles))), Effect.flatMap(Effect.fnUntraced(function* (value) {
334
338
  if (value === void 0) return {
335
339
  _tag: "success",
336
340
  identity: request.identity
@@ -1 +1 @@
1
- {"version":3,"file":"remote-runtime.js","names":["AgentChannel.VerifiedIdentity","AuthMethodExecution.JsonRequest","AgentChannel.ErrorCode","AgentChannel.FailureCode","AgentChannel.ChannelError","Files.FileError","DualRuntime.InvalidActionInputError","DualRuntime.InvalidActionOutputError","Files.Service","Files.File","ConnectionResolver.Service","DualRuntime.Service"],"sources":["../src/remote-runtime.ts"],"sourcesContent":["/**\n * Data-only SDK lifecycle requests for an installed, isolated integration plugin.\n *\n * @since 0.3.0\n */\nimport {\n Array,\n Cause,\n Effect,\n Layer,\n Match,\n Option,\n Predicate,\n Redacted,\n Schema,\n flow,\n pipe,\n} from \"effect\";\n\nimport { HttpClient, HttpClientRequest } from \"effect/http\";\nimport type { HttpClientResponse } from \"effect/http\";\n\nimport { ActionHandlerError, RetryableActionHandlerError } from \"./Action.ts\";\nimport * as AgentChannel from \"./AgentChannel.ts\";\nimport { AuthMethodExecution } from \"./AuthMethodExecution.ts\";\nimport { ConnectionResolver } from \"./ConnectionResolver.ts\";\nimport { DualRuntime } from \"./DualRuntime.ts\";\nimport { Files } from \"./Files.ts\";\n\nexport type Identity = typeof Identity.Type;\nexport const Identity = Schema.Struct({\n artifactDigest: Schema.String.check(Schema.isPattern(/^[a-f0-9]{128}$/u)),\n invocationId: Schema.NonEmptyString,\n organizationId: Schema.NonEmptyString,\n pluginKey: Schema.NonEmptyString,\n pluginVersion: Schema.NonEmptyString,\n});\n\nconst connection = Schema.Struct({\n connectionId: Schema.NonEmptyString,\n material: Schema.Json,\n methodId: Schema.NonEmptyString,\n providerId: Schema.NonEmptyString,\n setup: Schema.optionalKey(Schema.Json),\n});\nconst context = Schema.Struct({\n actor: Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"user\"), userId: Schema.NonEmptyString }),\n Schema.Struct({ kind: Schema.Literal(\"system\"), reason: Schema.optionalKey(Schema.String) }),\n ]),\n metadata: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),\n source: Schema.Struct({\n kind: Schema.NonEmptyString,\n metadata: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),\n subjectId: Schema.optionalKey(Schema.String),\n }),\n tenant: Schema.Struct({ organizationId: Schema.NonEmptyString, teamId: Schema.NonEmptyString }),\n});\nconst trigger = {\n config: Schema.Json,\n state: Schema.optionalKey(Schema.Json),\n triggerId: Schema.NonEmptyString,\n};\nconst webhook = { ...trigger, webhookUrl: Schema.String };\nconst channel = {\n channelId: Schema.NonEmptyString,\n definitionSettings: Schema.Json,\n deploymentSettings: Schema.Json,\n};\nconst delivery = {\n ...webhook,\n request: Schema.Struct({\n body: Schema.Json,\n headers: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n method: Schema.optionalKey(Schema.String),\n query: Schema.optionalKey(\n Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Array(Schema.String)])),\n ),\n rawBody: Schema.Uint8ArrayFromBase64,\n url: Schema.optionalKey(Schema.String),\n }),\n};\nexport type Operation = typeof Operation.Type;\nexport const Operation = Schema.Union([\n Schema.TaggedStruct(\"invoke\", { actionId: Schema.NonEmptyString, input: Schema.Json }),\n Schema.TaggedStruct(\"activate\", webhook),\n Schema.TaggedStruct(\"deactivate\", webhook),\n Schema.TaggedStruct(\"verify\", delivery),\n Schema.TaggedStruct(\"parse\", delivery),\n Schema.TaggedStruct(\"poll\", trigger),\n Schema.TaggedStruct(\"channelCheckAccess\", {\n ...channel,\n identity: AgentChannel.VerifiedIdentity,\n }),\n Schema.TaggedStruct(\"channelExecute\", { ...channel, command: Schema.Json }),\n AuthMethodExecution.JsonRequest,\n]);\n/** Where this call reads and stores the caller's files, and the token that lets it. */\nexport type FileAccess = typeof FileAccess.Type;\nexport const FileAccess = Schema.Struct({ token: Schema.NonEmptyString, url: Schema.String });\nexport type Request = typeof Request.Type;\nexport const Request = Schema.Struct({\n connection: Schema.optionalKey(connection),\n context,\n files: Schema.optionalKey(FileAccess),\n identity: Identity,\n operation: Operation,\n});\n\nconst RuntimeFailure = Schema.Struct({\n category: Schema.Literals([\"validation\", \"connection\", \"handler\", \"initialization\", \"protocol\"]),\n /** The Agent Channel failure the host rebuilds as its `ChannelError`. */\n channel: Schema.optionalKey(\n Schema.Struct({\n code: AgentChannel.ErrorCode,\n providerCode: Schema.optionalKey(AgentChannel.FailureCode),\n }),\n ),\n code: Schema.String,\n fields: Schema.optionalKey(Schema.Array(Schema.Struct({ path: Schema.String }))),\n message: Schema.String,\n retryAfterSeconds: Schema.optionalKey(Schema.Finite),\n retryable: Schema.Boolean,\n /** The provider's HTTP status, kept so the host can report why a provider rejected the call. */\n status: Schema.optionalKey(Schema.Int),\n});\nexport type Failure = typeof Failure.Type;\nexport const Failure = Schema.Union([\n ActionHandlerError,\n RetryableActionHandlerError,\n RuntimeFailure,\n]);\nexport type Response = typeof Response.Type;\nexport const Response = Schema.Union([\n Schema.TaggedStruct(\"success\", { identity: Identity, value: Schema.optionalKey(Schema.Json) }),\n Schema.TaggedStruct(\"failure\", { error: Failure, identity: Identity }),\n]);\n\n// Declared Action failures reach the host intact; the host owns public error filtering.\nexport function failure(error: unknown): Failure {\n if (Schema.is(ActionHandlerError)(error) || Schema.is(RetryableActionHandlerError)(error)) {\n return error;\n }\n if (Schema.is(AgentChannel.ChannelError)(error)) {\n return {\n category: \"handler\",\n channel: Option.match(Option.fromUndefinedOr(error.providerCode), {\n onNone: () => ({ code: error.code }),\n onSome: providerCode => ({ code: error.code, providerCode }),\n }),\n code: error._tag,\n message: \"Agent Channel operation failed\",\n retryable: false,\n };\n }\n if (Schema.is(Files.FileError)(error)) {\n return {\n category: \"handler\",\n code: \"FileError\",\n message: \"A Dual Files operation failed\",\n retryable: false,\n };\n }\n if (\n Schema.is(DualRuntime.InvalidActionInputError)(error) ||\n Schema.is(DualRuntime.InvalidActionOutputError)(error)\n ) {\n return {\n category: \"validation\",\n code: error._tag,\n fields: Array.map(error.fields, field => ({ path: field.path })),\n message: \"Plugin action validation failed\",\n retryable: false,\n };\n }\n const tag =\n Predicate.hasProperty(error, \"_tag\") && Predicate.isString(error._tag)\n ? error._tag\n : \"PluginHandlerError\";\n const category = pipe(\n Match.value(tag),\n Match.when(\"SchemaError\", () => \"validation\" as const),\n Match.whenOr(\n \"InvalidTriggerConfigError\",\n \"InvalidTriggerStateError\",\n \"InvalidTriggerOutputError\",\n () => \"validation\" as const,\n ),\n Match.whenOr(\n \"ConnectionRequiredError\",\n \"InvalidConnectionIdError\",\n \"InvalidResolvedConnectionError\",\n \"ConnectionIdNotAllowedError\",\n \"AuthMethodNotFoundError\",\n \"AuthMethodHookError\",\n \"ExpectedOAuth2MethodError\",\n \"OAuth2RefreshTokenUnavailableError\",\n () => \"connection\" as const,\n ),\n Match.orElse(() => \"handler\" as const),\n );\n return {\n category,\n code: Array.contains(\n [\n \"SchemaError\",\n \"InvalidTriggerConfigError\",\n \"InvalidTriggerStateError\",\n \"InvalidTriggerOutputError\",\n \"ConnectionRequiredError\",\n \"InvalidConnectionIdError\",\n \"InvalidResolvedConnectionError\",\n \"ConnectionIdNotAllowedError\",\n \"AuthMethodNotFoundError\",\n \"AuthMethodHookError\",\n \"ExpectedOAuth2MethodError\",\n \"OAuth2RefreshTokenUnavailableError\",\n \"ActionNotFoundError\",\n \"ActionHandlerNotFoundError\",\n \"TriggerNotFoundError\",\n \"UnsupportedTriggerRuntimeError\",\n \"FileError\",\n \"SandboxAccessNotDeclaredError\",\n \"SandboxRequestNotAllowedError\",\n ],\n tag,\n )\n ? tag\n : \"PluginHandlerError\",\n message: \"Plugin operation failed\",\n retryable: false,\n };\n}\n\nconst unavailableFiles = Files.Service.of({\n read: () =>\n Effect.fail(Files.FileError.make({ message: \"Dual Files is not available to this operation\" })),\n write: () =>\n Effect.fail(Files.FileError.make({ message: \"Dual Files is not available to this operation\" })),\n});\nexport const filesUnavailable = Layer.succeed(Files.Service, unavailableFiles);\n\nconst FileFailure = Schema.Struct({ message: Schema.String });\n\n// The host's file routes do the reading and storing, as the caller the token names.\nfunction filesService(access: FileAccess, http: HttpClient.HttpClient) {\n const client = HttpClient.mapRequest(\n http,\n flow(\n HttpClientRequest.prependUrl(`${access.url}/api/plugin-files`),\n HttpClientRequest.bearerToken(access.token),\n ),\n );\n function call<A>(\n request: HttpClientRequest.HttpClientRequest,\n read: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, unknown>,\n ) {\n return pipe(\n Effect.gen(function* () {\n const response = yield* client.execute(request);\n if (response.status < 200 || response.status >= 300) {\n return yield* Files.FileError.make(\n yield* Schema.decodeUnknownEffect(FileFailure)(yield* response.json),\n );\n }\n return yield* read(response);\n }),\n Effect.mapError(cause =>\n Schema.is(Files.FileError)(cause)\n ? cause\n : Files.FileError.make({\n cause: Redacted.make(cause),\n message: \"Cannot reach Dual Files\",\n }),\n ),\n );\n }\n return Files.Service.of({\n read: file =>\n call(HttpClientRequest.get(`/${encodeURIComponent(file.id)}`), response =>\n Effect.map(response.arrayBuffer, buffer => new Uint8Array(buffer)),\n ),\n write: file =>\n call(\n pipe(\n HttpClientRequest.post(\"\", { urlParams: { name: file.name } }),\n HttpClientRequest.bodyUint8Array(file.bytes, file.contentType ?? undefined),\n ),\n response => Effect.flatMap(response.json, Schema.decodeUnknownEffect(Files.File)),\n ),\n });\n}\n\nfunction connectionService(request: Request) {\n return ConnectionResolver.Service.of({\n resolve: input => {\n const selected = request.connection;\n if (selected === undefined) {\n return Effect.fail(ConnectionResolver.ConnectionRequiredError.make(input.target));\n }\n if (\n selected.providerId !== input.target.providerId ||\n (input.connectionId !== undefined && input.connectionId !== selected.connectionId)\n ) {\n return Effect.fail(\n ConnectionResolver.InvalidConnectionIdError.make({\n ...input.target,\n connectionId: input.connectionId ?? selected.connectionId,\n }),\n );\n }\n return Effect.succeed({ ...selected, encoding: \"json\" as const, setup: selected.setup });\n },\n });\n}\nexport function connectionLayer(request: Request) {\n return Layer.succeed(ConnectionResolver.Service, connectionService(request));\n}\n\nconst run = Effect.fnUntraced(\n function* (request: Request) {\n const runtime = yield* DualRuntime.Service;\n const connectionId = Option.match(Option.fromUndefinedOr(request.connection), {\n onNone: () => ({}),\n onSome: selected => ({ connectionId: selected.connectionId }),\n });\n const target = {\n ...connectionId,\n context: request.context,\n pluginKey: request.identity.pluginKey,\n };\n const operation = request.operation;\n if (operation._tag === \"invoke\") {\n return yield* runtime.invokeJson({ ...operation, ...target });\n }\n if (operation._tag === \"poll\") {\n const result = yield* flow(\n runtime.pollTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n if (result.state === undefined) return { events: result.events, meta: result.meta };\n return result;\n }\n if (operation._tag === \"activate\") {\n const result = yield* flow(\n runtime.activateTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n if (result.state === undefined) return { meta: result.meta };\n return result;\n }\n if (operation._tag === \"deactivate\") {\n return yield* flow(\n runtime.deactivateTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n }\n if (operation._tag === \"verify\") {\n return yield* flow(\n runtime.verifyTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n }\n if (operation._tag === \"parse\") {\n const result = yield* flow(\n runtime.parseTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n if (result.state === undefined) return { events: result.events, meta: result.meta };\n return result;\n }\n if (operation._tag === \"channelCheckAccess\") {\n return yield* runtime.checkAccessAgentChannel({\n channelId: operation.channelId,\n definitionSettings: operation.definitionSettings,\n deploymentSettings: operation.deploymentSettings,\n identity: operation.identity,\n ...connectionId,\n });\n }\n if (operation._tag === \"channelExecute\") {\n return yield* runtime.executeAgentChannel({\n channelId: operation.channelId,\n command: operation.command,\n definitionSettings: operation.definitionSettings,\n deploymentSettings: operation.deploymentSettings,\n ...connectionId,\n });\n }\n\n return yield* runtime.executeAuthJson(operation);\n },\n Effect.mapError(error => (Schema.is(Failure)(error) ? error : failure(error))),\n);\n\n/** Execute only in the guest after importing and building its installed plugin. */\nexport const execute = Effect.fn(\"RemoteRuntime.execute\")(function* (request: Request) {\n // The guest runner supplies its fetch client; a host calling in-process has no file routes to reach.\n const http = yield* Effect.serviceOption(HttpClient.HttpClient);\n if (request.identity.organizationId !== request.context.tenant.organizationId) {\n return {\n _tag: \"failure\",\n error: {\n category: \"protocol\",\n code: \"OrganizationMismatch\",\n message: \"Invocation organization does not match its context\",\n retryable: false,\n },\n identity: request.identity,\n } satisfies Response;\n }\n return yield* pipe(\n run(request),\n Effect.provideService(ConnectionResolver.Service, connectionService(request)),\n Effect.provideService(\n Files.Service,\n pipe(\n Option.fromUndefinedOr(request.files),\n Option.flatMap(access => Option.map(http, client => filesService(access, client))),\n Option.getOrElse(() => unavailableFiles),\n ),\n ),\n Effect.flatMap(\n Effect.fnUntraced(function* (value) {\n if (value === undefined) {\n return { _tag: \"success\", identity: request.identity } satisfies Response;\n }\n return {\n _tag: \"success\",\n identity: request.identity,\n value: yield* pipe(\n Schema.decodeUnknownEffect(Schema.Json)(value),\n Effect.mapError(failure),\n ),\n } satisfies Response;\n }),\n ),\n Effect.catch(error =>\n Effect.succeed({ _tag: \"failure\", error, identity: request.identity } satisfies Response),\n ),\n Effect.catchCauseIf(\n cause => !Cause.hasInterrupts(cause),\n () =>\n Effect.succeed({\n _tag: \"failure\",\n error: {\n category: \"handler\",\n code: \"PluginDefect\",\n message: \"Plugin operation failed\",\n retryable: false,\n },\n identity: request.identity,\n } satisfies Response),\n ),\n );\n});\n\nexport * as RemoteRuntime from \"./remote-runtime.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,WAAW,OAAO,OAAO;CACpC,gBAAgB,OAAO,OAAO,MAAM,OAAO,UAAU,kBAAkB,CAAC;CACxE,cAAc,OAAO;CACrB,gBAAgB,OAAO;CACvB,WAAW,OAAO;CAClB,eAAe,OAAO;AACxB,CAAC;AAED,MAAM,aAAa,OAAO,OAAO;CAC/B,cAAc,OAAO;CACrB,UAAU,OAAO;CACjB,UAAU,OAAO;CACjB,YAAY,OAAO;CACnB,OAAO,OAAO,YAAY,OAAO,IAAI;AACvC,CAAC;AACD,MAAM,UAAU,OAAO,OAAO;CAC5B,OAAO,OAAO,MAAM,CAClB,OAAO,OAAO;EAAE,MAAM,OAAO,QAAQ,MAAM;EAAG,QAAQ,OAAO;CAAe,CAAC,GAC7E,OAAO,OAAO;EAAE,MAAM,OAAO,QAAQ,QAAQ;EAAG,QAAQ,OAAO,YAAY,OAAO,MAAM;CAAE,CAAC,CAC7F,CAAC;CACD,UAAU,OAAO,YAAY,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI,CAAC;CACtE,QAAQ,OAAO,OAAO;EACpB,MAAM,OAAO;EACb,UAAU,OAAO,YAAY,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI,CAAC;EACtE,WAAW,OAAO,YAAY,OAAO,MAAM;CAC7C,CAAC;CACD,QAAQ,OAAO,OAAO;EAAE,gBAAgB,OAAO;EAAgB,QAAQ,OAAO;CAAe,CAAC;AAChG,CAAC;AACD,MAAM,UAAU;CACd,QAAQ,OAAO;CACf,OAAO,OAAO,YAAY,OAAO,IAAI;CACrC,WAAW,OAAO;AACpB;AACA,MAAM,UAAU;CAAE,GAAG;C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AEvD,OAAO;GACL,MAAM;GACN,UAAU,QAAQ;GAClB,OAAO,OAAO,KACZ,OAAO,oBAAoB,OAAO,IAAI,CAAC,CAAC,KAAK,GAC7C,OAAO,SAAS,OAAO,CACzB;EACF;CACF,CAAC,CACH,GACA,OAAO,OAAM,UACX,OAAO,QAAQ;EAAE,MAAM;EAAW;EAAO,UAAU,QAAQ;CAAS,CAAoB,CAC1F,GACA,OAAO,cACL,UAAS,CAAC,MAAM,cAAc,KAAK,SAEjC,OAAO,QAAQ;EACb,MAAM;EACN,OAAO;GACL,UAAU;GACV,MAAM;GACN,SAAS;GACT,WAAW;EACb;EACA,UAAU,QAAQ;CACpB,CAAoB,CACxB,CACF;AACF,CAAC"}
1
+ {"version":3,"file":"remote-runtime.js","names":["AgentChannel.VerifiedIdentity","AuthMethodExecution.JsonRequest","AgentChannel.ErrorCode","AgentChannel.FailureCode","AgentChannel.ChannelError","Files.FileError","DualRuntime.InvalidActionInputError","DualRuntime.InvalidActionOutputError","Files.Service","Files.File","ConnectionResolver.Service","DualRuntime.Service"],"sources":["../src/remote-runtime.ts"],"sourcesContent":["/**\n * Data-only SDK lifecycle requests for an installed, isolated integration plugin.\n *\n * @since 0.3.0\n */\nimport {\n Array,\n Cause,\n Effect,\n Layer,\n Match,\n Option,\n Predicate,\n Redacted,\n Schema,\n flow,\n pipe,\n} from \"effect\";\n\nimport { HttpClient, HttpClientRequest } from \"effect/http\";\nimport type { HttpClientResponse } from \"effect/http\";\n\nimport { ActionHandlerError, RetryableActionHandlerError } from \"./Action.ts\";\nimport * as AgentChannel from \"./AgentChannel.ts\";\nimport { AuthMethodExecution } from \"./AuthMethodExecution.ts\";\nimport { ConnectionResolver } from \"./ConnectionResolver.ts\";\nimport { DualRuntime } from \"./DualRuntime.ts\";\nimport { Files } from \"./Files.ts\";\n\nexport type Identity = typeof Identity.Type;\nexport const Identity = Schema.Struct({\n artifactDigest: Schema.String.check(Schema.isPattern(/^[a-f0-9]{128}$/u)),\n invocationId: Schema.NonEmptyString,\n organizationId: Schema.NonEmptyString,\n pluginKey: Schema.NonEmptyString,\n pluginVersion: Schema.NonEmptyString,\n});\n\nconst connection = Schema.Struct({\n connectionId: Schema.NonEmptyString,\n material: Schema.Json,\n methodId: Schema.NonEmptyString,\n providerId: Schema.NonEmptyString,\n setup: Schema.optionalKey(Schema.Json),\n});\nconst context = Schema.Struct({\n actor: Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"user\"), userId: Schema.NonEmptyString }),\n Schema.Struct({ kind: Schema.Literal(\"system\"), reason: Schema.optionalKey(Schema.String) }),\n ]),\n metadata: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),\n source: Schema.Struct({\n kind: Schema.NonEmptyString,\n metadata: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),\n subjectId: Schema.optionalKey(Schema.String),\n }),\n tenant: Schema.Struct({ organizationId: Schema.NonEmptyString, teamId: Schema.NonEmptyString }),\n});\nconst trigger = {\n config: Schema.Json,\n state: Schema.optionalKey(Schema.Json),\n triggerId: Schema.NonEmptyString,\n};\nconst webhook = { ...trigger, webhookUrl: Schema.String };\nconst channel = {\n channelId: Schema.NonEmptyString,\n definitionSettings: Schema.Json,\n deploymentSettings: Schema.Json,\n};\nconst delivery = {\n ...webhook,\n request: Schema.Struct({\n body: Schema.Json,\n headers: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),\n method: Schema.optionalKey(Schema.String),\n query: Schema.optionalKey(\n Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Array(Schema.String)])),\n ),\n rawBody: Schema.Uint8ArrayFromBase64,\n url: Schema.optionalKey(Schema.String),\n }),\n};\nexport type Operation = typeof Operation.Type;\nexport const Operation = Schema.Union([\n Schema.TaggedStruct(\"invoke\", { actionId: Schema.NonEmptyString, input: Schema.Json }),\n Schema.TaggedStruct(\"activate\", webhook),\n Schema.TaggedStruct(\"deactivate\", webhook),\n Schema.TaggedStruct(\"verify\", delivery),\n Schema.TaggedStruct(\"parse\", delivery),\n Schema.TaggedStruct(\"poll\", trigger),\n Schema.TaggedStruct(\"channelCheckAccess\", {\n ...channel,\n identity: AgentChannel.VerifiedIdentity,\n }),\n Schema.TaggedStruct(\"channelExecute\", { ...channel, command: Schema.Json }),\n AuthMethodExecution.JsonRequest,\n]);\n/** Where this call reads and stores the caller's files, and the token that lets it. */\nexport type FileAccess = typeof FileAccess.Type;\nexport const FileAccess = Schema.Struct({ token: Schema.NonEmptyString, url: Schema.String });\nexport type Request = typeof Request.Type;\nexport const Request = Schema.Struct({\n connection: Schema.optionalKey(connection),\n context,\n files: Schema.optionalKey(FileAccess),\n identity: Identity,\n operation: Operation,\n});\n\nconst RuntimeFailure = Schema.Struct({\n category: Schema.Literals([\"validation\", \"connection\", \"handler\", \"initialization\", \"protocol\"]),\n /** The Agent Channel failure the host rebuilds as its `ChannelError`. */\n channel: Schema.optionalKey(\n Schema.Struct({\n code: AgentChannel.ErrorCode,\n providerCode: Schema.optionalKey(AgentChannel.FailureCode),\n }),\n ),\n code: Schema.String,\n fields: Schema.optionalKey(Schema.Array(Schema.Struct({ path: Schema.String }))),\n message: Schema.String,\n retryAfterSeconds: Schema.optionalKey(Schema.Finite),\n retryable: Schema.Boolean,\n /** The provider's HTTP status, kept so the host can report why a provider rejected the call. */\n status: Schema.optionalKey(Schema.Int),\n});\nexport type Failure = typeof Failure.Type;\nexport const Failure = Schema.Union([\n ActionHandlerError,\n RetryableActionHandlerError,\n RuntimeFailure,\n]);\nexport type Response = typeof Response.Type;\nexport const Response = Schema.Union([\n Schema.TaggedStruct(\"success\", { identity: Identity, value: Schema.optionalKey(Schema.Json) }),\n Schema.TaggedStruct(\"failure\", { error: Failure, identity: Identity }),\n]);\n\n// Declared Action failures reach the host intact; the host owns public error filtering.\nexport function failure(error: unknown): Failure {\n if (Schema.is(ActionHandlerError)(error) || Schema.is(RetryableActionHandlerError)(error)) {\n return error;\n }\n if (Schema.is(AgentChannel.ChannelError)(error)) {\n return {\n category: \"handler\",\n channel: Option.match(Option.fromUndefinedOr(error.providerCode), {\n onNone: () => ({ code: error.code }),\n onSome: providerCode => ({ code: error.code, providerCode }),\n }),\n code: error._tag,\n message: \"Agent Channel operation failed\",\n retryable: false,\n };\n }\n if (Schema.is(Files.FileError)(error)) {\n return {\n category: \"handler\",\n code: \"FileError\",\n message: \"A Dual Files operation failed\",\n retryable: false,\n };\n }\n if (\n Schema.is(DualRuntime.InvalidActionInputError)(error) ||\n Schema.is(DualRuntime.InvalidActionOutputError)(error)\n ) {\n return {\n category: \"validation\",\n code: error._tag,\n fields: Array.map(error.fields, field => ({ path: field.path })),\n message: \"Plugin action validation failed\",\n retryable: false,\n };\n }\n const tag =\n Predicate.hasProperty(error, \"_tag\") && Predicate.isString(error._tag)\n ? error._tag\n : \"PluginHandlerError\";\n const category = pipe(\n Match.value(tag),\n Match.when(\"SchemaError\", () => \"validation\" as const),\n Match.whenOr(\n \"InvalidTriggerConfigError\",\n \"InvalidTriggerStateError\",\n \"InvalidTriggerOutputError\",\n () => \"validation\" as const,\n ),\n Match.whenOr(\n \"ConnectionRequiredError\",\n \"InvalidConnectionIdError\",\n \"InvalidResolvedConnectionError\",\n \"ConnectionIdNotAllowedError\",\n \"AuthMethodNotFoundError\",\n \"AuthMethodHookError\",\n \"ExpectedOAuth2MethodError\",\n \"OAuth2RefreshTokenUnavailableError\",\n () => \"connection\" as const,\n ),\n Match.orElse(() => \"handler\" as const),\n );\n return {\n category,\n code: Array.contains(\n [\n \"SchemaError\",\n \"InvalidTriggerConfigError\",\n \"InvalidTriggerStateError\",\n \"InvalidTriggerOutputError\",\n \"ConnectionRequiredError\",\n \"InvalidConnectionIdError\",\n \"InvalidResolvedConnectionError\",\n \"ConnectionIdNotAllowedError\",\n \"AuthMethodNotFoundError\",\n \"AuthMethodHookError\",\n \"ExpectedOAuth2MethodError\",\n \"OAuth2RefreshTokenUnavailableError\",\n \"ActionNotFoundError\",\n \"ActionHandlerNotFoundError\",\n \"TriggerNotFoundError\",\n \"UnsupportedTriggerRuntimeError\",\n \"FileError\",\n \"SandboxAccessNotDeclaredError\",\n \"SandboxRequestNotAllowedError\",\n ],\n tag,\n )\n ? tag\n : \"PluginHandlerError\",\n message: \"Plugin operation failed\",\n retryable: false,\n };\n}\n\nconst unavailableFiles = Files.Service.of({\n read: () =>\n Effect.fail(Files.FileError.make({ message: \"Dual Files is not available to this operation\" })),\n write: () =>\n Effect.fail(Files.FileError.make({ message: \"Dual Files is not available to this operation\" })),\n});\nexport const filesUnavailable = Layer.succeed(Files.Service, unavailableFiles);\n\nconst FileFailure = Schema.Struct({ message: Schema.String });\n\n// The host's file routes do the reading and storing, as the caller the token names.\nfunction filesService(access: FileAccess, http: HttpClient.HttpClient) {\n let writes = 0;\n const client = HttpClient.mapRequest(\n http,\n flow(\n HttpClientRequest.prependUrl(`${access.url}/api/plugin-files`),\n HttpClientRequest.bearerToken(access.token),\n ),\n );\n function call<A>(\n request: HttpClientRequest.HttpClientRequest,\n read: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, unknown>,\n ) {\n return pipe(\n Effect.gen(function* () {\n const response = yield* client.execute(request);\n if (response.status < 200 || response.status >= 300) {\n return yield* Files.FileError.make(\n yield* Schema.decodeUnknownEffect(FileFailure)(yield* response.json),\n );\n }\n return yield* read(response);\n }),\n Effect.mapError(cause =>\n Schema.is(Files.FileError)(cause)\n ? cause\n : Files.FileError.make({\n cause: Redacted.make(cause),\n message: \"Cannot reach Dual Files\",\n }),\n ),\n );\n }\n return Files.Service.of({\n read: file =>\n call(HttpClientRequest.get(`/${encodeURIComponent(file.id)}`), response =>\n Effect.map(response.arrayBuffer, buffer => new Uint8Array(buffer)),\n ),\n write: file =>\n Effect.suspend(() =>\n call(\n pipe(\n HttpClientRequest.post(\"\", {\n urlParams: { name: file.name, writeIndex: `${writes++}` },\n }),\n HttpClientRequest.bodyUint8Array(file.bytes, file.contentType ?? undefined),\n ),\n response => Effect.flatMap(response.json, Schema.decodeUnknownEffect(Files.File)),\n ),\n ),\n });\n}\n\nfunction connectionService(request: Request) {\n return ConnectionResolver.Service.of({\n resolve: input => {\n const selected = request.connection;\n if (selected === undefined) {\n return Effect.fail(ConnectionResolver.ConnectionRequiredError.make(input.target));\n }\n if (\n selected.providerId !== input.target.providerId ||\n (input.connectionId !== undefined && input.connectionId !== selected.connectionId)\n ) {\n return Effect.fail(\n ConnectionResolver.InvalidConnectionIdError.make({\n ...input.target,\n connectionId: input.connectionId ?? selected.connectionId,\n }),\n );\n }\n return Effect.succeed({ ...selected, encoding: \"json\" as const, setup: selected.setup });\n },\n });\n}\nexport function connectionLayer(request: Request) {\n return Layer.succeed(ConnectionResolver.Service, connectionService(request));\n}\n\nconst run = Effect.fnUntraced(\n function* (request: Request) {\n const runtime = yield* DualRuntime.Service;\n const connectionId = Option.match(Option.fromUndefinedOr(request.connection), {\n onNone: () => ({}),\n onSome: selected => ({ connectionId: selected.connectionId }),\n });\n const target = {\n ...connectionId,\n context: request.context,\n pluginKey: request.identity.pluginKey,\n };\n const operation = request.operation;\n if (operation._tag === \"invoke\") {\n return yield* runtime.invokeJson({ ...operation, ...target });\n }\n if (operation._tag === \"poll\") {\n const result = yield* flow(\n runtime.pollTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n if (result.state === undefined) return { events: result.events, meta: result.meta };\n return result;\n }\n if (operation._tag === \"activate\") {\n const result = yield* flow(\n runtime.activateTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n if (result.state === undefined) return { meta: result.meta };\n return result;\n }\n if (operation._tag === \"deactivate\") {\n return yield* flow(\n runtime.deactivateTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n }\n if (operation._tag === \"verify\") {\n return yield* flow(\n runtime.verifyTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n }\n if (operation._tag === \"parse\") {\n const result = yield* flow(\n runtime.parseTrigger,\n Effect.mapError(failure),\n )({ ...operation, ...target });\n if (result.state === undefined) return { events: result.events, meta: result.meta };\n return result;\n }\n if (operation._tag === \"channelCheckAccess\") {\n return yield* runtime.checkAccessAgentChannel({\n channelId: operation.channelId,\n definitionSettings: operation.definitionSettings,\n deploymentSettings: operation.deploymentSettings,\n identity: operation.identity,\n ...connectionId,\n });\n }\n if (operation._tag === \"channelExecute\") {\n return yield* runtime.executeAgentChannel({\n channelId: operation.channelId,\n command: operation.command,\n definitionSettings: operation.definitionSettings,\n deploymentSettings: operation.deploymentSettings,\n ...connectionId,\n });\n }\n\n return yield* runtime.executeAuthJson(operation);\n },\n Effect.mapError(error => (Schema.is(Failure)(error) ? error : failure(error))),\n);\n\n/** Execute only in the guest after importing and building its installed plugin. */\nexport const execute = Effect.fn(\"RemoteRuntime.execute\")(function* (request: Request) {\n // The guest runner supplies its fetch client; a host calling in-process has no file routes to reach.\n const http = yield* Effect.serviceOption(HttpClient.HttpClient);\n if (request.identity.organizationId !== request.context.tenant.organizationId) {\n return {\n _tag: \"failure\",\n error: {\n category: \"protocol\",\n code: \"OrganizationMismatch\",\n message: \"Invocation organization does not match its context\",\n retryable: false,\n },\n identity: request.identity,\n } satisfies Response;\n }\n return yield* pipe(\n run(request),\n Effect.provideService(ConnectionResolver.Service, connectionService(request)),\n Effect.provideService(\n Files.Service,\n pipe(\n Option.fromUndefinedOr(request.files),\n Option.flatMap(access => Option.map(http, client => filesService(access, client))),\n Option.getOrElse(() => unavailableFiles),\n ),\n ),\n Effect.flatMap(\n Effect.fnUntraced(function* (value) {\n if (value === undefined) {\n return { _tag: \"success\", identity: request.identity } satisfies Response;\n }\n return {\n _tag: \"success\",\n identity: request.identity,\n value: yield* pipe(\n Schema.decodeUnknownEffect(Schema.Json)(value),\n Effect.mapError(failure),\n ),\n } satisfies Response;\n }),\n ),\n Effect.catch(error =>\n Effect.succeed({ _tag: \"failure\", error, identity: request.identity } satisfies Response),\n ),\n Effect.catchCauseIf(\n cause => !Cause.hasInterrupts(cause),\n () =>\n Effect.succeed({\n _tag: \"failure\",\n error: {\n category: \"handler\",\n code: \"PluginDefect\",\n message: \"Plugin operation failed\",\n retryable: false,\n },\n identity: request.identity,\n } satisfies Response),\n ),\n );\n});\n\nexport * as RemoteRuntime from \"./remote-runtime.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,WAAW,OAAO,OAAO;CACpC,gBAAgB,OAAO,OAAO,MAAM,OAAO,UAAU,kBAAkB,CAAC;CACxE,cAAc,OAAO;CACrB,gBAAgB,OAAO;CACvB,WAAW,OAAO;CAClB,eAAe,OAAO;AACxB,CAAC;AAED,MAAM,aAAa,OAAO,OAAO;CAC/B,cAAc,OAAO;CACrB,UAAU,OAAO;CACjB,UAAU,OAAO;CACjB,YAAY,OAAO;CACnB,OAAO,OAAO,YAAY,OAAO,IAAI;AACvC,CAAC;AACD,MAAM,UAAU,OAAO,OAAO;CAC5B,OAAO,OAAO,MAAM,CAClB,OAAO,OAAO;EAAE,MAAM,OAAO,QAAQ,MAAM;EAAG,QAAQ,OAAO;CAAe,CAAC,GAC7E,OAAO,OAAO;EAAE,MAAM,OAAO,QAAQ,QAAQ;EAAG,QAAQ,OAAO,YAAY,OAAO,MAAM;CAAE,CAAC,CAC7F,CAAC;CACD,UAAU,OAAO,YAAY,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI,CAAC;CACtE,QAAQ,OAAO,OAAO;EACpB,MAAM,OAAO;EACb,UAAU,OAAO,YAAY,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI,CAAC;EACtE,WAAW,OAAO,YAAY,OAAO,MAAM;CAC7C,CAAC;CACD,QAAQ,OAAO,OAAO;EAAE,gBAAgB,OAAO;EAAgB,QAAQ,OAAO;CAAe,CAAC;AAChG,CAAC;AACD,MAAM,UAAU;CACd,QAAQ,OAAO;CACf,OAAO,OAAO,YAAY,OAAO,IAAI;CACrC,WAAW,OAAO;AACpB;AACA,MAAM,UAAU;CAAE,GAAG;CAAS,YAAY,OAAO;AAAO;AACxD,MAAM,UAAU;CACd,WAAW,OAAO;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AO;GACL,MAAM;GACN,UAAU,QAAQ;GAClB,OAAO,OAAO,KACZ,OAAO,oBAAoB,OAAO,IAAI,CAAC,CAAC,KAAK,GAC7C,OAAO,SAAS,OAAO,CACzB;EACF;CACF,CAAC,CACH,GACA,OAAO,OAAM,UACX,OAAO,QAAQ;EAAE,MAAM;EAAW;EAAO,UAAU,QAAQ;CAAS,CAAoB,CAC1F,GACA,OAAO,cACL,UAAS,CAAC,MAAM,cAAc,KAAK,SAEjC,OAAO,QAAQ;EACb,MAAM;EACN,OAAO;GACL,UAAU;GACV,MAAM;GACN,SAAS;GACT,WAAW;EACb;EACA,UAAU,QAAQ;CACpB,CAAoB,CACxB,CACF;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dual-os/sdk",
3
- "version": "0.9.2",
3
+ "version": "0.10.0",
4
4
  "license": "UNLICENSED",
5
5
  "files": [
6
6
  "dist/**/*.js",
@@ -3,9 +3,9 @@ import type { Context, Effect, Pipeable, SchemaAST } from "effect";
3
3
  import { Match, Predicate, Schema } from "effect";
4
4
 
5
5
  import * as AuthMethod from "./AuthMethod.ts";
6
+ import { Files } from "./Files.ts";
6
7
  import { validateIdentifier } from "./internal/identifier.ts";
7
8
  import { PipeableProto } from "./internal/proto.ts";
8
- import * as ToolFile from "./ToolFile.ts";
9
9
 
10
10
  export const TypeId = "@dual-os/sdk/AgentChannel" as const;
11
11
  export type TypeId = typeof TypeId;
@@ -307,11 +307,8 @@ export const ContextMessage = Schema.Struct({
307
307
  export type ContextMessage = typeof ContextMessage.Type;
308
308
 
309
309
  /** Decoded originals are limited separately by the host; ordinary command JSON stays bounded. */
310
- export const AssetFile = ToolFile.Schema.check(
311
- Schema.makeFilter(
312
- file =>
313
- file.sizeBytes > 0 && file.sizeBytes <= 10_485_760 && file.contentBase64.length <= 13_981_016,
314
- ),
310
+ export const AssetFile = Files.File.check(
311
+ Schema.makeFilter(file => file.sizeBytes > 0 && file.sizeBytes <= 10_485_760),
315
312
  );
316
313
 
317
314
  /** Closed error vocabulary: provider messages, payloads, and causes never cross this seam. */
package/src/Files.ts CHANGED
@@ -36,7 +36,7 @@ export class FileError extends Schema.TaggedError<FileError>()("FileError", {
36
36
  }) {}
37
37
 
38
38
  /**
39
- * Reads and stores files for the caller of an action: a workflow run, or the person in a chat.
39
+ * Reads and stores files for the caller of an action, trigger or channel operation.
40
40
  *
41
41
  * @since 0.1.0
42
42
  * @category services
@@ -59,7 +59,7 @@ const service = pipe(
59
59
  Effect.serviceOption(Service),
60
60
  Effect.flatMap(
61
61
  Effect.fromOption(() =>
62
- FileError.make({ message: "Files are only available when Dual calls the action" }),
62
+ FileError.make({ message: "Files are only available during a Dual plugin invocation" }),
63
63
  ),
64
64
  ),
65
65
  );